babylon.viewer.max.js 6.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494
  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 = 15);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(18); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(19); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(20); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. if (x === void 0) { x = 0; }
  2299. if (y === void 0) { y = 0; }
  2300. this.x = x;
  2301. this.y = y;
  2302. }
  2303. /**
  2304. * Gets a string with the Vector2 coordinates
  2305. * @returns a string with the Vector2 coordinates
  2306. */
  2307. Vector2.prototype.toString = function () {
  2308. return "{X: " + this.x + " Y:" + this.y + "}";
  2309. };
  2310. /**
  2311. * Gets class name
  2312. * @returns the string "Vector2"
  2313. */
  2314. Vector2.prototype.getClassName = function () {
  2315. return "Vector2";
  2316. };
  2317. /**
  2318. * Gets current vector hash code
  2319. * @returns the Vector2 hash code as a number
  2320. */
  2321. Vector2.prototype.getHashCode = function () {
  2322. var hash = this.x || 0;
  2323. hash = (hash * 397) ^ (this.y || 0);
  2324. return hash;
  2325. };
  2326. // Operators
  2327. /**
  2328. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2329. * @param array defines the source array
  2330. * @param index defines the offset in source array
  2331. * @returns the current Vector2
  2332. */
  2333. Vector2.prototype.toArray = function (array, index) {
  2334. if (index === void 0) { index = 0; }
  2335. array[index] = this.x;
  2336. array[index + 1] = this.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Copy the current vector to an array
  2341. * @returns a new array with 2 elements: the Vector2 coordinates.
  2342. */
  2343. Vector2.prototype.asArray = function () {
  2344. var result = new Array();
  2345. this.toArray(result, 0);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2350. * @param source defines the source Vector2
  2351. * @returns the current updated Vector2
  2352. */
  2353. Vector2.prototype.copyFrom = function (source) {
  2354. this.x = source.x;
  2355. this.y = source.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Sets the Vector2 coordinates with the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns the current updated Vector2
  2363. */
  2364. Vector2.prototype.copyFromFloats = function (x, y) {
  2365. this.x = x;
  2366. this.y = y;
  2367. return this;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the given floats
  2371. * @param x defines the first coordinate
  2372. * @param y defines the second coordinate
  2373. * @returns the current updated Vector2
  2374. */
  2375. Vector2.prototype.set = function (x, y) {
  2376. return this.copyFromFloats(x, y);
  2377. };
  2378. /**
  2379. * Add another vector with the current one
  2380. * @param otherVector defines the other vector
  2381. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2382. */
  2383. Vector2.prototype.add = function (otherVector) {
  2384. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2385. };
  2386. /**
  2387. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2388. * @param otherVector defines the other vector
  2389. * @param result defines the target vector
  2390. * @returns the unmodified current Vector2
  2391. */
  2392. Vector2.prototype.addToRef = function (otherVector, result) {
  2393. result.x = this.x + otherVector.x;
  2394. result.y = this.y + otherVector.y;
  2395. return this;
  2396. };
  2397. /**
  2398. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2399. * @param otherVector defines the other vector
  2400. * @returns the current updated Vector2
  2401. */
  2402. Vector2.prototype.addInPlace = function (otherVector) {
  2403. this.x += otherVector.x;
  2404. this.y += otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2409. * @param otherVector defines the other vector
  2410. * @returns a new Vector2
  2411. */
  2412. Vector2.prototype.addVector3 = function (otherVector) {
  2413. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2414. };
  2415. /**
  2416. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2417. * @param otherVector defines the other vector
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.subtract = function (otherVector) {
  2421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2422. };
  2423. /**
  2424. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2425. * @param otherVector defines the other vector
  2426. * @param result defines the target vector
  2427. * @returns the unmodified current Vector2
  2428. */
  2429. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2430. result.x = this.x - otherVector.x;
  2431. result.y = this.y - otherVector.y;
  2432. return this;
  2433. };
  2434. /**
  2435. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.subtractInPlace = function (otherVector) {
  2440. this.x -= otherVector.x;
  2441. this.y -= otherVector.y;
  2442. return this;
  2443. };
  2444. /**
  2445. * Multiplies in place the current Vector2 coordinates by the given ones
  2446. * @param otherVector defines the other vector
  2447. * @returns the current updated Vector2
  2448. */
  2449. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2450. this.x *= otherVector.x;
  2451. this.y *= otherVector.y;
  2452. return this;
  2453. };
  2454. /**
  2455. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2456. * @param otherVector defines the other vector
  2457. * @returns a new Vector2
  2458. */
  2459. Vector2.prototype.multiply = function (otherVector) {
  2460. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2461. };
  2462. /**
  2463. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2464. * @param otherVector defines the other vector
  2465. * @param result defines the target vector
  2466. * @returns the unmodified current Vector2
  2467. */
  2468. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2469. result.x = this.x * otherVector.x;
  2470. result.y = this.y * otherVector.y;
  2471. return this;
  2472. };
  2473. /**
  2474. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2475. * @param x defines the first coordinate
  2476. * @param y defines the second coordinate
  2477. * @returns a new Vector2
  2478. */
  2479. Vector2.prototype.multiplyByFloats = function (x, y) {
  2480. return new Vector2(this.x * x, this.y * y);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2484. * @param otherVector defines the other vector
  2485. * @returns a new Vector2
  2486. */
  2487. Vector2.prototype.divide = function (otherVector) {
  2488. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2489. };
  2490. /**
  2491. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2492. * @param otherVector defines the other vector
  2493. * @param result defines the target vector
  2494. * @returns the unmodified current Vector2
  2495. */
  2496. Vector2.prototype.divideToRef = function (otherVector, result) {
  2497. result.x = this.x / otherVector.x;
  2498. result.y = this.y / otherVector.y;
  2499. return this;
  2500. };
  2501. /**
  2502. * Divides the current Vector3 coordinates by the given ones
  2503. * @param otherVector defines the other vector
  2504. * @returns the current updated Vector2
  2505. */
  2506. Vector2.prototype.divideInPlace = function (otherVector) {
  2507. return this.divideToRef(otherVector, this);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 with current Vector2 negated coordinates
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.prototype.negate = function () {
  2514. return new Vector2(-this.x, -this.y);
  2515. };
  2516. /**
  2517. * Multiply the Vector2 coordinates by scale
  2518. * @param scale defines the scaling factor
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.scaleInPlace = function (scale) {
  2522. this.x *= scale;
  2523. this.y *= scale;
  2524. return this;
  2525. };
  2526. /**
  2527. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2528. * @param scale defines the scaling factor
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.scale = function (scale) {
  2532. var result = new Vector2(0, 0);
  2533. this.scaleToRef(scale, result);
  2534. return result;
  2535. };
  2536. /**
  2537. * Scale the current Vector2 values by a factor to a given Vector2
  2538. * @param scale defines the scale factor
  2539. * @param result defines the Vector2 object where to store the result
  2540. * @returns the unmodified current Vector2
  2541. */
  2542. Vector2.prototype.scaleToRef = function (scale, result) {
  2543. result.x = this.x * scale;
  2544. result.y = this.y * scale;
  2545. return this;
  2546. };
  2547. /**
  2548. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2549. * @param scale defines the scale factor
  2550. * @param result defines the Vector2 object where to store the result
  2551. * @returns the unmodified current Vector2
  2552. */
  2553. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2554. result.x += this.x * scale;
  2555. result.y += this.y * scale;
  2556. return this;
  2557. };
  2558. /**
  2559. * Gets a boolean if two vectors are equals
  2560. * @param otherVector defines the other vector
  2561. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2562. */
  2563. Vector2.prototype.equals = function (otherVector) {
  2564. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2565. };
  2566. /**
  2567. * Gets a boolean if two vectors are equals (using an epsilon value)
  2568. * @param otherVector defines the other vector
  2569. * @param epsilon defines the minimal distance to consider equality
  2570. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2571. */
  2572. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2573. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2574. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. // Properties
  3218. /**
  3219. * Gets the length of the Vector3
  3220. * @returns the length of the Vecto3
  3221. */
  3222. Vector3.prototype.length = function () {
  3223. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Gets the squared length of the Vector3
  3227. * @returns squared length of the Vector3
  3228. */
  3229. Vector3.prototype.lengthSquared = function () {
  3230. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3231. };
  3232. /**
  3233. * Normalize the current Vector3.
  3234. * Please note that this is an in place operation.
  3235. * @returns the current updated Vector3
  3236. */
  3237. Vector3.prototype.normalize = function () {
  3238. var len = this.length();
  3239. if (len === 0 || len === 1.0)
  3240. return this;
  3241. var num = 1.0 / len;
  3242. this.x *= num;
  3243. this.y *= num;
  3244. this.z *= num;
  3245. return this;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to a new vector
  3249. * @returns the new Vector3
  3250. */
  3251. Vector3.prototype.normalizeToNew = function () {
  3252. var normalized = new Vector3(0, 0, 0);
  3253. this.normalizeToRef(normalized);
  3254. return normalized;
  3255. };
  3256. /**
  3257. * Normalize the current Vector3 to the reference
  3258. * @param reference define the Vector3 to update
  3259. * @returns the updated Vector3
  3260. */
  3261. Vector3.prototype.normalizeToRef = function (reference) {
  3262. var len = this.length();
  3263. if (len === 0 || len === 1.0) {
  3264. reference.set(this.x, this.y, this.z);
  3265. return reference;
  3266. }
  3267. var scale = 1.0 / len;
  3268. this.scaleToRef(scale, reference);
  3269. return reference;
  3270. };
  3271. /**
  3272. * Creates a new Vector3 copied from the current Vector3
  3273. * @returns the new Vector3
  3274. */
  3275. Vector3.prototype.clone = function () {
  3276. return new Vector3(this.x, this.y, this.z);
  3277. };
  3278. /**
  3279. * Copies the given vector coordinates to the current Vector3 ones
  3280. * @param source defines the source Vector3
  3281. * @returns the current updated Vector3
  3282. */
  3283. Vector3.prototype.copyFrom = function (source) {
  3284. this.x = source.x;
  3285. this.y = source.y;
  3286. this.z = source.z;
  3287. return this;
  3288. };
  3289. /**
  3290. * Copies the given floats to the current Vector3 coordinates
  3291. * @param x defines the x coordinate of the operand
  3292. * @param y defines the y coordinate of the operand
  3293. * @param z defines the z coordinate of the operand
  3294. * @returns the current updated Vector3
  3295. */
  3296. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3297. this.x = x;
  3298. this.y = y;
  3299. this.z = z;
  3300. return this;
  3301. };
  3302. /**
  3303. * Copies the given floats to the current Vector3 coordinates
  3304. * @param x defines the x coordinate of the operand
  3305. * @param y defines the y coordinate of the operand
  3306. * @param z defines the z coordinate of the operand
  3307. * @returns the current updated Vector3
  3308. */
  3309. Vector3.prototype.set = function (x, y, z) {
  3310. return this.copyFromFloats(x, y, z);
  3311. };
  3312. // Statics
  3313. /**
  3314. * Get the clip factor between two vectors
  3315. * @param vector0 defines the first operand
  3316. * @param vector1 defines the second operand
  3317. * @param axis defines the axis to use
  3318. * @param size defines the size along the axis
  3319. * @returns the clip factor
  3320. */
  3321. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3322. var d0 = Vector3.Dot(vector0, axis) - size;
  3323. var d1 = Vector3.Dot(vector1, axis) - size;
  3324. var s = d0 / (d0 - d1);
  3325. return s;
  3326. };
  3327. /**
  3328. * Get angle between two vectors
  3329. * @param vector0 angle between vector0 and vector1
  3330. * @param vector1 angle between vector0 and vector1
  3331. * @param normal direction of the normal
  3332. * @return the angle between vector0 and vector1
  3333. */
  3334. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3335. var v0 = vector0.clone().normalize();
  3336. var v1 = vector1.clone().normalize();
  3337. var dot = Vector3.Dot(v0, v1);
  3338. var n = Vector3.Cross(v0, v1);
  3339. if (Vector3.Dot(n, normal) > 0) {
  3340. return Math.acos(dot);
  3341. }
  3342. return -Math.acos(dot);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @returns the new Vector3
  3349. */
  3350. Vector3.FromArray = function (array, offset) {
  3351. if (!offset) {
  3352. offset = 0;
  3353. }
  3354. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3355. };
  3356. /**
  3357. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3358. * This function is deprecated. Use FromArray instead
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.FromFloatArray = function (array, offset) {
  3364. return Vector3.FromArray(array, offset);
  3365. };
  3366. /**
  3367. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromArrayToRef = function (array, offset, result) {
  3373. result.x = array[offset];
  3374. result.y = array[offset + 1];
  3375. result.z = array[offset + 2];
  3376. };
  3377. /**
  3378. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3379. * This function is deprecated. Use FromArrayToRef instead.
  3380. * @param array defines the source array
  3381. * @param offset defines the offset in the source array
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3385. return Vector3.FromArrayToRef(array, offset, result);
  3386. };
  3387. /**
  3388. * Sets the given vector "result" with the given floats.
  3389. * @param x defines the x coordinate of the source
  3390. * @param y defines the y coordinate of the source
  3391. * @param z defines the z coordinate of the source
  3392. * @param result defines the Vector3 where to store the result
  3393. */
  3394. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3395. result.x = x;
  3396. result.y = y;
  3397. result.z = z;
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3401. * @returns a new empty Vector3
  3402. */
  3403. Vector3.Zero = function () {
  3404. return new Vector3(0.0, 0.0, 0.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3408. * @returns a new unit Vector3
  3409. */
  3410. Vector3.One = function () {
  3411. return new Vector3(1.0, 1.0, 1.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3415. * @returns a new up Vector3
  3416. */
  3417. Vector3.Up = function () {
  3418. return new Vector3(0.0, 1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3422. * @returns a new down Vector3
  3423. */
  3424. Vector3.Down = function () {
  3425. return new Vector3(0.0, -1.0, 0.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3429. * @returns a new forward Vector3
  3430. */
  3431. Vector3.Forward = function () {
  3432. return new Vector3(0.0, 0.0, 1.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3436. * @returns a new right Vector3
  3437. */
  3438. Vector3.Right = function () {
  3439. return new Vector3(1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3443. * @returns a new left Vector3
  3444. */
  3445. Vector3.Left = function () {
  3446. return new Vector3(-1.0, 0.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @returns the transformed Vector3
  3454. */
  3455. Vector3.TransformCoordinates = function (vector, transformation) {
  3456. var result = Vector3.Zero();
  3457. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3458. return result;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @param result defines the Vector3 where to store the result
  3466. */
  3467. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3468. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3469. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3470. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3471. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3472. result.x = x / w;
  3473. result.y = y / w;
  3474. result.z = z / w;
  3475. };
  3476. /**
  3477. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3478. * This method computes tranformed coordinates only, not transformed direction vectors
  3479. * @param x define the x coordinate of the source vector
  3480. * @param y define the y coordinate of the source vector
  3481. * @param z define the z coordinate of the source vector
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3490. result.x = rx / rw;
  3491. result.y = ry / rw;
  3492. result.z = rz / rw;
  3493. };
  3494. /**
  3495. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.TransformNormal = function (vector, transformation) {
  3502. var result = Vector3.Zero();
  3503. Vector3.TransformNormalToRef(vector, transformation, result);
  3504. return result;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3514. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3515. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3516. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3517. result.x = x;
  3518. result.y = y;
  3519. result.z = z;
  3520. };
  3521. /**
  3522. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3523. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3524. * @param x define the x coordinate of the source vector
  3525. * @param y define the y coordinate of the source vector
  3526. * @param z define the z coordinate of the source vector
  3527. * @param transformation defines the transformation matrix
  3528. * @param result defines the Vector3 where to store the result
  3529. */
  3530. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3531. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3532. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3533. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3537. * @param value1 defines the first control point
  3538. * @param value2 defines the second control point
  3539. * @param value3 defines the third control point
  3540. * @param value4 defines the fourth control point
  3541. * @param amount defines the amount on the spline to use
  3542. * @returns the new Vector3
  3543. */
  3544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3545. var squared = amount * amount;
  3546. var cubed = amount * squared;
  3547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3556. return new Vector3(x, y, z);
  3557. };
  3558. /**
  3559. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3562. * @param value defines the current value
  3563. * @param min defines the lower range value
  3564. * @param max defines the upper range value
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Clamp = function (value, min, max) {
  3568. var x = value.x;
  3569. x = (x > max.x) ? max.x : x;
  3570. x = (x < min.x) ? min.x : x;
  3571. var y = value.y;
  3572. y = (y > max.y) ? max.y : y;
  3573. y = (y < min.y) ? min.y : y;
  3574. var z = value.z;
  3575. z = (z > max.z) ? max.z : z;
  3576. z = (z < min.z) ? min.z : z;
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3581. * @param value1 defines the first control point
  3582. * @param tangent1 defines the first tangent vector
  3583. * @param value2 defines the second control point
  3584. * @param tangent2 defines the second tangent vector
  3585. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3589. var squared = amount * amount;
  3590. var cubed = amount * squared;
  3591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3593. var part3 = (cubed - (2.0 * squared)) + amount;
  3594. var part4 = cubed - squared;
  3595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @returns the new Vector3
  3606. */
  3607. Vector3.Lerp = function (start, end, amount) {
  3608. var result = new Vector3(0, 0, 0);
  3609. Vector3.LerpToRef(start, end, amount, result);
  3610. return result;
  3611. };
  3612. /**
  3613. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.LerpToRef = function (start, end, amount, result) {
  3620. result.x = start.x + ((end.x - start.x) * amount);
  3621. result.y = start.y + ((end.y - start.y) * amount);
  3622. result.z = start.z + ((end.z - start.z) * amount);
  3623. };
  3624. /**
  3625. * Returns the dot product (float) between the vectors "left" and "right"
  3626. * @param left defines the left operand
  3627. * @param right defines the right operand
  3628. * @returns the dot product
  3629. */
  3630. Vector3.Dot = function (left, right) {
  3631. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3632. };
  3633. /**
  3634. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @returns the cross product
  3639. */
  3640. Vector3.Cross = function (left, right) {
  3641. var result = Vector3.Zero();
  3642. Vector3.CrossToRef(left, right, result);
  3643. return result;
  3644. };
  3645. /**
  3646. * Sets the given vector "result" with the cross product of "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @param result defines the Vector3 where to store the result
  3651. */
  3652. Vector3.CrossToRef = function (left, right, result) {
  3653. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3654. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3655. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3656. result.copyFrom(MathTmp.Vector3[0]);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 as the normalization of the given vector
  3660. * @param vector defines the Vector3 to normalize
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Normalize = function (vector) {
  3664. var result = Vector3.Zero();
  3665. Vector3.NormalizeToRef(vector, result);
  3666. return result;
  3667. };
  3668. /**
  3669. * Sets the given vector "result" with the normalization of the given first vector
  3670. * @param vector defines the Vector3 to normalize
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.NormalizeToRef = function (vector, result) {
  3674. result.copyFrom(vector);
  3675. result.normalize();
  3676. };
  3677. /**
  3678. * Project a Vector3 onto screen space
  3679. * @param vector defines the Vector3 to project
  3680. * @param world defines the world matrix to use
  3681. * @param transform defines the transform (view x projection) matrix to use
  3682. * @param viewport defines the screen viewport to use
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Project = function (vector, world, transform, viewport) {
  3686. var cw = viewport.width;
  3687. var ch = viewport.height;
  3688. var cx = viewport.x;
  3689. var cy = viewport.y;
  3690. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3691. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.multiplyToRef(viewportMatrix, matrix);
  3695. return Vector3.TransformCoordinates(vector, matrix);
  3696. };
  3697. /**
  3698. * Unproject from screen space to object space
  3699. * @param source defines the screen space Vector3 to use
  3700. * @param viewportWidth defines the current width of the viewport
  3701. * @param viewportHeight defines the current height of the viewport
  3702. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3703. * @param transform defines the transform (view x projection) matrix to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3707. var matrix = MathTmp.Matrix[0];
  3708. world.multiplyToRef(transform, matrix);
  3709. matrix.invert();
  3710. source.x = source.x / viewportWidth * 2 - 1;
  3711. source.y = -(source.y / viewportHeight * 2 - 1);
  3712. var vector = Vector3.TransformCoordinates(source, matrix);
  3713. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3714. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3715. vector = vector.scale(1.0 / num);
  3716. }
  3717. return vector;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3730. var result = Vector3.Zero();
  3731. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3732. return result;
  3733. };
  3734. /**
  3735. * Unproject from screen space to object space
  3736. * @param source defines the screen space Vector3 to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3746. };
  3747. /**
  3748. * Unproject from screen space to object space
  3749. * @param sourceX defines the screen space x coordinate to use
  3750. * @param sourceY defines the screen space y coordinate to use
  3751. * @param sourceZ defines the screen space z coordinate to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param view defines the view matrix to use
  3756. * @param projection defines the projection matrix to use
  3757. * @param result defines the Vector3 where to store the result
  3758. */
  3759. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3760. var matrix = MathTmp.Matrix[0];
  3761. world.multiplyToRef(view, matrix);
  3762. matrix.multiplyToRef(projection, matrix);
  3763. matrix.invert();
  3764. var screenSource = MathTmp.Vector3[0];
  3765. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3766. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3767. screenSource.z = 2 * sourceZ - 1.0;
  3768. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3769. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3770. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3771. result.scaleInPlace(1.0 / num);
  3772. }
  3773. };
  3774. /**
  3775. * Gets the minimal coordinate values between two Vector3
  3776. * @param left defines the first operand
  3777. * @param right defines the second operand
  3778. * @returns the new Vector3
  3779. */
  3780. Vector3.Minimize = function (left, right) {
  3781. var min = left.clone();
  3782. min.minimizeInPlace(right);
  3783. return min;
  3784. };
  3785. /**
  3786. * Gets the maximal coordinate values between two Vector3
  3787. * @param left defines the first operand
  3788. * @param right defines the second operand
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Maximize = function (left, right) {
  3792. var max = left.clone();
  3793. max.maximizeInPlace(right);
  3794. return max;
  3795. };
  3796. /**
  3797. * Returns the distance between the vectors "value1" and "value2"
  3798. * @param value1 defines the first operand
  3799. * @param value2 defines the second operand
  3800. * @returns the distance
  3801. */
  3802. Vector3.Distance = function (value1, value2) {
  3803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3804. };
  3805. /**
  3806. * Returns the squared distance between the vectors "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the squared distance
  3810. */
  3811. Vector3.DistanceSquared = function (value1, value2) {
  3812. var x = value1.x - value2.x;
  3813. var y = value1.y - value2.y;
  3814. var z = value1.z - value2.z;
  3815. return (x * x) + (y * y) + (z * z);
  3816. };
  3817. /**
  3818. * Returns a new Vector3 located at the center between "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the new Vector3
  3822. */
  3823. Vector3.Center = function (value1, value2) {
  3824. var center = value1.add(value2);
  3825. center.scaleInPlace(0.5);
  3826. return center;
  3827. };
  3828. /**
  3829. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3830. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3831. * to something in order to rotate it from its local system to the given target system
  3832. * Note: axis1, axis2 and axis3 are normalized during this operation
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @returns a new Vector3
  3837. */
  3838. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3839. var rotation = Vector3.Zero();
  3840. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3841. return rotation;
  3842. };
  3843. /**
  3844. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @param ref defines the Vector3 where to store the result
  3849. */
  3850. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3851. var quat = MathTmp.Quaternion[0];
  3852. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3853. quat.toEulerAnglesToRef(ref);
  3854. };
  3855. return Vector3;
  3856. }());
  3857. BABYLON.Vector3 = Vector3;
  3858. //Vector4 class created for EulerAngle class conversion to Quaternion
  3859. var Vector4 = /** @class */ (function () {
  3860. /**
  3861. * Creates a Vector4 object from the given floats.
  3862. */
  3863. function Vector4(x, y, z, w) {
  3864. this.x = x;
  3865. this.y = y;
  3866. this.z = z;
  3867. this.w = w;
  3868. }
  3869. /**
  3870. * Returns the string with the Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.toString = function () {
  3873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3874. };
  3875. /**
  3876. * Returns the string "Vector4".
  3877. */
  3878. Vector4.prototype.getClassName = function () {
  3879. return "Vector4";
  3880. };
  3881. /**
  3882. * Returns the Vector4 hash code.
  3883. */
  3884. Vector4.prototype.getHashCode = function () {
  3885. var hash = this.x || 0;
  3886. hash = (hash * 397) ^ (this.y || 0);
  3887. hash = (hash * 397) ^ (this.z || 0);
  3888. hash = (hash * 397) ^ (this.w || 0);
  3889. return hash;
  3890. };
  3891. // Operators
  3892. /**
  3893. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3894. */
  3895. Vector4.prototype.asArray = function () {
  3896. var result = new Array();
  3897. this.toArray(result, 0);
  3898. return result;
  3899. };
  3900. /**
  3901. * Populates the given array from the given index with the Vector4 coordinates.
  3902. * Returns the Vector4.
  3903. */
  3904. Vector4.prototype.toArray = function (array, index) {
  3905. if (index === undefined) {
  3906. index = 0;
  3907. }
  3908. array[index] = this.x;
  3909. array[index + 1] = this.y;
  3910. array[index + 2] = this.z;
  3911. array[index + 3] = this.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Adds the given vector to the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.addInPlace = function (otherVector) {
  3919. this.x += otherVector.x;
  3920. this.y += otherVector.y;
  3921. this.z += otherVector.z;
  3922. this.w += otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3927. */
  3928. Vector4.prototype.add = function (otherVector) {
  3929. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3930. };
  3931. /**
  3932. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.addToRef = function (otherVector, result) {
  3936. result.x = this.x + otherVector.x;
  3937. result.y = this.y + otherVector.y;
  3938. result.z = this.z + otherVector.z;
  3939. result.w = this.w + otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Subtract in place the given vector from the current Vector4.
  3944. * Returns the updated Vector4.
  3945. */
  3946. Vector4.prototype.subtractInPlace = function (otherVector) {
  3947. this.x -= otherVector.x;
  3948. this.y -= otherVector.y;
  3949. this.z -= otherVector.z;
  3950. this.w -= otherVector.w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3955. */
  3956. Vector4.prototype.subtract = function (otherVector) {
  3957. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3958. };
  3959. /**
  3960. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3961. * Returns the current Vector4.
  3962. */
  3963. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3964. result.x = this.x - otherVector.x;
  3965. result.y = this.y - otherVector.y;
  3966. result.z = this.z - otherVector.z;
  3967. result.w = this.w - otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3972. */
  3973. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3974. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3981. result.x = this.x - x;
  3982. result.y = this.y - y;
  3983. result.z = this.z - z;
  3984. result.w = this.w - w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3989. */
  3990. Vector4.prototype.negate = function () {
  3991. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3992. };
  3993. /**
  3994. * Multiplies the current Vector4 coordinates by scale (float).
  3995. * Returns the updated Vector4.
  3996. */
  3997. Vector4.prototype.scaleInPlace = function (scale) {
  3998. this.x *= scale;
  3999. this.y *= scale;
  4000. this.z *= scale;
  4001. this.w *= scale;
  4002. return this;
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4006. */
  4007. Vector4.prototype.scale = function (scale) {
  4008. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4009. };
  4010. /**
  4011. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.scaleToRef = function (scale, result) {
  4015. result.x = this.x * scale;
  4016. result.y = this.y * scale;
  4017. result.z = this.z * scale;
  4018. result.w = this.w * scale;
  4019. return this;
  4020. };
  4021. /**
  4022. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4023. * @param scale defines the scale factor
  4024. * @param result defines the Vector4 object where to store the result
  4025. * @returns the unmodified current Vector4
  4026. */
  4027. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4028. result.x += this.x * scale;
  4029. result.y += this.y * scale;
  4030. result.z += this.z * scale;
  4031. result.w += this.w * scale;
  4032. return this;
  4033. };
  4034. /**
  4035. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4036. */
  4037. Vector4.prototype.equals = function (otherVector) {
  4038. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4039. };
  4040. /**
  4041. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4042. */
  4043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4044. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4045. return otherVector
  4046. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4047. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4048. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4049. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4050. };
  4051. /**
  4052. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4055. return this.x === x && this.y === y && this.z === z && this.w === w;
  4056. };
  4057. /**
  4058. * Multiplies in place the current Vector4 by the given one.
  4059. * Returns the updated Vector4.
  4060. */
  4061. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4062. this.x *= otherVector.x;
  4063. this.y *= otherVector.y;
  4064. this.z *= otherVector.z;
  4065. this.w *= otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4070. */
  4071. Vector4.prototype.multiply = function (otherVector) {
  4072. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4073. };
  4074. /**
  4075. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4076. * Returns the current Vector4.
  4077. */
  4078. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4079. result.x = this.x * otherVector.x;
  4080. result.y = this.y * otherVector.y;
  4081. result.z = this.z * otherVector.z;
  4082. result.w = this.w * otherVector.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4087. */
  4088. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4089. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4093. */
  4094. Vector4.prototype.divide = function (otherVector) {
  4095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4096. };
  4097. /**
  4098. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4099. * Returns the current Vector4.
  4100. */
  4101. Vector4.prototype.divideToRef = function (otherVector, result) {
  4102. result.x = this.x / otherVector.x;
  4103. result.y = this.y / otherVector.y;
  4104. result.z = this.z / otherVector.z;
  4105. result.w = this.w / otherVector.w;
  4106. return this;
  4107. };
  4108. /**
  4109. * Divides the current Vector3 coordinates by the given ones.
  4110. * @returns the updated Vector3.
  4111. */
  4112. Vector4.prototype.divideInPlace = function (otherVector) {
  4113. return this.divideToRef(otherVector, this);
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.minimizeInPlace = function (other) {
  4121. if (other.x < this.x)
  4122. this.x = other.x;
  4123. if (other.y < this.y)
  4124. this.y = other.y;
  4125. if (other.z < this.z)
  4126. this.z = other.z;
  4127. if (other.w < this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4133. * @param other defines the second operand
  4134. * @returns the current updated Vector4
  4135. */
  4136. Vector4.prototype.maximizeInPlace = function (other) {
  4137. if (other.x > this.x)
  4138. this.x = other.x;
  4139. if (other.y > this.y)
  4140. this.y = other.y;
  4141. if (other.z > this.z)
  4142. this.z = other.z;
  4143. if (other.w > this.w)
  4144. this.w = other.w;
  4145. return this;
  4146. };
  4147. // Properties
  4148. /**
  4149. * Returns the Vector4 length (float).
  4150. */
  4151. Vector4.prototype.length = function () {
  4152. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4153. };
  4154. /**
  4155. * Returns the Vector4 squared length (float).
  4156. */
  4157. Vector4.prototype.lengthSquared = function () {
  4158. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4159. };
  4160. // Methods
  4161. /**
  4162. * Normalizes in place the Vector4.
  4163. * Returns the updated Vector4.
  4164. */
  4165. Vector4.prototype.normalize = function () {
  4166. var len = this.length();
  4167. if (len === 0)
  4168. return this;
  4169. var num = 1.0 / len;
  4170. this.x *= num;
  4171. this.y *= num;
  4172. this.z *= num;
  4173. this.w *= num;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4178. */
  4179. Vector4.prototype.toVector3 = function () {
  4180. return new Vector3(this.x, this.y, this.z);
  4181. };
  4182. /**
  4183. * Returns a new Vector4 copied from the current one.
  4184. */
  4185. Vector4.prototype.clone = function () {
  4186. return new Vector4(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Vector4 with the given one coordinates.
  4190. * Returns the updated Vector4.
  4191. */
  4192. Vector4.prototype.copyFrom = function (source) {
  4193. this.x = source.x;
  4194. this.y = source.y;
  4195. this.z = source.z;
  4196. this.w = source.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Vector4 coordinates with the given floats.
  4201. * Returns the updated Vector4.
  4202. */
  4203. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Vector4 coordinates with the given floats.
  4212. * Returns the updated Vector4.
  4213. */
  4214. Vector4.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. // Statics
  4218. /**
  4219. * Returns a new Vector4 set from the starting index of the given array.
  4220. */
  4221. Vector4.FromArray = function (array, offset) {
  4222. if (!offset) {
  4223. offset = 0;
  4224. }
  4225. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4226. };
  4227. /**
  4228. * Updates the given vector "result" from the starting index of the given array.
  4229. */
  4230. Vector4.FromArrayToRef = function (array, offset, result) {
  4231. result.x = array[offset];
  4232. result.y = array[offset + 1];
  4233. result.z = array[offset + 2];
  4234. result.w = array[offset + 3];
  4235. };
  4236. /**
  4237. * Updates the given vector "result" from the starting index of the given Float32Array.
  4238. */
  4239. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4240. Vector4.FromArrayToRef(array, offset, result);
  4241. };
  4242. /**
  4243. * Updates the given vector "result" coordinates from the given floats.
  4244. */
  4245. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = w;
  4250. };
  4251. /**
  4252. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4253. */
  4254. Vector4.Zero = function () {
  4255. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4256. };
  4257. /**
  4258. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4259. */
  4260. Vector4.One = function () {
  4261. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4262. };
  4263. /**
  4264. * Returns a new normalized Vector4 from the given one.
  4265. */
  4266. Vector4.Normalize = function (vector) {
  4267. var result = Vector4.Zero();
  4268. Vector4.NormalizeToRef(vector, result);
  4269. return result;
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the normalization of the given one.
  4273. */
  4274. Vector4.NormalizeToRef = function (vector, result) {
  4275. result.copyFrom(vector);
  4276. result.normalize();
  4277. };
  4278. Vector4.Minimize = function (left, right) {
  4279. var min = left.clone();
  4280. min.minimizeInPlace(right);
  4281. return min;
  4282. };
  4283. Vector4.Maximize = function (left, right) {
  4284. var max = left.clone();
  4285. max.maximizeInPlace(right);
  4286. return max;
  4287. };
  4288. /**
  4289. * Returns the distance (float) between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Distance = function (value1, value2) {
  4292. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4293. };
  4294. /**
  4295. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4296. */
  4297. Vector4.DistanceSquared = function (value1, value2) {
  4298. var x = value1.x - value2.x;
  4299. var y = value1.y - value2.y;
  4300. var z = value1.z - value2.z;
  4301. var w = value1.w - value2.w;
  4302. return (x * x) + (y * y) + (z * z) + (w * w);
  4303. };
  4304. /**
  4305. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4306. */
  4307. Vector4.Center = function (value1, value2) {
  4308. var center = value1.add(value2);
  4309. center.scaleInPlace(0.5);
  4310. return center;
  4311. };
  4312. /**
  4313. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4314. * This methods computes transformed normalized direction vectors only.
  4315. */
  4316. Vector4.TransformNormal = function (vector, transformation) {
  4317. var result = Vector4.Zero();
  4318. Vector4.TransformNormalToRef(vector, transformation, result);
  4319. return result;
  4320. };
  4321. /**
  4322. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4323. * This methods computes transformed normalized direction vectors only.
  4324. */
  4325. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4329. result.x = x;
  4330. result.y = y;
  4331. result.z = z;
  4332. result.w = vector.w;
  4333. };
  4334. /**
  4335. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4336. * This methods computes transformed normalized direction vectors only.
  4337. */
  4338. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4339. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4340. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4341. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4342. result.w = w;
  4343. };
  4344. return Vector4;
  4345. }());
  4346. BABYLON.Vector4 = Vector4;
  4347. var Size = /** @class */ (function () {
  4348. /**
  4349. * Creates a Size object from the given width and height (floats).
  4350. */
  4351. function Size(width, height) {
  4352. this.width = width;
  4353. this.height = height;
  4354. }
  4355. // Returns a string with the Size width and height.
  4356. Size.prototype.toString = function () {
  4357. return "{W: " + this.width + ", H: " + this.height + "}";
  4358. };
  4359. /**
  4360. * Returns the string "Size"
  4361. */
  4362. Size.prototype.getClassName = function () {
  4363. return "Size";
  4364. };
  4365. /**
  4366. * Returns the Size hash code.
  4367. */
  4368. Size.prototype.getHashCode = function () {
  4369. var hash = this.width || 0;
  4370. hash = (hash * 397) ^ (this.height || 0);
  4371. return hash;
  4372. };
  4373. /**
  4374. * Updates the current size from the given one.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.copyFrom = function (src) {
  4378. this.width = src.width;
  4379. this.height = src.height;
  4380. };
  4381. /**
  4382. * Updates in place the current Size from the given floats.
  4383. * Returns the updated Size.
  4384. */
  4385. Size.prototype.copyFromFloats = function (width, height) {
  4386. this.width = width;
  4387. this.height = height;
  4388. return this;
  4389. };
  4390. /**
  4391. * Updates in place the current Size from the given floats.
  4392. * Returns the updated Size.
  4393. */
  4394. Size.prototype.set = function (width, height) {
  4395. return this.copyFromFloats(width, height);
  4396. };
  4397. /**
  4398. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4399. */
  4400. Size.prototype.multiplyByFloats = function (w, h) {
  4401. return new Size(this.width * w, this.height * h);
  4402. };
  4403. /**
  4404. * Returns a new Size copied from the given one.
  4405. */
  4406. Size.prototype.clone = function () {
  4407. return new Size(this.width, this.height);
  4408. };
  4409. /**
  4410. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4411. */
  4412. Size.prototype.equals = function (other) {
  4413. if (!other) {
  4414. return false;
  4415. }
  4416. return (this.width === other.width) && (this.height === other.height);
  4417. };
  4418. Object.defineProperty(Size.prototype, "surface", {
  4419. /**
  4420. * Returns the surface of the Size : width * height (float).
  4421. */
  4422. get: function () {
  4423. return this.width * this.height;
  4424. },
  4425. enumerable: true,
  4426. configurable: true
  4427. });
  4428. /**
  4429. * Returns a new Size set to (0.0, 0.0)
  4430. */
  4431. Size.Zero = function () {
  4432. return new Size(0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Size set as the addition result of the current Size and the given one.
  4436. */
  4437. Size.prototype.add = function (otherSize) {
  4438. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4439. return r;
  4440. };
  4441. /**
  4442. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4443. */
  4444. Size.prototype.subtract = function (otherSize) {
  4445. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4450. */
  4451. Size.Lerp = function (start, end, amount) {
  4452. var w = start.width + ((end.width - start.width) * amount);
  4453. var h = start.height + ((end.height - start.height) * amount);
  4454. return new Size(w, h);
  4455. };
  4456. return Size;
  4457. }());
  4458. BABYLON.Size = Size;
  4459. /**
  4460. * Class used to store quaternion data
  4461. * @see https://en.wikipedia.org/wiki/Quaternion
  4462. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4463. */
  4464. var Quaternion = /** @class */ (function () {
  4465. /**
  4466. * Creates a new Quaternion from the given floats
  4467. * @param x defines the first component (0 by default)
  4468. * @param y defines the second component (0 by default)
  4469. * @param z defines the third component (0 by default)
  4470. * @param w defines the fourth component (1.0 by default)
  4471. */
  4472. function Quaternion(
  4473. /** defines the first component (0 by default) */
  4474. x,
  4475. /** defines the second component (0 by default) */
  4476. y,
  4477. /** defines the third component (0 by default) */
  4478. z,
  4479. /** defines the fourth component (1.0 by default) */
  4480. w) {
  4481. if (x === void 0) { x = 0.0; }
  4482. if (y === void 0) { y = 0.0; }
  4483. if (z === void 0) { z = 0.0; }
  4484. if (w === void 0) { w = 1.0; }
  4485. this.x = x;
  4486. this.y = y;
  4487. this.z = z;
  4488. this.w = w;
  4489. }
  4490. /**
  4491. * Gets a string representation for the current quaternion
  4492. * @returns a string with the Quaternion coordinates
  4493. */
  4494. Quaternion.prototype.toString = function () {
  4495. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4496. };
  4497. /**
  4498. * Gets the class name of the quaternion
  4499. * @returns the string "Quaternion"
  4500. */
  4501. Quaternion.prototype.getClassName = function () {
  4502. return "Quaternion";
  4503. };
  4504. /**
  4505. * Gets a hash code for this quaternion
  4506. * @returns the quaternion hash code
  4507. */
  4508. Quaternion.prototype.getHashCode = function () {
  4509. var hash = this.x || 0;
  4510. hash = (hash * 397) ^ (this.y || 0);
  4511. hash = (hash * 397) ^ (this.z || 0);
  4512. hash = (hash * 397) ^ (this.w || 0);
  4513. return hash;
  4514. };
  4515. /**
  4516. * Copy the quaternion to an array
  4517. * @returns a new array populated with 4 elements from the quaternion coordinates
  4518. */
  4519. Quaternion.prototype.asArray = function () {
  4520. return [this.x, this.y, this.z, this.w];
  4521. };
  4522. /**
  4523. * Check if two quaternions are equals
  4524. * @param otherQuaternion defines the second operand
  4525. * @return true if the current quaternion and the given one coordinates are strictly equals
  4526. */
  4527. Quaternion.prototype.equals = function (otherQuaternion) {
  4528. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4529. };
  4530. /**
  4531. * Clone the current quaternion
  4532. * @returns a new quaternion copied from the current one
  4533. */
  4534. Quaternion.prototype.clone = function () {
  4535. return new Quaternion(this.x, this.y, this.z, this.w);
  4536. };
  4537. /**
  4538. * Copy a quaternion to the current one
  4539. * @param other defines the other quaternion
  4540. * @returns the updated current quaternion
  4541. */
  4542. Quaternion.prototype.copyFrom = function (other) {
  4543. this.x = other.x;
  4544. this.y = other.y;
  4545. this.z = other.z;
  4546. this.w = other.w;
  4547. return this;
  4548. };
  4549. /**
  4550. * Updates the current quaternion with the given float coordinates
  4551. * @param x defines the x coordinate
  4552. * @param y defines the y coordinate
  4553. * @param z defines the z coordinate
  4554. * @param w defines the w coordinate
  4555. * @returns the updated current quaternion
  4556. */
  4557. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4558. this.x = x;
  4559. this.y = y;
  4560. this.z = z;
  4561. this.w = w;
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion from the given float coordinates
  4566. * @param x defines the x coordinate
  4567. * @param y defines the y coordinate
  4568. * @param z defines the z coordinate
  4569. * @param w defines the w coordinate
  4570. * @returns the updated current quaternion
  4571. */
  4572. Quaternion.prototype.set = function (x, y, z, w) {
  4573. return this.copyFromFloats(x, y, z, w);
  4574. };
  4575. /**
  4576. * Adds two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4579. */
  4580. Quaternion.prototype.add = function (other) {
  4581. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4582. };
  4583. /**
  4584. * Add a quaternion to the current one
  4585. * @param other defines the quaternion to add
  4586. * @returns the current quaternion
  4587. */
  4588. Quaternion.prototype.addInPlace = function (other) {
  4589. this.x += other.x;
  4590. this.y += other.y;
  4591. this.z += other.z;
  4592. this.w += other.w;
  4593. return this;
  4594. };
  4595. /**
  4596. * Subtract two quaternions
  4597. * @param other defines the second operand
  4598. * @returns a new quaternion as the subtraction result of the given one from the current one
  4599. */
  4600. Quaternion.prototype.subtract = function (other) {
  4601. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4602. };
  4603. /**
  4604. * Multiplies the current quaternion by a scale factor
  4605. * @param value defines the scale factor
  4606. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4607. */
  4608. Quaternion.prototype.scale = function (value) {
  4609. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4610. };
  4611. /**
  4612. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4613. * @param scale defines the scale factor
  4614. * @param result defines the Quaternion object where to store the result
  4615. * @returns the unmodified current quaternion
  4616. */
  4617. Quaternion.prototype.scaleToRef = function (scale, result) {
  4618. result.x = this.x * scale;
  4619. result.y = this.y * scale;
  4620. result.z = this.z * scale;
  4621. result.w = this.w * scale;
  4622. return this;
  4623. };
  4624. /**
  4625. * Multiplies in place the current quaternion by a scale factor
  4626. * @param value defines the scale factor
  4627. * @returns the current modified quaternion
  4628. */
  4629. Quaternion.prototype.scaleInPlace = function (value) {
  4630. this.x *= value;
  4631. this.y *= value;
  4632. this.z *= value;
  4633. this.w *= value;
  4634. return this;
  4635. };
  4636. /**
  4637. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4638. * @param scale defines the scale factor
  4639. * @param result defines the Quaternion object where to store the result
  4640. * @returns the unmodified current quaternion
  4641. */
  4642. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4643. result.x += this.x * scale;
  4644. result.y += this.y * scale;
  4645. result.z += this.z * scale;
  4646. result.w += this.w * scale;
  4647. return this;
  4648. };
  4649. /**
  4650. * Multiplies two quaternions
  4651. * @param q1 defines the second operand
  4652. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4653. */
  4654. Quaternion.prototype.multiply = function (q1) {
  4655. var result = new Quaternion(0, 0, 0, 1.0);
  4656. this.multiplyToRef(q1, result);
  4657. return result;
  4658. };
  4659. /**
  4660. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @param result defines the target quaternion
  4663. * @returns the current quaternion
  4664. */
  4665. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4666. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4667. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4668. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4669. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4670. result.copyFromFloats(x, y, z, w);
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4675. * @param q1 defines the second operand
  4676. * @returns the currentupdated quaternion
  4677. */
  4678. Quaternion.prototype.multiplyInPlace = function (q1) {
  4679. this.multiplyToRef(q1, this);
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4684. * @param ref defines the target quaternion
  4685. * @returns the current quaternion
  4686. */
  4687. Quaternion.prototype.conjugateToRef = function (ref) {
  4688. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4689. return this;
  4690. };
  4691. /**
  4692. * Conjugates in place (1-q) the current quaternion
  4693. * @returns the current updated quaternion
  4694. */
  4695. Quaternion.prototype.conjugateInPlace = function () {
  4696. this.x *= -1;
  4697. this.y *= -1;
  4698. this.z *= -1;
  4699. return this;
  4700. };
  4701. /**
  4702. * Conjugates in place (1-q) the current quaternion
  4703. * @returns a new quaternion
  4704. */
  4705. Quaternion.prototype.conjugate = function () {
  4706. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4707. return result;
  4708. };
  4709. /**
  4710. * Gets length of current quaternion
  4711. * @returns the quaternion length (float)
  4712. */
  4713. Quaternion.prototype.length = function () {
  4714. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4715. };
  4716. /**
  4717. * Normalize in place the current quaternion
  4718. * @returns the current updated quaternion
  4719. */
  4720. Quaternion.prototype.normalize = function () {
  4721. var length = 1.0 / this.length();
  4722. this.x *= length;
  4723. this.y *= length;
  4724. this.z *= length;
  4725. this.w *= length;
  4726. return this;
  4727. };
  4728. /**
  4729. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns a new Vector3 containing the Euler angles
  4732. */
  4733. Quaternion.prototype.toEulerAngles = function (order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var result = Vector3.Zero();
  4736. this.toEulerAnglesToRef(result, order);
  4737. return result;
  4738. };
  4739. /**
  4740. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4741. * @param result defines the vector which will be filled with the Euler angles
  4742. * @param order is a reserved parameter and is ignore for now
  4743. * @returns the current unchanged quaternion
  4744. */
  4745. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4746. if (order === void 0) { order = "YZX"; }
  4747. var qz = this.z;
  4748. var qx = this.x;
  4749. var qy = this.y;
  4750. var qw = this.w;
  4751. var sqw = qw * qw;
  4752. var sqz = qz * qz;
  4753. var sqx = qx * qx;
  4754. var sqy = qy * qy;
  4755. var zAxisY = qy * qz - qx * qw;
  4756. var limit = .4999999;
  4757. if (zAxisY < -limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else if (zAxisY > limit) {
  4763. result.y = 2 * Math.atan2(qy, qw);
  4764. result.x = -Math.PI / 2;
  4765. result.z = 0;
  4766. }
  4767. else {
  4768. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4769. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4770. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4771. }
  4772. return this;
  4773. };
  4774. /**
  4775. * Updates the given rotation matrix with the current quaternion values
  4776. * @param result defines the target matrix
  4777. * @returns the current unchanged quaternion
  4778. */
  4779. Quaternion.prototype.toRotationMatrix = function (result) {
  4780. var xx = this.x * this.x;
  4781. var yy = this.y * this.y;
  4782. var zz = this.z * this.z;
  4783. var xy = this.x * this.y;
  4784. var zw = this.z * this.w;
  4785. var zx = this.z * this.x;
  4786. var yw = this.y * this.w;
  4787. var yz = this.y * this.z;
  4788. var xw = this.x * this.w;
  4789. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4790. result.m[1] = 2.0 * (xy + zw);
  4791. result.m[2] = 2.0 * (zx - yw);
  4792. result.m[3] = 0;
  4793. result.m[4] = 2.0 * (xy - zw);
  4794. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4795. result.m[6] = 2.0 * (yz + xw);
  4796. result.m[7] = 0;
  4797. result.m[8] = 2.0 * (zx + yw);
  4798. result.m[9] = 2.0 * (yz - xw);
  4799. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4800. result.m[11] = 0;
  4801. result.m[12] = 0;
  4802. result.m[13] = 0;
  4803. result.m[14] = 0;
  4804. result.m[15] = 1.0;
  4805. result._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @returns the current updated quaternion
  4812. */
  4813. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4814. Quaternion.FromRotationMatrixToRef(matrix, this);
  4815. return this;
  4816. };
  4817. // Statics
  4818. /**
  4819. * Creates a new quaternion from a rotation matrix
  4820. * @param matrix defines the source matrix
  4821. * @returns a new quaternion created from the given rotation matrix values
  4822. */
  4823. Quaternion.FromRotationMatrix = function (matrix) {
  4824. var result = new Quaternion();
  4825. Quaternion.FromRotationMatrixToRef(matrix, result);
  4826. return result;
  4827. };
  4828. /**
  4829. * Updates the given quaternion with the given rotation matrix values
  4830. * @param matrix defines the source matrix
  4831. * @param result defines the target quaternion
  4832. */
  4833. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4834. var data = matrix.m;
  4835. var m11 = data[0], m12 = data[4], m13 = data[8];
  4836. var m21 = data[1], m22 = data[5], m23 = data[9];
  4837. var m31 = data[2], m32 = data[6], m33 = data[10];
  4838. var trace = m11 + m22 + m33;
  4839. var s;
  4840. if (trace > 0) {
  4841. s = 0.5 / Math.sqrt(trace + 1.0);
  4842. result.w = 0.25 / s;
  4843. result.x = (m32 - m23) * s;
  4844. result.y = (m13 - m31) * s;
  4845. result.z = (m21 - m12) * s;
  4846. }
  4847. else if (m11 > m22 && m11 > m33) {
  4848. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4849. result.w = (m32 - m23) / s;
  4850. result.x = 0.25 * s;
  4851. result.y = (m12 + m21) / s;
  4852. result.z = (m13 + m31) / s;
  4853. }
  4854. else if (m22 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4856. result.w = (m13 - m31) / s;
  4857. result.x = (m12 + m21) / s;
  4858. result.y = 0.25 * s;
  4859. result.z = (m23 + m32) / s;
  4860. }
  4861. else {
  4862. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4863. result.w = (m21 - m12) / s;
  4864. result.x = (m13 + m31) / s;
  4865. result.y = (m23 + m32) / s;
  4866. result.z = 0.25 * s;
  4867. }
  4868. };
  4869. /**
  4870. * Returns the dot product (float) between the quaternions "left" and "right"
  4871. * @param left defines the left operand
  4872. * @param right defines the right operand
  4873. * @returns the dot product
  4874. */
  4875. Quaternion.Dot = function (left, right) {
  4876. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4877. };
  4878. /**
  4879. * Checks if the two quaternions are close to each other
  4880. * @param quat0 defines the first quaternion to check
  4881. * @param quat1 defines the second quaternion to check
  4882. * @returns true if the two quaternions are close to each other
  4883. */
  4884. Quaternion.AreClose = function (quat0, quat1) {
  4885. var dot = Quaternion.Dot(quat0, quat1);
  4886. return dot >= 0;
  4887. };
  4888. /**
  4889. * Creates an empty quaternion
  4890. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4891. */
  4892. Quaternion.Zero = function () {
  4893. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4894. };
  4895. /**
  4896. * Inverse a given quaternion
  4897. * @param q defines the source quaternion
  4898. * @returns a new quaternion as the inverted current quaternion
  4899. */
  4900. Quaternion.Inverse = function (q) {
  4901. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4902. };
  4903. /**
  4904. * Creates an identity quaternion
  4905. * @returns the identity quaternion
  4906. */
  4907. Quaternion.Identity = function () {
  4908. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4909. };
  4910. /**
  4911. * Gets a boolean indicating if the given quaternion is identity
  4912. * @param quaternion defines the quaternion to check
  4913. * @returns true if the quaternion is identity
  4914. */
  4915. Quaternion.IsIdentity = function (quaternion) {
  4916. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4917. };
  4918. /**
  4919. * Creates a quaternion from a rotation around an axis
  4920. * @param axis defines the axis to use
  4921. * @param angle defines the angle to use
  4922. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4923. */
  4924. Quaternion.RotationAxis = function (axis, angle) {
  4925. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4926. };
  4927. /**
  4928. * Creates a rotation around an axis and stores it into the given quaternion
  4929. * @param axis defines the axis to use
  4930. * @param angle defines the angle to use
  4931. * @param result defines the target quaternion
  4932. * @returns the target quaternion
  4933. */
  4934. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4935. var sin = Math.sin(angle / 2);
  4936. axis.normalize();
  4937. result.w = Math.cos(angle / 2);
  4938. result.x = axis.x * sin;
  4939. result.y = axis.y * sin;
  4940. result.z = axis.z * sin;
  4941. return result;
  4942. };
  4943. /**
  4944. * Creates a new quaternion from data stored into an array
  4945. * @param array defines the data source
  4946. * @param offset defines the offset in the source array where the data starts
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.FromArray = function (array, offset) {
  4950. if (!offset) {
  4951. offset = 0;
  4952. }
  4953. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4954. };
  4955. /**
  4956. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @returns the new quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4963. var q = new Quaternion();
  4964. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4965. return q;
  4966. };
  4967. /**
  4968. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4969. * @param yaw defines the rotation around Y axis
  4970. * @param pitch defines the rotation around X axis
  4971. * @param roll defines the rotation around Z axis
  4972. * @param result defines the target quaternion
  4973. */
  4974. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4975. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4976. var halfRoll = roll * 0.5;
  4977. var halfPitch = pitch * 0.5;
  4978. var halfYaw = yaw * 0.5;
  4979. var sinRoll = Math.sin(halfRoll);
  4980. var cosRoll = Math.cos(halfRoll);
  4981. var sinPitch = Math.sin(halfPitch);
  4982. var cosPitch = Math.cos(halfPitch);
  4983. var sinYaw = Math.sin(halfYaw);
  4984. var cosYaw = Math.cos(halfYaw);
  4985. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4986. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4987. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4988. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4998. var result = new Quaternion();
  4999. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5000. return result;
  5001. };
  5002. /**
  5003. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5004. * @param alpha defines the rotation around first axis
  5005. * @param beta defines the rotation around second axis
  5006. * @param gamma defines the rotation around third axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5010. // Produces a quaternion from Euler angles in the z-x-z orientation
  5011. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5012. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5013. var halfBeta = beta * 0.5;
  5014. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5016. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5018. };
  5019. /**
  5020. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @returns the new quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5027. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5028. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5029. return quat;
  5030. };
  5031. /**
  5032. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5033. * @param axis1 defines the first axis
  5034. * @param axis2 defines the second axis
  5035. * @param axis3 defines the third axis
  5036. * @param ref defines the target quaternion
  5037. */
  5038. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5039. var rotMat = MathTmp.Matrix[0];
  5040. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5041. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @returns the new interpolated quaternion
  5049. */
  5050. Quaternion.Slerp = function (left, right, amount) {
  5051. var result = Quaternion.Identity();
  5052. Quaternion.SlerpToRef(left, right, amount, result);
  5053. return result;
  5054. };
  5055. /**
  5056. * Interpolates between two quaternions and stores it into a target quaternion
  5057. * @param left defines first quaternion
  5058. * @param right defines second quaternion
  5059. * @param amount defines the gradient to use
  5060. * @param result defines the target quaternion
  5061. */
  5062. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5063. var num2;
  5064. var num3;
  5065. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5066. var flag = false;
  5067. if (num4 < 0) {
  5068. flag = true;
  5069. num4 = -num4;
  5070. }
  5071. if (num4 > 0.999999) {
  5072. num3 = 1 - amount;
  5073. num2 = flag ? -amount : amount;
  5074. }
  5075. else {
  5076. var num5 = Math.acos(num4);
  5077. var num6 = (1.0 / Math.sin(num5));
  5078. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5079. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5080. }
  5081. result.x = (num3 * left.x) + (num2 * right.x);
  5082. result.y = (num3 * left.y) + (num2 * right.y);
  5083. result.z = (num3 * left.z) + (num2 * right.z);
  5084. result.w = (num3 * left.w) + (num2 * right.w);
  5085. };
  5086. /**
  5087. * Interpolate between two quaternions using Hermite interpolation
  5088. * @param value1 defines first quaternion
  5089. * @param tangent1 defines the incoming tangent
  5090. * @param value2 defines second quaternion
  5091. * @param tangent2 defines the outgoing tangent
  5092. * @param amount defines the target quaternion
  5093. * @returns the new interpolated quaternion
  5094. */
  5095. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5096. var squared = amount * amount;
  5097. var cubed = amount * squared;
  5098. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5099. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5100. var part3 = (cubed - (2.0 * squared)) + amount;
  5101. var part4 = cubed - squared;
  5102. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5103. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5104. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5105. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5106. return new Quaternion(x, y, z, w);
  5107. };
  5108. return Quaternion;
  5109. }());
  5110. BABYLON.Quaternion = Quaternion;
  5111. /**
  5112. * Class used to store matrix data (4x4)
  5113. */
  5114. var Matrix = /** @class */ (function () {
  5115. /**
  5116. * Creates an empty matrix (filled with zeros)
  5117. */
  5118. function Matrix() {
  5119. this._isIdentity = false;
  5120. this._isIdentityDirty = true;
  5121. /**
  5122. * Gets or sets the internal data of the matrix
  5123. */
  5124. this.m = new Float32Array(16);
  5125. this._markAsUpdated();
  5126. }
  5127. /** @hidden */
  5128. Matrix.prototype._markAsUpdated = function () {
  5129. this.updateFlag = Matrix._updateFlagSeed++;
  5130. this._isIdentityDirty = true;
  5131. };
  5132. // Properties
  5133. /**
  5134. * Check if the current matrix is indentity
  5135. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5136. * @returns true is the matrix is the identity matrix
  5137. */
  5138. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5139. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5140. if (this._isIdentityDirty) {
  5141. this._isIdentityDirty = false;
  5142. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5146. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5147. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5148. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5149. this._isIdentity = false;
  5150. }
  5151. else {
  5152. this._isIdentity = true;
  5153. }
  5154. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5155. this._isIdentity = false;
  5156. }
  5157. }
  5158. return this._isIdentity;
  5159. };
  5160. /**
  5161. * Gets the determinant of the matrix
  5162. * @returns the matrix determinant
  5163. */
  5164. Matrix.prototype.determinant = function () {
  5165. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5166. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5167. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5168. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5169. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5170. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5171. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5172. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5173. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5174. };
  5175. // Methods
  5176. /**
  5177. * Returns the matrix as a Float32Array
  5178. * @returns the matrix underlying array
  5179. */
  5180. Matrix.prototype.toArray = function () {
  5181. return this.m;
  5182. };
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array.
  5186. */
  5187. Matrix.prototype.asArray = function () {
  5188. return this.toArray();
  5189. };
  5190. /**
  5191. * Inverts the current matrix in place
  5192. * @returns the current inverted matrix
  5193. */
  5194. Matrix.prototype.invert = function () {
  5195. this.invertToRef(this);
  5196. return this;
  5197. };
  5198. /**
  5199. * Sets all the matrix elements to zero
  5200. * @returns the current matrix
  5201. */
  5202. Matrix.prototype.reset = function () {
  5203. for (var index = 0; index < 16; index++) {
  5204. this.m[index] = 0.0;
  5205. }
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Adds the current matrix with a second one
  5211. * @param other defines the matrix to add
  5212. * @returns a new matrix as the addition of the current matrix and the given one
  5213. */
  5214. Matrix.prototype.add = function (other) {
  5215. var result = new Matrix();
  5216. this.addToRef(other, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5221. * @param other defines the matrix to add
  5222. * @param result defines the target matrix
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.addToRef = function (other, result) {
  5226. for (var index = 0; index < 16; index++) {
  5227. result.m[index] = this.m[index] + other.m[index];
  5228. }
  5229. result._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Adds in place the given matrix to the current matrix
  5234. * @param other defines the second operand
  5235. * @returns the current updated matrix
  5236. */
  5237. Matrix.prototype.addToSelf = function (other) {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] += other.m[index];
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Sets the given matrix to the current inverted Matrix
  5246. * @param other defines the target matrix
  5247. * @returns the unmodified current matrix
  5248. */
  5249. Matrix.prototype.invertToRef = function (other) {
  5250. var l1 = this.m[0];
  5251. var l2 = this.m[1];
  5252. var l3 = this.m[2];
  5253. var l4 = this.m[3];
  5254. var l5 = this.m[4];
  5255. var l6 = this.m[5];
  5256. var l7 = this.m[6];
  5257. var l8 = this.m[7];
  5258. var l9 = this.m[8];
  5259. var l10 = this.m[9];
  5260. var l11 = this.m[10];
  5261. var l12 = this.m[11];
  5262. var l13 = this.m[12];
  5263. var l14 = this.m[13];
  5264. var l15 = this.m[14];
  5265. var l16 = this.m[15];
  5266. var l17 = (l11 * l16) - (l12 * l15);
  5267. var l18 = (l10 * l16) - (l12 * l14);
  5268. var l19 = (l10 * l15) - (l11 * l14);
  5269. var l20 = (l9 * l16) - (l12 * l13);
  5270. var l21 = (l9 * l15) - (l11 * l13);
  5271. var l22 = (l9 * l14) - (l10 * l13);
  5272. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5273. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5274. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5275. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5276. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5277. var l28 = (l7 * l16) - (l8 * l15);
  5278. var l29 = (l6 * l16) - (l8 * l14);
  5279. var l30 = (l6 * l15) - (l7 * l14);
  5280. var l31 = (l5 * l16) - (l8 * l13);
  5281. var l32 = (l5 * l15) - (l7 * l13);
  5282. var l33 = (l5 * l14) - (l6 * l13);
  5283. var l34 = (l7 * l12) - (l8 * l11);
  5284. var l35 = (l6 * l12) - (l8 * l10);
  5285. var l36 = (l6 * l11) - (l7 * l10);
  5286. var l37 = (l5 * l12) - (l8 * l9);
  5287. var l38 = (l5 * l11) - (l7 * l9);
  5288. var l39 = (l5 * l10) - (l6 * l9);
  5289. other.m[0] = l23 * l27;
  5290. other.m[4] = l24 * l27;
  5291. other.m[8] = l25 * l27;
  5292. other.m[12] = l26 * l27;
  5293. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5294. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5295. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5296. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5297. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5298. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5299. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5300. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5301. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5302. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5303. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5304. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5305. other._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector (using 3 floats) in the current matrix
  5310. * @param x defines the 1st component of the translation
  5311. * @param y defines the 2nd component of the translation
  5312. * @param z defines the 3rd component of the translation
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5316. this.m[12] = x;
  5317. this.m[13] = y;
  5318. this.m[14] = z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Inserts the translation vector in the current matrix
  5324. * @param vector3 defines the translation to insert
  5325. * @returns the current updated matrix
  5326. */
  5327. Matrix.prototype.setTranslation = function (vector3) {
  5328. this.m[12] = vector3.x;
  5329. this.m[13] = vector3.y;
  5330. this.m[14] = vector3.z;
  5331. this._markAsUpdated();
  5332. return this;
  5333. };
  5334. /**
  5335. * Gets the translation value of the current matrix
  5336. * @returns a new Vector3 as the extracted translation from the matrix
  5337. */
  5338. Matrix.prototype.getTranslation = function () {
  5339. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5340. };
  5341. /**
  5342. * Fill a Vector3 with the extracted translation from the matrix
  5343. * @param result defines the Vector3 where to store the translation
  5344. * @returns the current matrix
  5345. */
  5346. Matrix.prototype.getTranslationToRef = function (result) {
  5347. result.x = this.m[12];
  5348. result.y = this.m[13];
  5349. result.z = this.m[14];
  5350. return this;
  5351. };
  5352. /**
  5353. * Remove rotation and scaling part from the matrix
  5354. * @returns the updated matrix
  5355. */
  5356. Matrix.prototype.removeRotationAndScaling = function () {
  5357. this.setRowFromFloats(0, 1, 0, 0, 0);
  5358. this.setRowFromFloats(1, 0, 1, 0, 0);
  5359. this.setRowFromFloats(2, 0, 0, 1, 0);
  5360. return this;
  5361. };
  5362. /**
  5363. * Multiply two matrices
  5364. * @param other defines the second operand
  5365. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5366. */
  5367. Matrix.prototype.multiply = function (other) {
  5368. var result = new Matrix();
  5369. this.multiplyToRef(other, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Copy the current matrix from the given one
  5374. * @param other defines the source matrix
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.copyFrom = function (other) {
  5378. for (var index = 0; index < 16; index++) {
  5379. this.m[index] = other.m[index];
  5380. }
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Populates the given array from the starting index with the current matrix values
  5386. * @param array defines the target array
  5387. * @param offset defines the offset in the target array where to start storing values
  5388. * @returns the current matrix
  5389. */
  5390. Matrix.prototype.copyToArray = function (array, offset) {
  5391. if (offset === void 0) { offset = 0; }
  5392. for (var index = 0; index < 16; index++) {
  5393. array[offset + index] = this.m[index];
  5394. }
  5395. return this;
  5396. };
  5397. /**
  5398. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5399. * @param other defines the second operand
  5400. * @param result defines the matrix where to store the multiplication
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToRef = function (other, result) {
  5404. this.multiplyToArray(other, result.m, 0);
  5405. result._markAsUpdated();
  5406. return this;
  5407. };
  5408. /**
  5409. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5410. * @param other defines the second operand
  5411. * @param result defines the array where to store the multiplication
  5412. * @param offset defines the offset in the target array where to start storing values
  5413. * @returns the current matrix
  5414. */
  5415. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5416. var tm0 = this.m[0];
  5417. var tm1 = this.m[1];
  5418. var tm2 = this.m[2];
  5419. var tm3 = this.m[3];
  5420. var tm4 = this.m[4];
  5421. var tm5 = this.m[5];
  5422. var tm6 = this.m[6];
  5423. var tm7 = this.m[7];
  5424. var tm8 = this.m[8];
  5425. var tm9 = this.m[9];
  5426. var tm10 = this.m[10];
  5427. var tm11 = this.m[11];
  5428. var tm12 = this.m[12];
  5429. var tm13 = this.m[13];
  5430. var tm14 = this.m[14];
  5431. var tm15 = this.m[15];
  5432. var om0 = other.m[0];
  5433. var om1 = other.m[1];
  5434. var om2 = other.m[2];
  5435. var om3 = other.m[3];
  5436. var om4 = other.m[4];
  5437. var om5 = other.m[5];
  5438. var om6 = other.m[6];
  5439. var om7 = other.m[7];
  5440. var om8 = other.m[8];
  5441. var om9 = other.m[9];
  5442. var om10 = other.m[10];
  5443. var om11 = other.m[11];
  5444. var om12 = other.m[12];
  5445. var om13 = other.m[13];
  5446. var om14 = other.m[14];
  5447. var om15 = other.m[15];
  5448. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5449. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5450. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5451. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5452. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5453. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5454. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5455. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5456. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5457. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5458. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5459. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5460. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5461. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5462. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5463. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5464. return this;
  5465. };
  5466. /**
  5467. * Check equality between this matrix and a second one
  5468. * @param value defines the second matrix to compare
  5469. * @returns true is the current matrix and the given one values are strictly equal
  5470. */
  5471. Matrix.prototype.equals = function (value) {
  5472. return value &&
  5473. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5474. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5475. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5476. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5477. };
  5478. /**
  5479. * Clone the current matrix
  5480. * @returns a new matrix from the current matrix
  5481. */
  5482. Matrix.prototype.clone = function () {
  5483. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5484. };
  5485. /**
  5486. * Returns the name of the current matrix class
  5487. * @returns the string "Matrix"
  5488. */
  5489. Matrix.prototype.getClassName = function () {
  5490. return "Matrix";
  5491. };
  5492. /**
  5493. * Gets the hash code of the current matrix
  5494. * @returns the hash code
  5495. */
  5496. Matrix.prototype.getHashCode = function () {
  5497. var hash = this.m[0] || 0;
  5498. for (var i = 1; i < 16; i++) {
  5499. hash = (hash * 397) ^ (this.m[i] || 0);
  5500. }
  5501. return hash;
  5502. };
  5503. /**
  5504. * Decomposes the current Matrix into a translation, rotation and scaling components
  5505. * @param scale defines the scale vector3 given as a reference to update
  5506. * @param rotation defines the rotation quaternion given as a reference to update
  5507. * @param translation defines the translation vector3 given as a reference to update
  5508. * @returns true if operation was successful
  5509. */
  5510. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5511. if (translation) {
  5512. translation.x = this.m[12];
  5513. translation.y = this.m[13];
  5514. translation.z = this.m[14];
  5515. }
  5516. scale = scale || MathTmp.Vector3[0];
  5517. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5518. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5519. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5520. if (this.determinant() <= 0) {
  5521. scale.y *= -1;
  5522. }
  5523. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5524. if (rotation) {
  5525. rotation.x = 0;
  5526. rotation.y = 0;
  5527. rotation.z = 0;
  5528. rotation.w = 1;
  5529. }
  5530. return false;
  5531. }
  5532. if (rotation) {
  5533. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5534. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Gets specific row of the matrix
  5540. * @param index defines the number of the row to get
  5541. * @returns the index-th row of the current matrix as a new Vector4
  5542. */
  5543. Matrix.prototype.getRow = function (index) {
  5544. if (index < 0 || index > 3) {
  5545. return null;
  5546. }
  5547. var i = index * 4;
  5548. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5549. };
  5550. /**
  5551. * Sets the index-th row of the current matrix to the vector4 values
  5552. * @param index defines the number of the row to set
  5553. * @param row defines the target vector4
  5554. * @returns the updated current matrix
  5555. */
  5556. Matrix.prototype.setRow = function (index, row) {
  5557. if (index < 0 || index > 3) {
  5558. return this;
  5559. }
  5560. var i = index * 4;
  5561. this.m[i + 0] = row.x;
  5562. this.m[i + 1] = row.y;
  5563. this.m[i + 2] = row.z;
  5564. this.m[i + 3] = row.w;
  5565. this._markAsUpdated();
  5566. return this;
  5567. };
  5568. /**
  5569. * Compute the transpose of the matrix
  5570. * @returns the new transposed matrix
  5571. */
  5572. Matrix.prototype.transpose = function () {
  5573. return Matrix.Transpose(this);
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix and store it in a given matrix
  5577. * @param result defines the target matrix
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.transposeToRef = function (result) {
  5581. Matrix.TransposeToRef(this, result);
  5582. return this;
  5583. };
  5584. /**
  5585. * Sets the index-th row of the current matrix with the given 4 x float values
  5586. * @param index defines the row index
  5587. * @param x defines the x component to set
  5588. * @param y defines the y component to set
  5589. * @param z defines the z component to set
  5590. * @param w defines the w component to set
  5591. * @returns the updated current matrix
  5592. */
  5593. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5594. if (index < 0 || index > 3) {
  5595. return this;
  5596. }
  5597. var i = index * 4;
  5598. this.m[i + 0] = x;
  5599. this.m[i + 1] = y;
  5600. this.m[i + 2] = z;
  5601. this.m[i + 3] = w;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5607. * @param scale defines the scale factor
  5608. * @returns a new matrix
  5609. */
  5610. Matrix.prototype.scale = function (scale) {
  5611. var result = new Matrix();
  5612. this.scaleToRef(scale, result);
  5613. return result;
  5614. };
  5615. /**
  5616. * Scale the current matrix values by a factor to a given result matrix
  5617. * @param scale defines the scale factor
  5618. * @param result defines the matrix to store the result
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.scaleToRef = function (scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = this.m[index] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Scale the current matrix values by a factor and add the result to a given matrix
  5630. * @param scale defines the scale factor
  5631. * @param result defines the Matrix to store the result
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5635. for (var index = 0; index < 16; index++) {
  5636. result.m[index] += this.m[index] * scale;
  5637. }
  5638. result._markAsUpdated();
  5639. return this;
  5640. };
  5641. /**
  5642. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5643. * @param ref matrix to store the result
  5644. */
  5645. Matrix.prototype.toNormalMatrix = function (ref) {
  5646. this.invertToRef(ref);
  5647. ref.transpose();
  5648. var m = ref.m;
  5649. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5650. };
  5651. /**
  5652. * Gets only rotation part of the current matrix
  5653. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5654. */
  5655. Matrix.prototype.getRotationMatrix = function () {
  5656. var result = Matrix.Identity();
  5657. this.getRotationMatrixToRef(result);
  5658. return result;
  5659. };
  5660. /**
  5661. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5662. * @param result defines the target matrix to store data to
  5663. * @returns the current matrix
  5664. */
  5665. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5666. var m = this.m;
  5667. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5668. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5669. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5670. if (this.determinant() <= 0) {
  5671. sy *= -1;
  5672. }
  5673. if (sx === 0 || sy === 0 || sz === 0) {
  5674. Matrix.IdentityToRef(result);
  5675. }
  5676. else {
  5677. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5678. }
  5679. return this;
  5680. };
  5681. // Statics
  5682. /**
  5683. * Creates a matrix from an array
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @returns a new Matrix set from the starting index of the given array
  5687. */
  5688. Matrix.FromArray = function (array, offset) {
  5689. var result = new Matrix();
  5690. if (!offset) {
  5691. offset = 0;
  5692. }
  5693. Matrix.FromArrayToRef(array, offset, result);
  5694. return result;
  5695. };
  5696. /**
  5697. * Copy the content of an array into a given matrix
  5698. * @param array defines the source array
  5699. * @param offset defines an offset in the source array
  5700. * @param result defines the target matrix
  5701. */
  5702. Matrix.FromArrayToRef = function (array, offset, result) {
  5703. for (var index = 0; index < 16; index++) {
  5704. result.m[index] = array[index + offset];
  5705. }
  5706. result._markAsUpdated();
  5707. };
  5708. /**
  5709. * Stores an array into a matrix after having multiplied each component by a given factor
  5710. * @param array defines the source array
  5711. * @param offset defines the offset in the source array
  5712. * @param scale defines the scaling factor
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5716. for (var index = 0; index < 16; index++) {
  5717. result.m[index] = array[index + offset] * scale;
  5718. }
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Stores a list of values (16) inside a given matrix
  5723. * @param initialM11 defines 1st value of 1st row
  5724. * @param initialM12 defines 2nd value of 1st row
  5725. * @param initialM13 defines 3rd value of 1st row
  5726. * @param initialM14 defines 4th value of 1st row
  5727. * @param initialM21 defines 1st value of 2nd row
  5728. * @param initialM22 defines 2nd value of 2nd row
  5729. * @param initialM23 defines 3rd value of 2nd row
  5730. * @param initialM24 defines 4th value of 2nd row
  5731. * @param initialM31 defines 1st value of 3rd row
  5732. * @param initialM32 defines 2nd value of 3rd row
  5733. * @param initialM33 defines 3rd value of 3rd row
  5734. * @param initialM34 defines 4th value of 3rd row
  5735. * @param initialM41 defines 1st value of 4th row
  5736. * @param initialM42 defines 2nd value of 4th row
  5737. * @param initialM43 defines 3rd value of 4th row
  5738. * @param initialM44 defines 4th value of 4th row
  5739. * @param result defines the target matrix
  5740. */
  5741. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5742. result.m[0] = initialM11;
  5743. result.m[1] = initialM12;
  5744. result.m[2] = initialM13;
  5745. result.m[3] = initialM14;
  5746. result.m[4] = initialM21;
  5747. result.m[5] = initialM22;
  5748. result.m[6] = initialM23;
  5749. result.m[7] = initialM24;
  5750. result.m[8] = initialM31;
  5751. result.m[9] = initialM32;
  5752. result.m[10] = initialM33;
  5753. result.m[11] = initialM34;
  5754. result.m[12] = initialM41;
  5755. result.m[13] = initialM42;
  5756. result.m[14] = initialM43;
  5757. result.m[15] = initialM44;
  5758. result._markAsUpdated();
  5759. };
  5760. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5761. /**
  5762. * Gets an identity matrix that must not be updated
  5763. */
  5764. get: function () {
  5765. return Matrix._identityReadOnly;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. /**
  5771. * Creates new matrix from a list of values (16)
  5772. * @param initialM11 defines 1st value of 1st row
  5773. * @param initialM12 defines 2nd value of 1st row
  5774. * @param initialM13 defines 3rd value of 1st row
  5775. * @param initialM14 defines 4th value of 1st row
  5776. * @param initialM21 defines 1st value of 2nd row
  5777. * @param initialM22 defines 2nd value of 2nd row
  5778. * @param initialM23 defines 3rd value of 2nd row
  5779. * @param initialM24 defines 4th value of 2nd row
  5780. * @param initialM31 defines 1st value of 3rd row
  5781. * @param initialM32 defines 2nd value of 3rd row
  5782. * @param initialM33 defines 3rd value of 3rd row
  5783. * @param initialM34 defines 4th value of 3rd row
  5784. * @param initialM41 defines 1st value of 4th row
  5785. * @param initialM42 defines 2nd value of 4th row
  5786. * @param initialM43 defines 3rd value of 4th row
  5787. * @param initialM44 defines 4th value of 4th row
  5788. * @returns the new matrix
  5789. */
  5790. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5791. var result = new Matrix();
  5792. result.m[0] = initialM11;
  5793. result.m[1] = initialM12;
  5794. result.m[2] = initialM13;
  5795. result.m[3] = initialM14;
  5796. result.m[4] = initialM21;
  5797. result.m[5] = initialM22;
  5798. result.m[6] = initialM23;
  5799. result.m[7] = initialM24;
  5800. result.m[8] = initialM31;
  5801. result.m[9] = initialM32;
  5802. result.m[10] = initialM33;
  5803. result.m[11] = initialM34;
  5804. result.m[12] = initialM41;
  5805. result.m[13] = initialM42;
  5806. result.m[14] = initialM43;
  5807. result.m[15] = initialM44;
  5808. return result;
  5809. };
  5810. /**
  5811. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @returns a new matrix
  5816. */
  5817. Matrix.Compose = function (scale, rotation, translation) {
  5818. var result = Matrix.Identity();
  5819. Matrix.ComposeToRef(scale, rotation, translation, result);
  5820. return result;
  5821. };
  5822. /**
  5823. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5824. * @param scale defines the scale vector3
  5825. * @param rotation defines the rotation quaternion
  5826. * @param translation defines the translation vector3
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5830. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5831. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5832. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5833. result.setTranslation(translation);
  5834. };
  5835. /**
  5836. * Creates a new identity matrix
  5837. * @returns a new identity matrix
  5838. */
  5839. Matrix.Identity = function () {
  5840. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix and stores the result in a given matrix
  5844. * @param result defines the target matrix
  5845. */
  5846. Matrix.IdentityToRef = function (result) {
  5847. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5848. };
  5849. /**
  5850. * Creates a new zero matrix
  5851. * @returns a new zero matrix
  5852. */
  5853. Matrix.Zero = function () {
  5854. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationX = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationXToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new matrix as the invert of a given matrix
  5868. * @param source defines the source matrix
  5869. * @returns the new matrix
  5870. */
  5871. Matrix.Invert = function (source) {
  5872. var result = new Matrix();
  5873. source.invertToRef(result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5878. * @param angle defines the angle (in radians) to use
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.RotationXToRef = function (angle, result) {
  5882. var s = Math.sin(angle);
  5883. var c = Math.cos(angle);
  5884. result.m[0] = 1.0;
  5885. result.m[15] = 1.0;
  5886. result.m[5] = c;
  5887. result.m[10] = c;
  5888. result.m[9] = -s;
  5889. result.m[6] = s;
  5890. result.m[1] = 0.0;
  5891. result.m[2] = 0.0;
  5892. result.m[3] = 0.0;
  5893. result.m[4] = 0.0;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = 0.0;
  5896. result.m[11] = 0.0;
  5897. result.m[12] = 0.0;
  5898. result.m[13] = 0.0;
  5899. result.m[14] = 0.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a new rotation matrix for "angle" radians around the Y axis
  5904. * @param angle defines the angle (in radians) to use
  5905. * @return the new matrix
  5906. */
  5907. Matrix.RotationY = function (angle) {
  5908. var result = new Matrix();
  5909. Matrix.RotationYToRef(angle, result);
  5910. return result;
  5911. };
  5912. /**
  5913. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5914. * @param angle defines the angle (in radians) to use
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.RotationYToRef = function (angle, result) {
  5918. var s = Math.sin(angle);
  5919. var c = Math.cos(angle);
  5920. result.m[5] = 1.0;
  5921. result.m[15] = 1.0;
  5922. result.m[0] = c;
  5923. result.m[2] = -s;
  5924. result.m[8] = s;
  5925. result.m[10] = c;
  5926. result.m[1] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[6] = 0.0;
  5930. result.m[7] = 0.0;
  5931. result.m[9] = 0.0;
  5932. result.m[11] = 0.0;
  5933. result.m[12] = 0.0;
  5934. result.m[13] = 0.0;
  5935. result.m[14] = 0.0;
  5936. result._markAsUpdated();
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the Z axis
  5940. * @param angle defines the angle (in radians) to use
  5941. * @return the new matrix
  5942. */
  5943. Matrix.RotationZ = function (angle) {
  5944. var result = new Matrix();
  5945. Matrix.RotationZToRef(angle, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationZToRef = function (angle, result) {
  5954. var s = Math.sin(angle);
  5955. var c = Math.cos(angle);
  5956. result.m[10] = 1.0;
  5957. result.m[15] = 1.0;
  5958. result.m[0] = c;
  5959. result.m[1] = s;
  5960. result.m[4] = -s;
  5961. result.m[5] = c;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[8] = 0.0;
  5967. result.m[9] = 0.0;
  5968. result.m[11] = 0.0;
  5969. result.m[12] = 0.0;
  5970. result.m[13] = 0.0;
  5971. result.m[14] = 0.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the given axis
  5976. * @param axis defines the axis to use
  5977. * @param angle defines the angle (in radians) to use
  5978. * @return the new matrix
  5979. */
  5980. Matrix.RotationAxis = function (axis, angle) {
  5981. var result = Matrix.Zero();
  5982. Matrix.RotationAxisToRef(axis, angle, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5987. * @param axis defines the axis to use
  5988. * @param angle defines the angle (in radians) to use
  5989. * @param result defines the target matrix
  5990. */
  5991. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5992. var s = Math.sin(-angle);
  5993. var c = Math.cos(-angle);
  5994. var c1 = 1 - c;
  5995. axis.normalize();
  5996. result.m[0] = (axis.x * axis.x) * c1 + c;
  5997. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5998. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5999. result.m[3] = 0.0;
  6000. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6001. result.m[5] = (axis.y * axis.y) * c1 + c;
  6002. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6003. result.m[7] = 0.0;
  6004. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6005. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6006. result.m[10] = (axis.z * axis.z) * c1 + c;
  6007. result.m[11] = 0.0;
  6008. result.m[15] = 1.0;
  6009. result._markAsUpdated();
  6010. };
  6011. /**
  6012. * Creates a rotation matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @returns the new rotation matrix
  6017. */
  6018. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6019. var result = new Matrix();
  6020. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6021. return result;
  6022. };
  6023. /**
  6024. * Creates a rotation matrix and stores it in a given matrix
  6025. * @param yaw defines the yaw angle in radians (Y axis)
  6026. * @param pitch defines the pitch angle in radians (X axis)
  6027. * @param roll defines the roll angle in radians (X axis)
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6031. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6032. this._tempQuaternion.toRotationMatrix(result);
  6033. };
  6034. /**
  6035. * Creates a scaling matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @returns the new matrix
  6040. */
  6041. Matrix.Scaling = function (x, y, z) {
  6042. var result = Matrix.Zero();
  6043. Matrix.ScalingToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a scaling matrix and stores it in a given matrix
  6048. * @param x defines the scale factor on X axis
  6049. * @param y defines the scale factor on Y axis
  6050. * @param z defines the scale factor on Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.ScalingToRef = function (x, y, z, result) {
  6054. result.m[0] = x;
  6055. result.m[1] = 0.0;
  6056. result.m[2] = 0.0;
  6057. result.m[3] = 0.0;
  6058. result.m[4] = 0.0;
  6059. result.m[5] = y;
  6060. result.m[6] = 0.0;
  6061. result.m[7] = 0.0;
  6062. result.m[8] = 0.0;
  6063. result.m[9] = 0.0;
  6064. result.m[10] = z;
  6065. result.m[11] = 0.0;
  6066. result.m[12] = 0.0;
  6067. result.m[13] = 0.0;
  6068. result.m[14] = 0.0;
  6069. result.m[15] = 1.0;
  6070. result._markAsUpdated();
  6071. };
  6072. /**
  6073. * Creates a translation matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @returns the new matrix
  6078. */
  6079. Matrix.Translation = function (x, y, z) {
  6080. var result = Matrix.Identity();
  6081. Matrix.TranslationToRef(x, y, z, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a translation matrix and stores it in a given matrix
  6086. * @param x defines the translation on X axis
  6087. * @param y defines the translation on Y axis
  6088. * @param z defines the translationon Z axis
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.TranslationToRef = function (x, y, z, result) {
  6092. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6093. };
  6094. /**
  6095. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @returns the new matrix
  6100. */
  6101. Matrix.Lerp = function (startValue, endValue, gradient) {
  6102. var result = Matrix.Zero();
  6103. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6104. return result;
  6105. };
  6106. /**
  6107. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6108. * @param startValue defines the start value
  6109. * @param endValue defines the end value
  6110. * @param gradient defines the gradient factor
  6111. * @param result defines the Matrix object where to store data
  6112. */
  6113. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6114. for (var index = 0; index < 16; index++) {
  6115. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6116. }
  6117. result._markAsUpdated();
  6118. };
  6119. /**
  6120. * Builds a new matrix whose values are computed by:
  6121. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6122. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6123. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6124. * @param startValue defines the first matrix
  6125. * @param endValue defines the second matrix
  6126. * @param gradient defines the gradient between the two matrices
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6130. var result = Matrix.Zero();
  6131. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Update a matrix to values which are computed by:
  6136. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6137. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6138. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6139. * @param startValue defines the first matrix
  6140. * @param endValue defines the second matrix
  6141. * @param gradient defines the gradient between the two matrices
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6145. var startScale = MathTmp.Vector3[0];
  6146. var startRotation = MathTmp.Quaternion[0];
  6147. var startTranslation = MathTmp.Vector3[1];
  6148. startValue.decompose(startScale, startRotation, startTranslation);
  6149. var endScale = MathTmp.Vector3[2];
  6150. var endRotation = MathTmp.Quaternion[1];
  6151. var endTranslation = MathTmp.Vector3[3];
  6152. endValue.decompose(endScale, endRotation, endTranslation);
  6153. var resultScale = MathTmp.Vector3[4];
  6154. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6155. var resultRotation = MathTmp.Quaternion[2];
  6156. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6157. var resultTranslation = MathTmp.Vector3[5];
  6158. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6159. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6160. };
  6161. /**
  6162. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6163. * This function works in left handed mode
  6164. * @param eye defines the final position of the entity
  6165. * @param target defines where the entity should look at
  6166. * @param up defines the up vector for the entity
  6167. * @returns the new matrix
  6168. */
  6169. Matrix.LookAtLH = function (eye, target, up) {
  6170. var result = Matrix.Zero();
  6171. Matrix.LookAtLHToRef(eye, target, up, result);
  6172. return result;
  6173. };
  6174. /**
  6175. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6176. * This function works in left handed mode
  6177. * @param eye defines the final position of the entity
  6178. * @param target defines where the entity should look at
  6179. * @param up defines the up vector for the entity
  6180. * @param result defines the target matrix
  6181. */
  6182. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6183. // Z axis
  6184. target.subtractToRef(eye, this._zAxis);
  6185. this._zAxis.normalize();
  6186. // X axis
  6187. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6188. if (this._xAxis.lengthSquared() === 0) {
  6189. this._xAxis.x = 1.0;
  6190. }
  6191. else {
  6192. this._xAxis.normalize();
  6193. }
  6194. // Y axis
  6195. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6196. this._yAxis.normalize();
  6197. // Eye angles
  6198. var ex = -Vector3.Dot(this._xAxis, eye);
  6199. var ey = -Vector3.Dot(this._yAxis, eye);
  6200. var ez = -Vector3.Dot(this._zAxis, eye);
  6201. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6202. };
  6203. /**
  6204. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6205. * This function works in right handed mode
  6206. * @param eye defines the final position of the entity
  6207. * @param target defines where the entity should look at
  6208. * @param up defines the up vector for the entity
  6209. * @returns the new matrix
  6210. */
  6211. Matrix.LookAtRH = function (eye, target, up) {
  6212. var result = Matrix.Zero();
  6213. Matrix.LookAtRHToRef(eye, target, up, result);
  6214. return result;
  6215. };
  6216. /**
  6217. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6218. * This function works in right handed mode
  6219. * @param eye defines the final position of the entity
  6220. * @param target defines where the entity should look at
  6221. * @param up defines the up vector for the entity
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6225. // Z axis
  6226. eye.subtractToRef(target, this._zAxis);
  6227. this._zAxis.normalize();
  6228. // X axis
  6229. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6230. if (this._xAxis.lengthSquared() === 0) {
  6231. this._xAxis.x = 1.0;
  6232. }
  6233. else {
  6234. this._xAxis.normalize();
  6235. }
  6236. // Y axis
  6237. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6238. this._yAxis.normalize();
  6239. // Eye angles
  6240. var ex = -Vector3.Dot(this._xAxis, eye);
  6241. var ey = -Vector3.Dot(this._yAxis, eye);
  6242. var ez = -Vector3.Dot(this._zAxis, eye);
  6243. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6244. };
  6245. /**
  6246. * Create a left-handed orthographic projection matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed orthographic projection matrix
  6252. */
  6253. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Store a left-handed orthographic projection to a given matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. */
  6266. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6267. var n = znear;
  6268. var f = zfar;
  6269. var a = 2.0 / width;
  6270. var b = 2.0 / height;
  6271. var c = 2.0 / (f - n);
  6272. var d = -(f + n) / (f - n);
  6273. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6274. };
  6275. /**
  6276. * Create a left-handed orthographic projection matrix
  6277. * @param left defines the viewport left coordinate
  6278. * @param right defines the viewport right coordinate
  6279. * @param bottom defines the viewport bottom coordinate
  6280. * @param top defines the viewport top coordinate
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed orthographic projection matrix
  6284. */
  6285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed orthographic projection into a given matrix
  6292. * @param left defines the viewport left coordinate
  6293. * @param right defines the viewport right coordinate
  6294. * @param bottom defines the viewport bottom coordinate
  6295. * @param top defines the viewport top coordinate
  6296. * @param znear defines the near clip plane
  6297. * @param zfar defines the far clip plane
  6298. * @param result defines the target matrix
  6299. */
  6300. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6301. var n = znear;
  6302. var f = zfar;
  6303. var a = 2.0 / (right - left);
  6304. var b = 2.0 / (top - bottom);
  6305. var c = 2.0 / (f - n);
  6306. var d = -(f + n) / (f - n);
  6307. var i0 = (left + right) / (left - right);
  6308. var i1 = (top + bottom) / (bottom - top);
  6309. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6310. };
  6311. /**
  6312. * Creates a right-handed orthographic projection matrix
  6313. * @param left defines the viewport left coordinate
  6314. * @param right defines the viewport right coordinate
  6315. * @param bottom defines the viewport bottom coordinate
  6316. * @param top defines the viewport top coordinate
  6317. * @param znear defines the near clip plane
  6318. * @param zfar defines the far clip plane
  6319. * @returns a new matrix as a right-handed orthographic projection matrix
  6320. */
  6321. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6322. var matrix = Matrix.Zero();
  6323. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6324. return matrix;
  6325. };
  6326. /**
  6327. * Stores a right-handed orthographic projection into a given matrix
  6328. * @param left defines the viewport left coordinate
  6329. * @param right defines the viewport right coordinate
  6330. * @param bottom defines the viewport bottom coordinate
  6331. * @param top defines the viewport top coordinate
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6337. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6338. result.m[10] *= -1.0;
  6339. };
  6340. /**
  6341. * Creates a left-handed perspective projection matrix
  6342. * @param width defines the viewport width
  6343. * @param height defines the viewport height
  6344. * @param znear defines the near clip plane
  6345. * @param zfar defines the far clip plane
  6346. * @returns a new matrix as a left-handed perspective projection matrix
  6347. */
  6348. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6349. var matrix = Matrix.Zero();
  6350. var n = znear;
  6351. var f = zfar;
  6352. var a = 2.0 * n / width;
  6353. var b = 2.0 * n / height;
  6354. var c = (f + n) / (f - n);
  6355. var d = -2.0 * f * n / (f - n);
  6356. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6357. return matrix;
  6358. };
  6359. /**
  6360. * Creates a left-handed perspective projection matrix
  6361. * @param fov defines the horizontal field of view
  6362. * @param aspect defines the aspect ratio
  6363. * @param znear defines the near clip plane
  6364. * @param zfar defines the far clip plane
  6365. * @returns a new matrix as a left-handed perspective projection matrix
  6366. */
  6367. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6368. var matrix = Matrix.Zero();
  6369. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6370. return matrix;
  6371. };
  6372. /**
  6373. * Stores a left-handed perspective projection into a given matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @param result defines the target matrix
  6379. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6380. */
  6381. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6382. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6383. var n = znear;
  6384. var f = zfar;
  6385. var t = 1.0 / (Math.tan(fov * 0.5));
  6386. var a = isVerticalFovFixed ? (t / aspect) : t;
  6387. var b = isVerticalFovFixed ? t : (t * aspect);
  6388. var c = (f + n) / (f - n);
  6389. var d = -2.0 * f * n / (f - n);
  6390. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6391. };
  6392. /**
  6393. * Creates a right-handed perspective projection matrix
  6394. * @param fov defines the horizontal field of view
  6395. * @param aspect defines the aspect ratio
  6396. * @param znear defines the near clip plane
  6397. * @param zfar defines the far clip plane
  6398. * @returns a new matrix as a right-handed perspective projection matrix
  6399. */
  6400. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6401. var matrix = Matrix.Zero();
  6402. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6403. return matrix;
  6404. };
  6405. /**
  6406. * Stores a right-handed perspective projection into a given matrix
  6407. * @param fov defines the horizontal field of view
  6408. * @param aspect defines the aspect ratio
  6409. * @param znear defines the near clip plane
  6410. * @param zfar defines the far clip plane
  6411. * @param result defines the target matrix
  6412. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6413. */
  6414. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6415. //alternatively this could be expressed as:
  6416. // m = PerspectiveFovLHToRef
  6417. // m[10] *= -1.0;
  6418. // m[11] *= -1.0;
  6419. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6420. var n = znear;
  6421. var f = zfar;
  6422. var t = 1.0 / (Math.tan(fov * 0.5));
  6423. var a = isVerticalFovFixed ? (t / aspect) : t;
  6424. var b = isVerticalFovFixed ? t : (t * aspect);
  6425. var c = -(f + n) / (f - n);
  6426. var d = -2 * f * n / (f - n);
  6427. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6428. };
  6429. /**
  6430. * Stores a perspective projection for WebVR info a given matrix
  6431. * @param fov defines the field of view
  6432. * @param znear defines the near clip plane
  6433. * @param zfar defines the far clip plane
  6434. * @param result defines the target matrix
  6435. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6436. */
  6437. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6438. if (rightHanded === void 0) { rightHanded = false; }
  6439. var rightHandedFactor = rightHanded ? -1 : 1;
  6440. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6441. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6442. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6443. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6444. var xScale = 2.0 / (leftTan + rightTan);
  6445. var yScale = 2.0 / (upTan + downTan);
  6446. result.m[0] = xScale;
  6447. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6448. result.m[5] = yScale;
  6449. result.m[6] = result.m[7] = 0.0;
  6450. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6451. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6452. result.m[10] = -zfar / (znear - zfar);
  6453. result.m[11] = 1.0 * rightHandedFactor;
  6454. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6455. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6456. result._markAsUpdated();
  6457. };
  6458. /**
  6459. * Computes a complete transformation matrix
  6460. * @param viewport defines the viewport to use
  6461. * @param world defines the world matrix
  6462. * @param view defines the view matrix
  6463. * @param projection defines the projection matrix
  6464. * @param zmin defines the near clip plane
  6465. * @param zmax defines the far clip plane
  6466. * @returns the transformation matrix
  6467. */
  6468. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6469. var cw = viewport.width;
  6470. var ch = viewport.height;
  6471. var cx = viewport.x;
  6472. var cy = viewport.y;
  6473. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6474. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6475. };
  6476. /**
  6477. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6478. * @param matrix defines the matrix to use
  6479. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6480. */
  6481. Matrix.GetAsMatrix2x2 = function (matrix) {
  6482. return new Float32Array([
  6483. matrix.m[0], matrix.m[1],
  6484. matrix.m[4], matrix.m[5]
  6485. ]);
  6486. };
  6487. /**
  6488. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6489. * @param matrix defines the matrix to use
  6490. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6491. */
  6492. Matrix.GetAsMatrix3x3 = function (matrix) {
  6493. return new Float32Array([
  6494. matrix.m[0], matrix.m[1], matrix.m[2],
  6495. matrix.m[4], matrix.m[5], matrix.m[6],
  6496. matrix.m[8], matrix.m[9], matrix.m[10]
  6497. ]);
  6498. };
  6499. /**
  6500. * Compute the transpose of a given matrix
  6501. * @param matrix defines the matrix to transpose
  6502. * @returns the new matrix
  6503. */
  6504. Matrix.Transpose = function (matrix) {
  6505. var result = new Matrix();
  6506. Matrix.TransposeToRef(matrix, result);
  6507. return result;
  6508. };
  6509. /**
  6510. * Compute the transpose of a matrix and store it in a target matrix
  6511. * @param matrix defines the matrix to transpose
  6512. * @param result defines the target matrix
  6513. */
  6514. Matrix.TransposeToRef = function (matrix, result) {
  6515. result.m[0] = matrix.m[0];
  6516. result.m[1] = matrix.m[4];
  6517. result.m[2] = matrix.m[8];
  6518. result.m[3] = matrix.m[12];
  6519. result.m[4] = matrix.m[1];
  6520. result.m[5] = matrix.m[5];
  6521. result.m[6] = matrix.m[9];
  6522. result.m[7] = matrix.m[13];
  6523. result.m[8] = matrix.m[2];
  6524. result.m[9] = matrix.m[6];
  6525. result.m[10] = matrix.m[10];
  6526. result.m[11] = matrix.m[14];
  6527. result.m[12] = matrix.m[3];
  6528. result.m[13] = matrix.m[7];
  6529. result.m[14] = matrix.m[11];
  6530. result.m[15] = matrix.m[15];
  6531. };
  6532. /**
  6533. * Computes a reflection matrix from a plane
  6534. * @param plane defines the reflection plane
  6535. * @returns a new matrix
  6536. */
  6537. Matrix.Reflection = function (plane) {
  6538. var matrix = new Matrix();
  6539. Matrix.ReflectionToRef(plane, matrix);
  6540. return matrix;
  6541. };
  6542. /**
  6543. * Computes a reflection matrix from a plane
  6544. * @param plane defines the reflection plane
  6545. * @param result defines the target matrix
  6546. */
  6547. Matrix.ReflectionToRef = function (plane, result) {
  6548. plane.normalize();
  6549. var x = plane.normal.x;
  6550. var y = plane.normal.y;
  6551. var z = plane.normal.z;
  6552. var temp = -2 * x;
  6553. var temp2 = -2 * y;
  6554. var temp3 = -2 * z;
  6555. result.m[0] = (temp * x) + 1;
  6556. result.m[1] = temp2 * x;
  6557. result.m[2] = temp3 * x;
  6558. result.m[3] = 0.0;
  6559. result.m[4] = temp * y;
  6560. result.m[5] = (temp2 * y) + 1;
  6561. result.m[6] = temp3 * y;
  6562. result.m[7] = 0.0;
  6563. result.m[8] = temp * z;
  6564. result.m[9] = temp2 * z;
  6565. result.m[10] = (temp3 * z) + 1;
  6566. result.m[11] = 0.0;
  6567. result.m[12] = temp * plane.d;
  6568. result.m[13] = temp2 * plane.d;
  6569. result.m[14] = temp3 * plane.d;
  6570. result.m[15] = 1.0;
  6571. result._markAsUpdated();
  6572. };
  6573. /**
  6574. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6575. * @param xaxis defines the value of the 1st axis
  6576. * @param yaxis defines the value of the 2nd axis
  6577. * @param zaxis defines the value of the 3rd axis
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6581. result.m[0] = xaxis.x;
  6582. result.m[1] = xaxis.y;
  6583. result.m[2] = xaxis.z;
  6584. result.m[3] = 0.0;
  6585. result.m[4] = yaxis.x;
  6586. result.m[5] = yaxis.y;
  6587. result.m[6] = yaxis.z;
  6588. result.m[7] = 0.0;
  6589. result.m[8] = zaxis.x;
  6590. result.m[9] = zaxis.y;
  6591. result.m[10] = zaxis.z;
  6592. result.m[11] = 0.0;
  6593. result.m[12] = 0.0;
  6594. result.m[13] = 0.0;
  6595. result.m[14] = 0.0;
  6596. result.m[15] = 1.0;
  6597. result._markAsUpdated();
  6598. };
  6599. /**
  6600. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6601. * @param quat defines the quaternion to use
  6602. * @param result defines the target matrix
  6603. */
  6604. Matrix.FromQuaternionToRef = function (quat, result) {
  6605. var xx = quat.x * quat.x;
  6606. var yy = quat.y * quat.y;
  6607. var zz = quat.z * quat.z;
  6608. var xy = quat.x * quat.y;
  6609. var zw = quat.z * quat.w;
  6610. var zx = quat.z * quat.x;
  6611. var yw = quat.y * quat.w;
  6612. var yz = quat.y * quat.z;
  6613. var xw = quat.x * quat.w;
  6614. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6615. result.m[1] = 2.0 * (xy + zw);
  6616. result.m[2] = 2.0 * (zx - yw);
  6617. result.m[3] = 0.0;
  6618. result.m[4] = 2.0 * (xy - zw);
  6619. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6620. result.m[6] = 2.0 * (yz + xw);
  6621. result.m[7] = 0.0;
  6622. result.m[8] = 2.0 * (zx + yw);
  6623. result.m[9] = 2.0 * (yz - xw);
  6624. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6625. result.m[11] = 0.0;
  6626. result.m[12] = 0.0;
  6627. result.m[13] = 0.0;
  6628. result.m[14] = 0.0;
  6629. result.m[15] = 1.0;
  6630. result._markAsUpdated();
  6631. };
  6632. Matrix._tempQuaternion = new Quaternion();
  6633. Matrix._xAxis = Vector3.Zero();
  6634. Matrix._yAxis = Vector3.Zero();
  6635. Matrix._zAxis = Vector3.Zero();
  6636. Matrix._updateFlagSeed = 0;
  6637. Matrix._identityReadOnly = Matrix.Identity();
  6638. return Matrix;
  6639. }());
  6640. BABYLON.Matrix = Matrix;
  6641. var Plane = /** @class */ (function () {
  6642. /**
  6643. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6644. */
  6645. function Plane(a, b, c, d) {
  6646. this.normal = new Vector3(a, b, c);
  6647. this.d = d;
  6648. }
  6649. /**
  6650. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6651. */
  6652. Plane.prototype.asArray = function () {
  6653. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6654. };
  6655. // Methods
  6656. /**
  6657. * Returns a new plane copied from the current Plane.
  6658. */
  6659. Plane.prototype.clone = function () {
  6660. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6661. };
  6662. /**
  6663. * Returns the string "Plane".
  6664. */
  6665. Plane.prototype.getClassName = function () {
  6666. return "Plane";
  6667. };
  6668. /**
  6669. * Returns the Plane hash code.
  6670. */
  6671. Plane.prototype.getHashCode = function () {
  6672. var hash = this.normal.getHashCode();
  6673. hash = (hash * 397) ^ (this.d || 0);
  6674. return hash;
  6675. };
  6676. /**
  6677. * Normalize the current Plane in place.
  6678. * Returns the updated Plane.
  6679. */
  6680. Plane.prototype.normalize = function () {
  6681. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6682. var magnitude = 0.0;
  6683. if (norm !== 0) {
  6684. magnitude = 1.0 / norm;
  6685. }
  6686. this.normal.x *= magnitude;
  6687. this.normal.y *= magnitude;
  6688. this.normal.z *= magnitude;
  6689. this.d *= magnitude;
  6690. return this;
  6691. };
  6692. /**
  6693. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6694. */
  6695. Plane.prototype.transform = function (transformation) {
  6696. var transposedMatrix = Matrix.Transpose(transformation);
  6697. var x = this.normal.x;
  6698. var y = this.normal.y;
  6699. var z = this.normal.z;
  6700. var d = this.d;
  6701. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6702. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6703. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6704. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6705. return new Plane(normalX, normalY, normalZ, finalD);
  6706. };
  6707. /**
  6708. * Returns the dot product (float) of the point coordinates and the plane normal.
  6709. */
  6710. Plane.prototype.dotCoordinate = function (point) {
  6711. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6712. };
  6713. /**
  6714. * Updates the current Plane from the plane defined by the three given points.
  6715. * Returns the updated Plane.
  6716. */
  6717. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6718. var x1 = point2.x - point1.x;
  6719. var y1 = point2.y - point1.y;
  6720. var z1 = point2.z - point1.z;
  6721. var x2 = point3.x - point1.x;
  6722. var y2 = point3.y - point1.y;
  6723. var z2 = point3.z - point1.z;
  6724. var yz = (y1 * z2) - (z1 * y2);
  6725. var xz = (z1 * x2) - (x1 * z2);
  6726. var xy = (x1 * y2) - (y1 * x2);
  6727. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6728. var invPyth;
  6729. if (pyth !== 0) {
  6730. invPyth = 1.0 / pyth;
  6731. }
  6732. else {
  6733. invPyth = 0.0;
  6734. }
  6735. this.normal.x = yz * invPyth;
  6736. this.normal.y = xz * invPyth;
  6737. this.normal.z = xy * invPyth;
  6738. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6739. return this;
  6740. };
  6741. /**
  6742. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6743. */
  6744. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6745. var dot = Vector3.Dot(this.normal, direction);
  6746. return (dot <= epsilon);
  6747. };
  6748. /**
  6749. * Returns the signed distance (float) from the given point to the Plane.
  6750. */
  6751. Plane.prototype.signedDistanceTo = function (point) {
  6752. return Vector3.Dot(point, this.normal) + this.d;
  6753. };
  6754. // Statics
  6755. /**
  6756. * Returns a new Plane from the given array.
  6757. */
  6758. Plane.FromArray = function (array) {
  6759. return new Plane(array[0], array[1], array[2], array[3]);
  6760. };
  6761. /**
  6762. * Returns a new Plane defined by the three given points.
  6763. */
  6764. Plane.FromPoints = function (point1, point2, point3) {
  6765. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6766. result.copyFromPoints(point1, point2, point3);
  6767. return result;
  6768. };
  6769. /**
  6770. * Returns a new Plane the normal vector to this plane at the given origin point.
  6771. * Note : the vector "normal" is updated because normalized.
  6772. */
  6773. Plane.FromPositionAndNormal = function (origin, normal) {
  6774. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6775. normal.normalize();
  6776. result.normal = normal;
  6777. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6778. return result;
  6779. };
  6780. /**
  6781. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6782. */
  6783. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6784. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return Vector3.Dot(point, normal) + d;
  6786. };
  6787. return Plane;
  6788. }());
  6789. BABYLON.Plane = Plane;
  6790. var Viewport = /** @class */ (function () {
  6791. /**
  6792. * Creates a Viewport object located at (x, y) and sized (width, height).
  6793. */
  6794. function Viewport(x, y, width, height) {
  6795. this.x = x;
  6796. this.y = y;
  6797. this.width = width;
  6798. this.height = height;
  6799. }
  6800. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6801. if (renderWidthOrEngine.getRenderWidth) {
  6802. var engine = renderWidthOrEngine;
  6803. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6804. }
  6805. var renderWidth = renderWidthOrEngine;
  6806. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6807. };
  6808. /**
  6809. * Returns a new Viewport copied from the current one.
  6810. */
  6811. Viewport.prototype.clone = function () {
  6812. return new Viewport(this.x, this.y, this.width, this.height);
  6813. };
  6814. return Viewport;
  6815. }());
  6816. BABYLON.Viewport = Viewport;
  6817. var Frustum = /** @class */ (function () {
  6818. function Frustum() {
  6819. }
  6820. /**
  6821. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6822. */
  6823. Frustum.GetPlanes = function (transform) {
  6824. var frustumPlanes = [];
  6825. for (var index = 0; index < 6; index++) {
  6826. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6827. }
  6828. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6829. return frustumPlanes;
  6830. };
  6831. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6835. frustumPlane.d = transform.m[15] + transform.m[14];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6842. frustumPlane.d = transform.m[15] - transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6847. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6848. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6849. frustumPlane.d = transform.m[15] + transform.m[12];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6856. frustumPlane.d = transform.m[15] - transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6863. frustumPlane.d = transform.m[15] - transform.m[13];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6870. frustumPlane.d = transform.m[15] + transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. /**
  6874. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6875. */
  6876. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6877. // Near
  6878. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6879. // Far
  6880. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6881. // Left
  6882. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6883. // Right
  6884. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6885. // Top
  6886. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6887. // Bottom
  6888. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6889. };
  6890. return Frustum;
  6891. }());
  6892. BABYLON.Frustum = Frustum;
  6893. /** Defines supported spaces */
  6894. var Space;
  6895. (function (Space) {
  6896. /** Local (object) space */
  6897. Space[Space["LOCAL"] = 0] = "LOCAL";
  6898. /** World space */
  6899. Space[Space["WORLD"] = 1] = "WORLD";
  6900. /** Bone space */
  6901. Space[Space["BONE"] = 2] = "BONE";
  6902. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6903. /** Defines the 3 main axes */
  6904. var Axis = /** @class */ (function () {
  6905. function Axis() {
  6906. }
  6907. /** X axis */
  6908. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6909. /** Y axis */
  6910. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6911. /** Z axis */
  6912. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6913. return Axis;
  6914. }());
  6915. BABYLON.Axis = Axis;
  6916. ;
  6917. var BezierCurve = /** @class */ (function () {
  6918. function BezierCurve() {
  6919. }
  6920. /**
  6921. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6922. */
  6923. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6924. // Extract X (which is equal to time here)
  6925. var f0 = 1 - 3 * x2 + 3 * x1;
  6926. var f1 = 3 * x2 - 6 * x1;
  6927. var f2 = 3 * x1;
  6928. var refinedT = t;
  6929. for (var i = 0; i < 5; i++) {
  6930. var refinedT2 = refinedT * refinedT;
  6931. var refinedT3 = refinedT2 * refinedT;
  6932. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6933. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6934. refinedT -= (x - t) * slope;
  6935. refinedT = Math.min(1, Math.max(0, refinedT));
  6936. }
  6937. // Resolve cubic bezier for the given x
  6938. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6939. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6940. Math.pow(refinedT, 3);
  6941. };
  6942. return BezierCurve;
  6943. }());
  6944. BABYLON.BezierCurve = BezierCurve;
  6945. /**
  6946. * Defines potential orientation for back face culling
  6947. */
  6948. var Orientation;
  6949. (function (Orientation) {
  6950. /**
  6951. * Clockwise
  6952. */
  6953. Orientation[Orientation["CW"] = 0] = "CW";
  6954. /** Counter clockwise */
  6955. Orientation[Orientation["CCW"] = 1] = "CCW";
  6956. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6957. /**
  6958. * Defines angle representation
  6959. */
  6960. var Angle = /** @class */ (function () {
  6961. /**
  6962. * Creates an Angle object of "radians" radians (float).
  6963. */
  6964. function Angle(radians) {
  6965. this._radians = radians;
  6966. if (this._radians < 0.0)
  6967. this._radians += (2.0 * Math.PI);
  6968. }
  6969. /**
  6970. * Get value in degrees
  6971. * @returns the Angle value in degrees (float)
  6972. */
  6973. Angle.prototype.degrees = function () {
  6974. return this._radians * 180.0 / Math.PI;
  6975. };
  6976. /**
  6977. * Get value in radians
  6978. * @returns the Angle value in radians (float)
  6979. */
  6980. Angle.prototype.radians = function () {
  6981. return this._radians;
  6982. };
  6983. /**
  6984. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6985. * @param a defines first vector
  6986. * @param b defines second vector
  6987. * @returns a new Angle
  6988. */
  6989. Angle.BetweenTwoPoints = function (a, b) {
  6990. var delta = b.subtract(a);
  6991. var theta = Math.atan2(delta.y, delta.x);
  6992. return new Angle(theta);
  6993. };
  6994. /**
  6995. * Gets a new Angle object from the given float in radians
  6996. * @param radians defines the angle value in radians
  6997. * @returns a new Angle
  6998. */
  6999. Angle.FromRadians = function (radians) {
  7000. return new Angle(radians);
  7001. };
  7002. /**
  7003. * Gets a new Angle object from the given float in degrees
  7004. * @param degrees defines the angle value in degrees
  7005. * @returns a new Angle
  7006. */
  7007. Angle.FromDegrees = function (degrees) {
  7008. return new Angle(degrees * Math.PI / 180.0);
  7009. };
  7010. return Angle;
  7011. }());
  7012. BABYLON.Angle = Angle;
  7013. var Arc2 = /** @class */ (function () {
  7014. /**
  7015. * Creates an Arc object from the three given points : start, middle and end.
  7016. */
  7017. function Arc2(startPoint, midPoint, endPoint) {
  7018. this.startPoint = startPoint;
  7019. this.midPoint = midPoint;
  7020. this.endPoint = endPoint;
  7021. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7022. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7023. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7024. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7025. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7026. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7027. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7028. var a1 = this.startAngle.degrees();
  7029. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7030. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7031. // angles correction
  7032. if (a2 - a1 > +180.0)
  7033. a2 -= 360.0;
  7034. if (a2 - a1 < -180.0)
  7035. a2 += 360.0;
  7036. if (a3 - a2 > +180.0)
  7037. a3 -= 360.0;
  7038. if (a3 - a2 < -180.0)
  7039. a3 += 360.0;
  7040. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7041. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7042. }
  7043. return Arc2;
  7044. }());
  7045. BABYLON.Arc2 = Arc2;
  7046. var Path2 = /** @class */ (function () {
  7047. /**
  7048. * Creates a Path2 object from the starting 2D coordinates x and y.
  7049. */
  7050. function Path2(x, y) {
  7051. this._points = new Array();
  7052. this._length = 0.0;
  7053. this.closed = false;
  7054. this._points.push(new Vector2(x, y));
  7055. }
  7056. /**
  7057. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addLineTo = function (x, y) {
  7061. if (this.closed) {
  7062. return this;
  7063. }
  7064. var newPoint = new Vector2(x, y);
  7065. var previousPoint = this._points[this._points.length - 1];
  7066. this._points.push(newPoint);
  7067. this._length += newPoint.subtract(previousPoint).length();
  7068. return this;
  7069. };
  7070. /**
  7071. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7072. * Returns the updated Path2.
  7073. */
  7074. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7075. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7076. if (this.closed) {
  7077. return this;
  7078. }
  7079. var startPoint = this._points[this._points.length - 1];
  7080. var midPoint = new Vector2(midX, midY);
  7081. var endPoint = new Vector2(endX, endY);
  7082. var arc = new Arc2(startPoint, midPoint, endPoint);
  7083. var increment = arc.angle.radians() / numberOfSegments;
  7084. if (arc.orientation === Orientation.CW)
  7085. increment *= -1;
  7086. var currentAngle = arc.startAngle.radians() + increment;
  7087. for (var i = 0; i < numberOfSegments; i++) {
  7088. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7089. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7090. this.addLineTo(x, y);
  7091. currentAngle += increment;
  7092. }
  7093. return this;
  7094. };
  7095. /**
  7096. * Closes the Path2.
  7097. * Returns the Path2.
  7098. */
  7099. Path2.prototype.close = function () {
  7100. this.closed = true;
  7101. return this;
  7102. };
  7103. /**
  7104. * Returns the Path2 total length (float).
  7105. */
  7106. Path2.prototype.length = function () {
  7107. var result = this._length;
  7108. if (!this.closed) {
  7109. var lastPoint = this._points[this._points.length - 1];
  7110. var firstPoint = this._points[0];
  7111. result += (firstPoint.subtract(lastPoint).length());
  7112. }
  7113. return result;
  7114. };
  7115. /**
  7116. * Returns the Path2 internal array of points.
  7117. */
  7118. Path2.prototype.getPoints = function () {
  7119. return this._points;
  7120. };
  7121. /**
  7122. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7123. */
  7124. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7125. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7126. return Vector2.Zero();
  7127. }
  7128. var lengthPosition = normalizedLengthPosition * this.length();
  7129. var previousOffset = 0;
  7130. for (var i = 0; i < this._points.length; i++) {
  7131. var j = (i + 1) % this._points.length;
  7132. var a = this._points[i];
  7133. var b = this._points[j];
  7134. var bToA = b.subtract(a);
  7135. var nextOffset = (bToA.length() + previousOffset);
  7136. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7137. var dir = bToA.normalize();
  7138. var localOffset = lengthPosition - previousOffset;
  7139. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7140. }
  7141. previousOffset = nextOffset;
  7142. }
  7143. return Vector2.Zero();
  7144. };
  7145. /**
  7146. * Returns a new Path2 starting at the coordinates (x, y).
  7147. */
  7148. Path2.StartingAt = function (x, y) {
  7149. return new Path2(x, y);
  7150. };
  7151. return Path2;
  7152. }());
  7153. BABYLON.Path2 = Path2;
  7154. var Path3D = /** @class */ (function () {
  7155. /**
  7156. * new Path3D(path, normal, raw)
  7157. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7158. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7159. * path : an array of Vector3, the curve axis of the Path3D
  7160. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7161. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7162. */
  7163. function Path3D(path, firstNormal, raw) {
  7164. if (firstNormal === void 0) { firstNormal = null; }
  7165. this.path = path;
  7166. this._curve = new Array();
  7167. this._distances = new Array();
  7168. this._tangents = new Array();
  7169. this._normals = new Array();
  7170. this._binormals = new Array();
  7171. for (var p = 0; p < path.length; p++) {
  7172. this._curve[p] = path[p].clone(); // hard copy
  7173. }
  7174. this._raw = raw || false;
  7175. this._compute(firstNormal);
  7176. }
  7177. /**
  7178. * Returns the Path3D array of successive Vector3 designing its curve.
  7179. */
  7180. Path3D.prototype.getCurve = function () {
  7181. return this._curve;
  7182. };
  7183. /**
  7184. * Returns an array populated with tangent vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getTangents = function () {
  7187. return this._tangents;
  7188. };
  7189. /**
  7190. * Returns an array populated with normal vectors on each Path3D curve point.
  7191. */
  7192. Path3D.prototype.getNormals = function () {
  7193. return this._normals;
  7194. };
  7195. /**
  7196. * Returns an array populated with binormal vectors on each Path3D curve point.
  7197. */
  7198. Path3D.prototype.getBinormals = function () {
  7199. return this._binormals;
  7200. };
  7201. /**
  7202. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7203. */
  7204. Path3D.prototype.getDistances = function () {
  7205. return this._distances;
  7206. };
  7207. /**
  7208. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7209. * Returns the same object updated.
  7210. */
  7211. Path3D.prototype.update = function (path, firstNormal) {
  7212. if (firstNormal === void 0) { firstNormal = null; }
  7213. for (var p = 0; p < path.length; p++) {
  7214. this._curve[p].x = path[p].x;
  7215. this._curve[p].y = path[p].y;
  7216. this._curve[p].z = path[p].z;
  7217. }
  7218. this._compute(firstNormal);
  7219. return this;
  7220. };
  7221. // private function compute() : computes tangents, normals and binormals
  7222. Path3D.prototype._compute = function (firstNormal) {
  7223. var l = this._curve.length;
  7224. // first and last tangents
  7225. this._tangents[0] = this._getFirstNonNullVector(0);
  7226. if (!this._raw) {
  7227. this._tangents[0].normalize();
  7228. }
  7229. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7230. if (!this._raw) {
  7231. this._tangents[l - 1].normalize();
  7232. }
  7233. // normals and binormals at first point : arbitrary vector with _normalVector()
  7234. var tg0 = this._tangents[0];
  7235. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7236. this._normals[0] = pp0;
  7237. if (!this._raw) {
  7238. this._normals[0].normalize();
  7239. }
  7240. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7241. if (!this._raw) {
  7242. this._binormals[0].normalize();
  7243. }
  7244. this._distances[0] = 0.0;
  7245. // normals and binormals : next points
  7246. var prev; // previous vector (segment)
  7247. var cur; // current vector (segment)
  7248. var curTang; // current tangent
  7249. // previous normal
  7250. var prevBinor; // previous binormal
  7251. for (var i = 1; i < l; i++) {
  7252. // tangents
  7253. prev = this._getLastNonNullVector(i);
  7254. if (i < l - 1) {
  7255. cur = this._getFirstNonNullVector(i);
  7256. this._tangents[i] = prev.add(cur);
  7257. this._tangents[i].normalize();
  7258. }
  7259. this._distances[i] = this._distances[i - 1] + prev.length();
  7260. // normals and binormals
  7261. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7262. curTang = this._tangents[i];
  7263. prevBinor = this._binormals[i - 1];
  7264. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7265. if (!this._raw) {
  7266. this._normals[i].normalize();
  7267. }
  7268. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7269. if (!this._raw) {
  7270. this._binormals[i].normalize();
  7271. }
  7272. }
  7273. };
  7274. // private function getFirstNonNullVector(index)
  7275. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7276. Path3D.prototype._getFirstNonNullVector = function (index) {
  7277. var i = 1;
  7278. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7279. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7280. i++;
  7281. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7282. }
  7283. return nNVector;
  7284. };
  7285. // private function getLastNonNullVector(index)
  7286. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7287. Path3D.prototype._getLastNonNullVector = function (index) {
  7288. var i = 1;
  7289. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7290. while (nLVector.length() === 0 && index > i + 1) {
  7291. i++;
  7292. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7293. }
  7294. return nLVector;
  7295. };
  7296. // private function normalVector(v0, vt, va) :
  7297. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7298. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7299. Path3D.prototype._normalVector = function (v0, vt, va) {
  7300. var normal0;
  7301. var tgl = vt.length();
  7302. if (tgl === 0.0) {
  7303. tgl = 1.0;
  7304. }
  7305. if (va === undefined || va === null) {
  7306. var point;
  7307. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7308. point = new Vector3(0.0, -1.0, 0.0);
  7309. }
  7310. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7311. point = new Vector3(1.0, 0.0, 0.0);
  7312. }
  7313. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7314. point = new Vector3(0.0, 0.0, 1.0);
  7315. }
  7316. else {
  7317. point = Vector3.Zero();
  7318. }
  7319. normal0 = Vector3.Cross(vt, point);
  7320. }
  7321. else {
  7322. normal0 = Vector3.Cross(vt, va);
  7323. Vector3.CrossToRef(normal0, vt, normal0);
  7324. }
  7325. normal0.normalize();
  7326. return normal0;
  7327. };
  7328. return Path3D;
  7329. }());
  7330. BABYLON.Path3D = Path3D;
  7331. var Curve3 = /** @class */ (function () {
  7332. /**
  7333. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7334. * A Curve3 is designed from a series of successive Vector3.
  7335. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7336. */
  7337. function Curve3(points) {
  7338. this._length = 0.0;
  7339. this._points = points;
  7340. this._length = this._computeLength(points);
  7341. }
  7342. /**
  7343. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7344. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7345. * @param v1 (Vector3) the control point
  7346. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7350. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2) {
  7353. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7363. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7364. * @param v1 (Vector3) the first control point
  7365. * @param v2 (Vector3) the second control point
  7366. * @param v3 (Vector3) the end point of the Cubic Bezier
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7370. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7371. var bez = new Array();
  7372. var equation = function (t, val0, val1, val2, val3) {
  7373. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7374. return res;
  7375. };
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7378. }
  7379. return new Curve3(bez);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7383. * @param p1 (Vector3) the origin point of the Hermite Spline
  7384. * @param t1 (Vector3) the tangent vector at the origin point
  7385. * @param p2 (Vector3) the end point of the Hermite Spline
  7386. * @param t2 (Vector3) the tangent vector at the end point
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7390. var hermite = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. for (var i = 0; i <= nbPoints; i++) {
  7393. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7394. }
  7395. return new Curve3(hermite);
  7396. };
  7397. /**
  7398. * Returns a Curve3 object along a CatmullRom Spline curve :
  7399. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7400. * @param nbPoints (integer) the wanted number of points between each curve control points
  7401. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7402. */
  7403. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7404. var catmullRom = new Array();
  7405. var step = 1.0 / nbPoints;
  7406. var amount = 0.0;
  7407. if (closed) {
  7408. var pointsCount = points.length;
  7409. for (var i = 0; i < pointsCount; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. catmullRom.push(catmullRom[0]);
  7417. }
  7418. else {
  7419. var totalPoints = new Array();
  7420. totalPoints.push(points[0].clone());
  7421. Array.prototype.push.apply(totalPoints, points);
  7422. totalPoints.push(points[points.length - 1].clone());
  7423. for (var i = 0; i < totalPoints.length - 3; i++) {
  7424. amount = 0;
  7425. for (var c = 0; c < nbPoints; c++) {
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. amount += step;
  7428. }
  7429. }
  7430. i--;
  7431. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7432. }
  7433. return new Curve3(catmullRom);
  7434. };
  7435. /**
  7436. * Returns the Curve3 stored array of successive Vector3
  7437. */
  7438. Curve3.prototype.getPoints = function () {
  7439. return this._points;
  7440. };
  7441. /**
  7442. * Returns the computed length (float) of the curve.
  7443. */
  7444. Curve3.prototype.length = function () {
  7445. return this._length;
  7446. };
  7447. /**
  7448. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7449. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7450. * curveA and curveB keep unchanged.
  7451. */
  7452. Curve3.prototype.continue = function (curve) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var continuedPoints = this._points.slice();
  7455. var curvePoints = curve.getPoints();
  7456. for (var i = 1; i < curvePoints.length; i++) {
  7457. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7458. }
  7459. var continuedCurve = new Curve3(continuedPoints);
  7460. return continuedCurve;
  7461. };
  7462. Curve3.prototype._computeLength = function (path) {
  7463. var l = 0;
  7464. for (var i = 1; i < path.length; i++) {
  7465. l += (path[i].subtract(path[i - 1])).length();
  7466. }
  7467. return l;
  7468. };
  7469. return Curve3;
  7470. }());
  7471. BABYLON.Curve3 = Curve3;
  7472. // Vertex formats
  7473. var PositionNormalVertex = /** @class */ (function () {
  7474. function PositionNormalVertex(position, normal) {
  7475. if (position === void 0) { position = Vector3.Zero(); }
  7476. if (normal === void 0) { normal = Vector3.Up(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. }
  7480. PositionNormalVertex.prototype.clone = function () {
  7481. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7482. };
  7483. return PositionNormalVertex;
  7484. }());
  7485. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7486. var PositionNormalTextureVertex = /** @class */ (function () {
  7487. function PositionNormalTextureVertex(position, normal, uv) {
  7488. if (position === void 0) { position = Vector3.Zero(); }
  7489. if (normal === void 0) { normal = Vector3.Up(); }
  7490. if (uv === void 0) { uv = Vector2.Zero(); }
  7491. this.position = position;
  7492. this.normal = normal;
  7493. this.uv = uv;
  7494. }
  7495. PositionNormalTextureVertex.prototype.clone = function () {
  7496. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7497. };
  7498. return PositionNormalTextureVertex;
  7499. }());
  7500. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7501. // Temporary pre-allocated objects for engine internal use
  7502. // usage in any internal function :
  7503. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7504. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7505. var Tmp = /** @class */ (function () {
  7506. function Tmp() {
  7507. }
  7508. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7509. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7510. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7511. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7512. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7513. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7514. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7515. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7516. Matrix.Zero(), Matrix.Zero(),
  7517. Matrix.Zero(), Matrix.Zero(),
  7518. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7519. return Tmp;
  7520. }());
  7521. BABYLON.Tmp = Tmp;
  7522. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7523. var MathTmp = /** @class */ (function () {
  7524. function MathTmp() {
  7525. }
  7526. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7527. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7528. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7529. return MathTmp;
  7530. }());
  7531. })(BABYLON || (BABYLON = {}));
  7532. //# sourceMappingURL=babylon.math.js.map
  7533. var BABYLON;
  7534. (function (BABYLON) {
  7535. var Scalar = /** @class */ (function () {
  7536. function Scalar() {
  7537. }
  7538. /**
  7539. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7540. */
  7541. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7542. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7543. var num = a - b;
  7544. return -epsilon <= num && num <= epsilon;
  7545. };
  7546. /**
  7547. * Returns a string : the upper case translation of the number i to hexadecimal.
  7548. */
  7549. Scalar.ToHex = function (i) {
  7550. var str = i.toString(16);
  7551. if (i <= 15) {
  7552. return ("0" + str).toUpperCase();
  7553. }
  7554. return str.toUpperCase();
  7555. };
  7556. /**
  7557. * Returns -1 if value is negative and +1 is value is positive.
  7558. * Returns the value itself if it's equal to zero.
  7559. */
  7560. Scalar.Sign = function (value) {
  7561. value = +value; // convert to a number
  7562. if (value === 0 || isNaN(value))
  7563. return value;
  7564. return value > 0 ? 1 : -1;
  7565. };
  7566. /**
  7567. * Returns the value itself if it's between min and max.
  7568. * Returns min if the value is lower than min.
  7569. * Returns max if the value is greater than max.
  7570. */
  7571. Scalar.Clamp = function (value, min, max) {
  7572. if (min === void 0) { min = 0; }
  7573. if (max === void 0) { max = 1; }
  7574. return Math.min(max, Math.max(min, value));
  7575. };
  7576. /**
  7577. * Returns the log2 of value.
  7578. */
  7579. Scalar.Log2 = function (value) {
  7580. return Math.log(value) * Math.LOG2E;
  7581. };
  7582. /**
  7583. * Loops the value, so that it is never larger than length and never smaller than 0.
  7584. *
  7585. * This is similar to the modulo operator but it works with floating point numbers.
  7586. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7587. * With t = 5 and length = 2.5, the result would be 0.0.
  7588. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7589. */
  7590. Scalar.Repeat = function (value, length) {
  7591. return value - Math.floor(value / length) * length;
  7592. };
  7593. /**
  7594. * Normalize the value between 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Normalize = function (value, min, max) {
  7597. return (value - min) / (max - min);
  7598. };
  7599. /**
  7600. * Denormalize the value from 0.0 and 1.0 using min and max values
  7601. */
  7602. Scalar.Denormalize = function (normalized, min, max) {
  7603. return (normalized * (max - min) + min);
  7604. };
  7605. /**
  7606. * Calculates the shortest difference between two given angles given in degrees.
  7607. */
  7608. Scalar.DeltaAngle = function (current, target) {
  7609. var num = Scalar.Repeat(target - current, 360.0);
  7610. if (num > 180.0) {
  7611. num -= 360.0;
  7612. }
  7613. return num;
  7614. };
  7615. /**
  7616. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7617. *
  7618. * The returned value will move back and forth between 0 and length
  7619. */
  7620. Scalar.PingPong = function (tx, length) {
  7621. var t = Scalar.Repeat(tx, length * 2.0);
  7622. return length - Math.abs(t - length);
  7623. };
  7624. /**
  7625. * Interpolates between min and max with smoothing at the limits.
  7626. *
  7627. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7628. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7629. */
  7630. Scalar.SmoothStep = function (from, to, tx) {
  7631. var t = Scalar.Clamp(tx);
  7632. t = -2.0 * t * t * t + 3.0 * t * t;
  7633. return to * t + from * (1.0 - t);
  7634. };
  7635. /**
  7636. * Moves a value current towards target.
  7637. *
  7638. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7639. * Negative values of maxDelta pushes the value away from target.
  7640. */
  7641. Scalar.MoveTowards = function (current, target, maxDelta) {
  7642. var result = 0;
  7643. if (Math.abs(target - current) <= maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. result = current + Scalar.Sign(target - current) * maxDelta;
  7648. }
  7649. return result;
  7650. };
  7651. /**
  7652. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7653. *
  7654. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7655. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7656. */
  7657. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7658. var num = Scalar.DeltaAngle(current, target);
  7659. var result = 0;
  7660. if (-maxDelta < num && num < maxDelta) {
  7661. result = target;
  7662. }
  7663. else {
  7664. target = current + num;
  7665. result = Scalar.MoveTowards(current, target, maxDelta);
  7666. }
  7667. return result;
  7668. };
  7669. /**
  7670. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7671. */
  7672. Scalar.Lerp = function (start, end, amount) {
  7673. return start + ((end - start) * amount);
  7674. };
  7675. /**
  7676. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7677. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7678. */
  7679. Scalar.LerpAngle = function (start, end, amount) {
  7680. var num = Scalar.Repeat(end - start, 360.0);
  7681. if (num > 180.0) {
  7682. num -= 360.0;
  7683. }
  7684. return start + num * Scalar.Clamp(amount);
  7685. };
  7686. /**
  7687. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7688. */
  7689. Scalar.InverseLerp = function (a, b, value) {
  7690. var result = 0;
  7691. if (a != b) {
  7692. result = Scalar.Clamp((value - a) / (b - a));
  7693. }
  7694. else {
  7695. result = 0.0;
  7696. }
  7697. return result;
  7698. };
  7699. /**
  7700. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7701. */
  7702. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7703. var squared = amount * amount;
  7704. var cubed = amount * squared;
  7705. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7706. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7707. var part3 = (cubed - (2.0 * squared)) + amount;
  7708. var part4 = cubed - squared;
  7709. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7710. };
  7711. /**
  7712. * Returns a random float number between and min and max values
  7713. */
  7714. Scalar.RandomRange = function (min, max) {
  7715. if (min === max)
  7716. return min;
  7717. return ((Math.random() * (max - min)) + min);
  7718. };
  7719. /**
  7720. * This function returns percentage of a number in a given range.
  7721. *
  7722. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7723. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7724. */
  7725. Scalar.RangeToPercent = function (number, min, max) {
  7726. return ((number - min) / (max - min));
  7727. };
  7728. /**
  7729. * This function returns number that corresponds to the percentage in a given range.
  7730. *
  7731. * PercentToRange(0.34,0,100) will return 34.
  7732. */
  7733. Scalar.PercentToRange = function (percent, min, max) {
  7734. return ((max - min) * percent + min);
  7735. };
  7736. /**
  7737. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7738. * @param angle The angle to normalize in radian.
  7739. * @return The converted angle.
  7740. */
  7741. Scalar.NormalizeRadians = function (angle) {
  7742. // More precise but slower version kept for reference.
  7743. // angle = angle % Tools.TwoPi;
  7744. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7745. //if (angle > Math.PI) {
  7746. // angle -= Tools.TwoPi;
  7747. //}
  7748. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7749. return angle;
  7750. };
  7751. /**
  7752. * Two pi constants convenient for computation.
  7753. */
  7754. Scalar.TwoPi = Math.PI * 2;
  7755. return Scalar;
  7756. }());
  7757. BABYLON.Scalar = Scalar;
  7758. })(BABYLON || (BABYLON = {}));
  7759. //# sourceMappingURL=babylon.math.scalar.js.map
  7760. //# sourceMappingURL=babylon.mixins.js.map
  7761. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7762. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7763. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7764. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7765. //# sourceMappingURL=babylon.webgl2.js.map
  7766. var BABYLON;
  7767. (function (BABYLON) {
  7768. var __decoratorInitialStore = {};
  7769. var __mergedStore = {};
  7770. var _copySource = function (creationFunction, source, instanciate) {
  7771. var destination = creationFunction();
  7772. // Tags
  7773. if (BABYLON.Tags) {
  7774. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7775. }
  7776. var classStore = getMergedStore(destination);
  7777. // Properties
  7778. for (var property in classStore) {
  7779. var propertyDescriptor = classStore[property];
  7780. var sourceProperty = source[property];
  7781. var propertyType = propertyDescriptor.type;
  7782. if (sourceProperty !== undefined && sourceProperty !== null) {
  7783. switch (propertyType) {
  7784. case 0: // Value
  7785. case 6: // Mesh reference
  7786. case 11: // Camera reference
  7787. destination[property] = sourceProperty;
  7788. break;
  7789. case 1: // Texture
  7790. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7791. break;
  7792. case 2: // Color3
  7793. case 3: // FresnelParameters
  7794. case 4: // Vector2
  7795. case 5: // Vector3
  7796. case 7: // Color Curves
  7797. case 10: // Quaternion
  7798. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. return destination;
  7804. };
  7805. function getDirectStore(target) {
  7806. var classKey = target.getClassName();
  7807. if (!__decoratorInitialStore[classKey]) {
  7808. __decoratorInitialStore[classKey] = {};
  7809. }
  7810. return __decoratorInitialStore[classKey];
  7811. }
  7812. /**
  7813. * Return the list of properties flagged as serializable
  7814. * @param target: host object
  7815. */
  7816. function getMergedStore(target) {
  7817. var classKey = target.getClassName();
  7818. if (__mergedStore[classKey]) {
  7819. return __mergedStore[classKey];
  7820. }
  7821. __mergedStore[classKey] = {};
  7822. var store = __mergedStore[classKey];
  7823. var currentTarget = target;
  7824. var currentKey = classKey;
  7825. while (currentKey) {
  7826. var initialStore = __decoratorInitialStore[currentKey];
  7827. for (var property in initialStore) {
  7828. store[property] = initialStore[property];
  7829. }
  7830. var parent_1 = void 0;
  7831. var done = false;
  7832. do {
  7833. parent_1 = Object.getPrototypeOf(currentTarget);
  7834. if (!parent_1.getClassName) {
  7835. done = true;
  7836. break;
  7837. }
  7838. if (parent_1.getClassName() !== currentKey) {
  7839. break;
  7840. }
  7841. currentTarget = parent_1;
  7842. } while (parent_1);
  7843. if (done) {
  7844. break;
  7845. }
  7846. currentKey = parent_1.getClassName();
  7847. currentTarget = parent_1;
  7848. }
  7849. return store;
  7850. }
  7851. function generateSerializableMember(type, sourceName) {
  7852. return function (target, propertyKey) {
  7853. var classStore = getDirectStore(target);
  7854. if (!classStore[propertyKey]) {
  7855. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7856. }
  7857. };
  7858. }
  7859. function generateExpandMember(setCallback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return function (target, propertyKey) {
  7862. var key = targetKey || ("_" + propertyKey);
  7863. Object.defineProperty(target, propertyKey, {
  7864. get: function () {
  7865. return this[key];
  7866. },
  7867. set: function (value) {
  7868. if (this[key] === value) {
  7869. return;
  7870. }
  7871. this[key] = value;
  7872. target[setCallback].apply(this);
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. };
  7878. }
  7879. function expandToProperty(callback, targetKey) {
  7880. if (targetKey === void 0) { targetKey = null; }
  7881. return generateExpandMember(callback, targetKey);
  7882. }
  7883. BABYLON.expandToProperty = expandToProperty;
  7884. function serialize(sourceName) {
  7885. return generateSerializableMember(0, sourceName); // value member
  7886. }
  7887. BABYLON.serialize = serialize;
  7888. function serializeAsTexture(sourceName) {
  7889. return generateSerializableMember(1, sourceName); // texture member
  7890. }
  7891. BABYLON.serializeAsTexture = serializeAsTexture;
  7892. function serializeAsColor3(sourceName) {
  7893. return generateSerializableMember(2, sourceName); // color3 member
  7894. }
  7895. BABYLON.serializeAsColor3 = serializeAsColor3;
  7896. function serializeAsFresnelParameters(sourceName) {
  7897. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7898. }
  7899. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7900. function serializeAsVector2(sourceName) {
  7901. return generateSerializableMember(4, sourceName); // vector2 member
  7902. }
  7903. BABYLON.serializeAsVector2 = serializeAsVector2;
  7904. function serializeAsVector3(sourceName) {
  7905. return generateSerializableMember(5, sourceName); // vector3 member
  7906. }
  7907. BABYLON.serializeAsVector3 = serializeAsVector3;
  7908. function serializeAsMeshReference(sourceName) {
  7909. return generateSerializableMember(6, sourceName); // mesh reference member
  7910. }
  7911. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7912. function serializeAsColorCurves(sourceName) {
  7913. return generateSerializableMember(7, sourceName); // color curves
  7914. }
  7915. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7916. function serializeAsColor4(sourceName) {
  7917. return generateSerializableMember(8, sourceName); // color 4
  7918. }
  7919. BABYLON.serializeAsColor4 = serializeAsColor4;
  7920. function serializeAsImageProcessingConfiguration(sourceName) {
  7921. return generateSerializableMember(9, sourceName); // image processing
  7922. }
  7923. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7924. function serializeAsQuaternion(sourceName) {
  7925. return generateSerializableMember(10, sourceName); // quaternion member
  7926. }
  7927. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7928. /**
  7929. * Decorator used to define property that can be serialized as reference to a camera
  7930. * @param sourceName defines the name of the property to decorate
  7931. */
  7932. function serializeAsCameraReference(sourceName) {
  7933. return generateSerializableMember(11, sourceName); // camera reference member
  7934. }
  7935. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7936. var SerializationHelper = /** @class */ (function () {
  7937. function SerializationHelper() {
  7938. }
  7939. SerializationHelper.Serialize = function (entity, serializationObject) {
  7940. if (!serializationObject) {
  7941. serializationObject = {};
  7942. }
  7943. // Tags
  7944. if (BABYLON.Tags) {
  7945. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7946. }
  7947. var serializedProperties = getMergedStore(entity);
  7948. // Properties
  7949. for (var property in serializedProperties) {
  7950. var propertyDescriptor = serializedProperties[property];
  7951. var targetPropertyName = propertyDescriptor.sourceName || property;
  7952. var propertyType = propertyDescriptor.type;
  7953. var sourceProperty = entity[property];
  7954. if (sourceProperty !== undefined && sourceProperty !== null) {
  7955. switch (propertyType) {
  7956. case 0: // Value
  7957. serializationObject[targetPropertyName] = sourceProperty;
  7958. break;
  7959. case 1: // Texture
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 2: // Color3
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 3: // FresnelParameters
  7966. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7967. break;
  7968. case 4: // Vector2
  7969. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7970. break;
  7971. case 5: // Vector3
  7972. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7973. break;
  7974. case 6: // Mesh reference
  7975. serializationObject[targetPropertyName] = sourceProperty.id;
  7976. break;
  7977. case 7: // Color Curves
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 8: // Color 4
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 9: // Image Processing
  7984. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7985. break;
  7986. case 10: // Quaternion
  7987. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7988. break;
  7989. case 11: // Camera reference
  7990. serializationObject[targetPropertyName] = sourceProperty.id;
  7991. break;
  7992. }
  7993. }
  7994. }
  7995. return serializationObject;
  7996. };
  7997. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7998. if (rootUrl === void 0) { rootUrl = null; }
  7999. var destination = creationFunction();
  8000. if (!rootUrl) {
  8001. rootUrl = "";
  8002. }
  8003. // Tags
  8004. if (BABYLON.Tags) {
  8005. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8006. }
  8007. var classStore = getMergedStore(destination);
  8008. // Properties
  8009. for (var property in classStore) {
  8010. var propertyDescriptor = classStore[property];
  8011. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8012. var propertyType = propertyDescriptor.type;
  8013. if (sourceProperty !== undefined && sourceProperty !== null) {
  8014. var dest = destination;
  8015. switch (propertyType) {
  8016. case 0: // Value
  8017. dest[property] = sourceProperty;
  8018. break;
  8019. case 1: // Texture
  8020. if (scene) {
  8021. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8022. }
  8023. break;
  8024. case 2: // Color3
  8025. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8026. break;
  8027. case 3: // FresnelParameters
  8028. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8029. break;
  8030. case 4: // Vector2
  8031. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8032. break;
  8033. case 5: // Vector3
  8034. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8035. break;
  8036. case 6: // Mesh reference
  8037. if (scene) {
  8038. dest[property] = scene.getLastMeshByID(sourceProperty);
  8039. }
  8040. break;
  8041. case 7: // Color Curves
  8042. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8043. break;
  8044. case 8: // Color 4
  8045. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8046. break;
  8047. case 9: // Image Processing
  8048. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8049. break;
  8050. case 10: // Quaternion
  8051. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8052. break;
  8053. case 11: // Camera reference
  8054. if (scene) {
  8055. dest[property] = scene.getCameraByID(sourceProperty);
  8056. }
  8057. break;
  8058. }
  8059. }
  8060. }
  8061. return destination;
  8062. };
  8063. SerializationHelper.Clone = function (creationFunction, source) {
  8064. return _copySource(creationFunction, source, false);
  8065. };
  8066. SerializationHelper.Instanciate = function (creationFunction, source) {
  8067. return _copySource(creationFunction, source, true);
  8068. };
  8069. return SerializationHelper;
  8070. }());
  8071. BABYLON.SerializationHelper = SerializationHelper;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.decorators.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * Wrapper class for promise with external resolve and reject.
  8078. */
  8079. var Deferred = /** @class */ (function () {
  8080. /**
  8081. * Constructor for this deferred object.
  8082. */
  8083. function Deferred() {
  8084. var _this = this;
  8085. this.promise = new Promise(function (resolve, reject) {
  8086. _this._resolve = resolve;
  8087. _this._reject = reject;
  8088. });
  8089. }
  8090. Object.defineProperty(Deferred.prototype, "resolve", {
  8091. /**
  8092. * The resolve method of the promise associated with this deferred object.
  8093. */
  8094. get: function () {
  8095. return this._resolve;
  8096. },
  8097. enumerable: true,
  8098. configurable: true
  8099. });
  8100. Object.defineProperty(Deferred.prototype, "reject", {
  8101. /**
  8102. * The reject method of the promise associated with this deferred object.
  8103. */
  8104. get: function () {
  8105. return this._reject;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. return Deferred;
  8111. }());
  8112. BABYLON.Deferred = Deferred;
  8113. })(BABYLON || (BABYLON = {}));
  8114. //# sourceMappingURL=babylon.deferred.js.map
  8115. var BABYLON;
  8116. (function (BABYLON) {
  8117. /**
  8118. * A class serves as a medium between the observable and its observers
  8119. */
  8120. var EventState = /** @class */ (function () {
  8121. /**
  8122. * Create a new EventState
  8123. * @param mask defines the mask associated with this state
  8124. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8125. * @param target defines the original target of the state
  8126. * @param currentTarget defines the current target of the state
  8127. */
  8128. function EventState(mask, skipNextObservers, target, currentTarget) {
  8129. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8130. this.initalize(mask, skipNextObservers, target, currentTarget);
  8131. }
  8132. /**
  8133. * Initialize the current event state
  8134. * @param mask defines the mask associated with this state
  8135. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8136. * @param target defines the original target of the state
  8137. * @param currentTarget defines the current target of the state
  8138. * @returns the current event state
  8139. */
  8140. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8141. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8142. this.mask = mask;
  8143. this.skipNextObservers = skipNextObservers;
  8144. this.target = target;
  8145. this.currentTarget = currentTarget;
  8146. return this;
  8147. };
  8148. return EventState;
  8149. }());
  8150. BABYLON.EventState = EventState;
  8151. /**
  8152. * Represent an Observer registered to a given Observable object.
  8153. */
  8154. var Observer = /** @class */ (function () {
  8155. /**
  8156. * Creates a new observer
  8157. * @param callback defines the callback to call when the observer is notified
  8158. * @param mask defines the mask of the observer (used to filter notifications)
  8159. * @param scope defines the current scope used to restore the JS context
  8160. */
  8161. function Observer(
  8162. /**
  8163. * Defines the callback to call when the observer is notified
  8164. */
  8165. callback,
  8166. /**
  8167. * Defines the mask of the observer (used to filter notifications)
  8168. */
  8169. mask,
  8170. /**
  8171. * Defines the current scope used to restore the JS context
  8172. */
  8173. scope) {
  8174. if (scope === void 0) { scope = null; }
  8175. this.callback = callback;
  8176. this.mask = mask;
  8177. this.scope = scope;
  8178. /** @hidden */
  8179. this._willBeUnregistered = false;
  8180. /**
  8181. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8182. */
  8183. this.unregisterOnNextCall = false;
  8184. }
  8185. return Observer;
  8186. }());
  8187. BABYLON.Observer = Observer;
  8188. /**
  8189. * Represent a list of observers registered to multiple Observables object.
  8190. */
  8191. var MultiObserver = /** @class */ (function () {
  8192. function MultiObserver() {
  8193. }
  8194. /**
  8195. * Release associated resources
  8196. */
  8197. MultiObserver.prototype.dispose = function () {
  8198. if (this._observers && this._observables) {
  8199. for (var index = 0; index < this._observers.length; index++) {
  8200. this._observables[index].remove(this._observers[index]);
  8201. }
  8202. }
  8203. this._observers = null;
  8204. this._observables = null;
  8205. };
  8206. /**
  8207. * Raise a callback when one of the observable will notify
  8208. * @param observables defines a list of observables to watch
  8209. * @param callback defines the callback to call on notification
  8210. * @param mask defines the mask used to filter notifications
  8211. * @param scope defines the current scope used to restore the JS context
  8212. * @returns the new MultiObserver
  8213. */
  8214. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8215. if (mask === void 0) { mask = -1; }
  8216. if (scope === void 0) { scope = null; }
  8217. var result = new MultiObserver();
  8218. result._observers = new Array();
  8219. result._observables = observables;
  8220. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8221. var observable = observables_1[_i];
  8222. var observer = observable.add(callback, mask, false, scope);
  8223. if (observer) {
  8224. result._observers.push(observer);
  8225. }
  8226. }
  8227. return result;
  8228. };
  8229. return MultiObserver;
  8230. }());
  8231. BABYLON.MultiObserver = MultiObserver;
  8232. /**
  8233. * The Observable class is a simple implementation of the Observable pattern.
  8234. *
  8235. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8236. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8237. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8238. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8239. */
  8240. var Observable = /** @class */ (function () {
  8241. /**
  8242. * Creates a new observable
  8243. * @param onObserverAdded defines a callback to call when a new observer is added
  8244. */
  8245. function Observable(onObserverAdded) {
  8246. this._observers = new Array();
  8247. this._eventState = new EventState(0);
  8248. if (onObserverAdded) {
  8249. this._onObserverAdded = onObserverAdded;
  8250. }
  8251. }
  8252. /**
  8253. * Create a new Observer with the specified callback
  8254. * @param callback the callback that will be executed for that Observer
  8255. * @param mask the mask used to filter observers
  8256. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8257. * @param scope optional scope for the callback to be called from
  8258. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8259. * @returns the new observer created for the callback
  8260. */
  8261. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8262. if (mask === void 0) { mask = -1; }
  8263. if (insertFirst === void 0) { insertFirst = false; }
  8264. if (scope === void 0) { scope = null; }
  8265. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8266. if (!callback) {
  8267. return null;
  8268. }
  8269. var observer = new Observer(callback, mask, scope);
  8270. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8271. if (insertFirst) {
  8272. this._observers.unshift(observer);
  8273. }
  8274. else {
  8275. this._observers.push(observer);
  8276. }
  8277. if (this._onObserverAdded) {
  8278. this._onObserverAdded(observer);
  8279. }
  8280. return observer;
  8281. };
  8282. /**
  8283. * Create a new Observer with the specified callback and unregisters after the next notification
  8284. * @param callback the callback that will be executed for that Observer
  8285. * @returns the new observer created for the callback
  8286. */
  8287. Observable.prototype.addOnce = function (callback) {
  8288. return this.add(callback, undefined, undefined, undefined, true);
  8289. };
  8290. /**
  8291. * Remove an Observer from the Observable object
  8292. * @param observer the instance of the Observer to remove
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.remove = function (observer) {
  8296. if (!observer) {
  8297. return false;
  8298. }
  8299. var index = this._observers.indexOf(observer);
  8300. if (index !== -1) {
  8301. this._observers.splice(index, 1);
  8302. return true;
  8303. }
  8304. return false;
  8305. };
  8306. /**
  8307. * Remove a callback from the Observable object
  8308. * @param callback the callback to remove
  8309. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8310. * @returns false if it doesn't belong to this Observable
  8311. */
  8312. Observable.prototype.removeCallback = function (callback, scope) {
  8313. for (var index = 0; index < this._observers.length; index++) {
  8314. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8315. this._observers.splice(index, 1);
  8316. return true;
  8317. }
  8318. }
  8319. return false;
  8320. };
  8321. Observable.prototype._deferUnregister = function (observer) {
  8322. var _this = this;
  8323. observer.unregisterOnNextCall = false;
  8324. observer._willBeUnregistered = true;
  8325. BABYLON.Tools.SetImmediate(function () {
  8326. _this.remove(observer);
  8327. });
  8328. };
  8329. /**
  8330. * Notify all Observers by calling their respective callback with the given data
  8331. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8332. * @param eventData defines the data to send to all observers
  8333. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8334. * @param target defines the original target of the state
  8335. * @param currentTarget defines the current target of the state
  8336. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8337. */
  8338. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8339. if (mask === void 0) { mask = -1; }
  8340. if (!this._observers.length) {
  8341. return true;
  8342. }
  8343. var state = this._eventState;
  8344. state.mask = mask;
  8345. state.target = target;
  8346. state.currentTarget = currentTarget;
  8347. state.skipNextObservers = false;
  8348. state.lastReturnValue = eventData;
  8349. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8350. var obs = _a[_i];
  8351. if (obs._willBeUnregistered) {
  8352. continue;
  8353. }
  8354. if (obs.mask & mask) {
  8355. if (obs.scope) {
  8356. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8357. }
  8358. else {
  8359. state.lastReturnValue = obs.callback(eventData, state);
  8360. }
  8361. if (obs.unregisterOnNextCall) {
  8362. this._deferUnregister(obs);
  8363. }
  8364. }
  8365. if (state.skipNextObservers) {
  8366. return false;
  8367. }
  8368. }
  8369. return true;
  8370. };
  8371. /**
  8372. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8373. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8374. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8375. * and it is crucial that all callbacks will be executed.
  8376. * The order of the callbacks is kept, callbacks are not executed parallel.
  8377. *
  8378. * @param eventData The data to be sent to each callback
  8379. * @param mask is used to filter observers defaults to -1
  8380. * @param target defines the callback target (see EventState)
  8381. * @param currentTarget defines he current object in the bubbling phase
  8382. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8383. */
  8384. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8385. var _this = this;
  8386. if (mask === void 0) { mask = -1; }
  8387. // create an empty promise
  8388. var p = Promise.resolve(eventData);
  8389. // no observers? return this promise.
  8390. if (!this._observers.length) {
  8391. return p;
  8392. }
  8393. var state = this._eventState;
  8394. state.mask = mask;
  8395. state.target = target;
  8396. state.currentTarget = currentTarget;
  8397. state.skipNextObservers = false;
  8398. // execute one callback after another (not using Promise.all, the order is important)
  8399. this._observers.forEach(function (obs) {
  8400. if (state.skipNextObservers) {
  8401. return;
  8402. }
  8403. if (obs._willBeUnregistered) {
  8404. return;
  8405. }
  8406. if (obs.mask & mask) {
  8407. if (obs.scope) {
  8408. p = p.then(function (lastReturnedValue) {
  8409. state.lastReturnValue = lastReturnedValue;
  8410. return obs.callback.apply(obs.scope, [eventData, state]);
  8411. });
  8412. }
  8413. else {
  8414. p = p.then(function (lastReturnedValue) {
  8415. state.lastReturnValue = lastReturnedValue;
  8416. return obs.callback(eventData, state);
  8417. });
  8418. }
  8419. if (obs.unregisterOnNextCall) {
  8420. _this._deferUnregister(obs);
  8421. }
  8422. }
  8423. });
  8424. // return the eventData
  8425. return p.then(function () { return eventData; });
  8426. };
  8427. /**
  8428. * Notify a specific observer
  8429. * @param observer defines the observer to notify
  8430. * @param eventData defines the data to be sent to each callback
  8431. * @param mask is used to filter observers defaults to -1
  8432. */
  8433. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8434. if (mask === void 0) { mask = -1; }
  8435. var state = this._eventState;
  8436. state.mask = mask;
  8437. state.skipNextObservers = false;
  8438. observer.callback(eventData, state);
  8439. };
  8440. /**
  8441. * Gets a boolean indicating if the observable has at least one observer
  8442. * @returns true is the Observable has at least one Observer registered
  8443. */
  8444. Observable.prototype.hasObservers = function () {
  8445. return this._observers.length > 0;
  8446. };
  8447. /**
  8448. * Clear the list of observers
  8449. */
  8450. Observable.prototype.clear = function () {
  8451. this._observers = new Array();
  8452. this._onObserverAdded = null;
  8453. };
  8454. /**
  8455. * Clone the current observable
  8456. * @returns a new observable
  8457. */
  8458. Observable.prototype.clone = function () {
  8459. var result = new Observable();
  8460. result._observers = this._observers.slice(0);
  8461. return result;
  8462. };
  8463. /**
  8464. * Does this observable handles observer registered with a given mask
  8465. * @param mask defines the mask to be tested
  8466. * @return whether or not one observer registered with the given mask is handeled
  8467. **/
  8468. Observable.prototype.hasSpecificMask = function (mask) {
  8469. if (mask === void 0) { mask = -1; }
  8470. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8471. var obs = _a[_i];
  8472. if (obs.mask & mask || obs.mask === mask) {
  8473. return true;
  8474. }
  8475. }
  8476. return false;
  8477. };
  8478. return Observable;
  8479. }());
  8480. BABYLON.Observable = Observable;
  8481. })(BABYLON || (BABYLON = {}));
  8482. //# sourceMappingURL=babylon.observable.js.map
  8483. var BABYLON;
  8484. (function (BABYLON) {
  8485. var SmartArray = /** @class */ (function () {
  8486. function SmartArray(capacity) {
  8487. this.length = 0;
  8488. this.data = new Array(capacity);
  8489. this._id = SmartArray._GlobalId++;
  8490. }
  8491. SmartArray.prototype.push = function (value) {
  8492. this.data[this.length++] = value;
  8493. if (this.length > this.data.length) {
  8494. this.data.length *= 2;
  8495. }
  8496. };
  8497. SmartArray.prototype.forEach = function (func) {
  8498. for (var index = 0; index < this.length; index++) {
  8499. func(this.data[index]);
  8500. }
  8501. };
  8502. SmartArray.prototype.sort = function (compareFn) {
  8503. this.data.sort(compareFn);
  8504. };
  8505. SmartArray.prototype.reset = function () {
  8506. this.length = 0;
  8507. };
  8508. SmartArray.prototype.dispose = function () {
  8509. this.reset();
  8510. if (this.data) {
  8511. this.data.length = 0;
  8512. this.data = [];
  8513. }
  8514. };
  8515. SmartArray.prototype.concat = function (array) {
  8516. if (array.length === 0) {
  8517. return;
  8518. }
  8519. if (this.length + array.length > this.data.length) {
  8520. this.data.length = (this.length + array.length) * 2;
  8521. }
  8522. for (var index = 0; index < array.length; index++) {
  8523. this.data[this.length++] = (array.data || array)[index];
  8524. }
  8525. };
  8526. SmartArray.prototype.indexOf = function (value) {
  8527. var position = this.data.indexOf(value);
  8528. if (position >= this.length) {
  8529. return -1;
  8530. }
  8531. return position;
  8532. };
  8533. SmartArray.prototype.contains = function (value) {
  8534. return this.data.indexOf(value) !== -1;
  8535. };
  8536. // Statics
  8537. SmartArray._GlobalId = 0;
  8538. return SmartArray;
  8539. }());
  8540. BABYLON.SmartArray = SmartArray;
  8541. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8542. __extends(SmartArrayNoDuplicate, _super);
  8543. function SmartArrayNoDuplicate() {
  8544. var _this = _super !== null && _super.apply(this, arguments) || this;
  8545. _this._duplicateId = 0;
  8546. return _this;
  8547. }
  8548. SmartArrayNoDuplicate.prototype.push = function (value) {
  8549. _super.prototype.push.call(this, value);
  8550. if (!value.__smartArrayFlags) {
  8551. value.__smartArrayFlags = {};
  8552. }
  8553. value.__smartArrayFlags[this._id] = this._duplicateId;
  8554. };
  8555. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8556. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8557. return false;
  8558. }
  8559. this.push(value);
  8560. return true;
  8561. };
  8562. SmartArrayNoDuplicate.prototype.reset = function () {
  8563. _super.prototype.reset.call(this);
  8564. this._duplicateId++;
  8565. };
  8566. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8567. if (array.length === 0) {
  8568. return;
  8569. }
  8570. if (this.length + array.length > this.data.length) {
  8571. this.data.length = (this.length + array.length) * 2;
  8572. }
  8573. for (var index = 0; index < array.length; index++) {
  8574. var item = (array.data || array)[index];
  8575. this.pushNoDuplicate(item);
  8576. }
  8577. };
  8578. return SmartArrayNoDuplicate;
  8579. }(SmartArray));
  8580. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8581. })(BABYLON || (BABYLON = {}));
  8582. //# sourceMappingURL=babylon.smartArray.js.map
  8583. var BABYLON;
  8584. (function (BABYLON) {
  8585. /** Class used to store color gradient */
  8586. var ColorGradient = /** @class */ (function () {
  8587. function ColorGradient() {
  8588. }
  8589. /**
  8590. * Will get a color picked randomly between color1 and color2.
  8591. * If color2 is undefined then color1 will be used
  8592. * @param result defines the target Color4 to store the result in
  8593. */
  8594. ColorGradient.prototype.getColorToRef = function (result) {
  8595. if (!this.color2) {
  8596. result.copyFrom(this.color1);
  8597. return;
  8598. }
  8599. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8600. };
  8601. return ColorGradient;
  8602. }());
  8603. BABYLON.ColorGradient = ColorGradient;
  8604. /** Class used to store factor gradient */
  8605. var FactorGradient = /** @class */ (function () {
  8606. function FactorGradient() {
  8607. }
  8608. return FactorGradient;
  8609. }());
  8610. BABYLON.FactorGradient = FactorGradient;
  8611. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8612. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8613. var LoadFileError = /** @class */ (function (_super) {
  8614. __extends(LoadFileError, _super);
  8615. function LoadFileError(message, request) {
  8616. var _this = _super.call(this, message) || this;
  8617. _this.request = request;
  8618. _this.name = "LoadFileError";
  8619. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8620. return _this;
  8621. }
  8622. // Polyfill for Object.setPrototypeOf if necessary.
  8623. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8624. return LoadFileError;
  8625. }(Error));
  8626. BABYLON.LoadFileError = LoadFileError;
  8627. var RetryStrategy = /** @class */ (function () {
  8628. function RetryStrategy() {
  8629. }
  8630. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8631. if (maxRetries === void 0) { maxRetries = 3; }
  8632. if (baseInterval === void 0) { baseInterval = 500; }
  8633. return function (url, request, retryIndex) {
  8634. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8635. return -1;
  8636. }
  8637. return Math.pow(2, retryIndex) * baseInterval;
  8638. };
  8639. };
  8640. return RetryStrategy;
  8641. }());
  8642. BABYLON.RetryStrategy = RetryStrategy;
  8643. // Screenshots
  8644. var screenshotCanvas;
  8645. var cloneValue = function (source, destinationObject) {
  8646. if (!source)
  8647. return null;
  8648. if (source instanceof BABYLON.Mesh) {
  8649. return null;
  8650. }
  8651. if (source instanceof BABYLON.SubMesh) {
  8652. return source.clone(destinationObject);
  8653. }
  8654. else if (source.clone) {
  8655. return source.clone();
  8656. }
  8657. return null;
  8658. };
  8659. var Tools = /** @class */ (function () {
  8660. function Tools() {
  8661. }
  8662. /**
  8663. * Interpolates between a and b via alpha
  8664. * @param a The lower value (returned when alpha = 0)
  8665. * @param b The upper value (returned when alpha = 1)
  8666. * @param alpha The interpolation-factor
  8667. * @return The mixed value
  8668. */
  8669. Tools.Mix = function (a, b, alpha) {
  8670. return a * (1 - alpha) + b * alpha;
  8671. };
  8672. Tools.Instantiate = function (className) {
  8673. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8674. return Tools.RegisteredExternalClasses[className];
  8675. }
  8676. var arr = className.split(".");
  8677. var fn = (window || this);
  8678. for (var i = 0, len = arr.length; i < len; i++) {
  8679. fn = fn[arr[i]];
  8680. }
  8681. if (typeof fn !== "function") {
  8682. return null;
  8683. }
  8684. return fn;
  8685. };
  8686. /**
  8687. * Provides a slice function that will work even on IE
  8688. * @param data defines the array to slice
  8689. * @param start defines the start of the data (optional)
  8690. * @param end defines the end of the data (optional)
  8691. * @returns the new sliced array
  8692. */
  8693. Tools.Slice = function (data, start, end) {
  8694. if (data.slice) {
  8695. return data.slice(start, end);
  8696. }
  8697. return Array.prototype.slice.call(data, start, end);
  8698. };
  8699. Tools.SetImmediate = function (action) {
  8700. if (window.setImmediate) {
  8701. window.setImmediate(action);
  8702. }
  8703. else {
  8704. setTimeout(action, 1);
  8705. }
  8706. };
  8707. Tools.IsExponentOfTwo = function (value) {
  8708. var count = 1;
  8709. do {
  8710. count *= 2;
  8711. } while (count < value);
  8712. return count === value;
  8713. };
  8714. /**
  8715. * Returns the nearest 32-bit single precision float representation of a Number
  8716. * @param value A Number. If the parameter is of a different type, it will get converted
  8717. * to a number or to NaN if it cannot be converted
  8718. * @returns number
  8719. */
  8720. Tools.FloatRound = function (value) {
  8721. if (Math.fround) {
  8722. return Math.fround(value);
  8723. }
  8724. return (Tools._tmpFloatArray[0] = value);
  8725. };
  8726. /**
  8727. * Find the next highest power of two.
  8728. * @param x Number to start search from.
  8729. * @return Next highest power of two.
  8730. */
  8731. Tools.CeilingPOT = function (x) {
  8732. x--;
  8733. x |= x >> 1;
  8734. x |= x >> 2;
  8735. x |= x >> 4;
  8736. x |= x >> 8;
  8737. x |= x >> 16;
  8738. x++;
  8739. return x;
  8740. };
  8741. /**
  8742. * Find the next lowest power of two.
  8743. * @param x Number to start search from.
  8744. * @return Next lowest power of two.
  8745. */
  8746. Tools.FloorPOT = function (x) {
  8747. x = x | (x >> 1);
  8748. x = x | (x >> 2);
  8749. x = x | (x >> 4);
  8750. x = x | (x >> 8);
  8751. x = x | (x >> 16);
  8752. return x - (x >> 1);
  8753. };
  8754. /**
  8755. * Find the nearest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next nearest power of two.
  8758. */
  8759. Tools.NearestPOT = function (x) {
  8760. var c = Tools.CeilingPOT(x);
  8761. var f = Tools.FloorPOT(x);
  8762. return (c - x) > (x - f) ? f : c;
  8763. };
  8764. Tools.GetExponentOfTwo = function (value, max, mode) {
  8765. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8766. var pot;
  8767. switch (mode) {
  8768. case BABYLON.Engine.SCALEMODE_FLOOR:
  8769. pot = Tools.FloorPOT(value);
  8770. break;
  8771. case BABYLON.Engine.SCALEMODE_NEAREST:
  8772. pot = Tools.NearestPOT(value);
  8773. break;
  8774. case BABYLON.Engine.SCALEMODE_CEILING:
  8775. default:
  8776. pot = Tools.CeilingPOT(value);
  8777. break;
  8778. }
  8779. return Math.min(pot, max);
  8780. };
  8781. Tools.GetFilename = function (path) {
  8782. var index = path.lastIndexOf("/");
  8783. if (index < 0)
  8784. return path;
  8785. return path.substring(index + 1);
  8786. };
  8787. /**
  8788. * Extracts the "folder" part of a path (everything before the filename).
  8789. * @param uri The URI to extract the info from
  8790. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8791. * @returns The "folder" part of the path
  8792. */
  8793. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8794. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8795. var index = uri.lastIndexOf("/");
  8796. if (index < 0) {
  8797. if (returnUnchangedIfNoSlash) {
  8798. return uri;
  8799. }
  8800. return "";
  8801. }
  8802. return uri.substring(0, index + 1);
  8803. };
  8804. Tools.GetDOMTextContent = function (element) {
  8805. var result = "";
  8806. var child = element.firstChild;
  8807. while (child) {
  8808. if (child.nodeType === 3) {
  8809. result += child.textContent;
  8810. }
  8811. child = child.nextSibling;
  8812. }
  8813. return result;
  8814. };
  8815. Tools.ToDegrees = function (angle) {
  8816. return angle * 180 / Math.PI;
  8817. };
  8818. Tools.ToRadians = function (angle) {
  8819. return angle * Math.PI / 180;
  8820. };
  8821. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8822. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8823. var output = "";
  8824. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8825. var i = 0;
  8826. var bytes = new Uint8Array(buffer);
  8827. while (i < bytes.length) {
  8828. chr1 = bytes[i++];
  8829. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8830. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8831. enc1 = chr1 >> 2;
  8832. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8833. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8834. enc4 = chr3 & 63;
  8835. if (isNaN(chr2)) {
  8836. enc3 = enc4 = 64;
  8837. }
  8838. else if (isNaN(chr3)) {
  8839. enc4 = 64;
  8840. }
  8841. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8842. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8843. }
  8844. return "data:image/png;base64," + output;
  8845. };
  8846. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8847. if (bias === void 0) { bias = null; }
  8848. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8849. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8850. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8851. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8852. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8853. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8854. }
  8855. if (bias) {
  8856. minimum.x -= minimum.x * bias.x + bias.y;
  8857. minimum.y -= minimum.y * bias.x + bias.y;
  8858. minimum.z -= minimum.z * bias.x + bias.y;
  8859. maximum.x += maximum.x * bias.x + bias.y;
  8860. maximum.y += maximum.y * bias.x + bias.y;
  8861. maximum.z += maximum.z * bias.x + bias.y;
  8862. }
  8863. return {
  8864. minimum: minimum,
  8865. maximum: maximum
  8866. };
  8867. };
  8868. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8869. if (bias === void 0) { bias = null; }
  8870. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8871. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8872. if (!stride) {
  8873. stride = 3;
  8874. }
  8875. for (var index = start; index < start + count; index++) {
  8876. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. minimum.z -= minimum.z * bias.x + bias.y;
  8884. maximum.x += maximum.x * bias.x + bias.y;
  8885. maximum.y += maximum.y * bias.x + bias.y;
  8886. maximum.z += maximum.z * bias.x + bias.y;
  8887. }
  8888. return {
  8889. minimum: minimum,
  8890. maximum: maximum
  8891. };
  8892. };
  8893. Tools.Vector2ArrayFeeder = function (array) {
  8894. return function (index) {
  8895. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8896. var length = isFloatArray ? array.length / 2 : array.length;
  8897. if (index >= length) {
  8898. return null;
  8899. }
  8900. if (isFloatArray) {
  8901. var fa = array;
  8902. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8903. }
  8904. var a = array;
  8905. return a[index];
  8906. };
  8907. };
  8908. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8909. if (bias === void 0) { bias = null; }
  8910. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8911. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8912. var i = 0;
  8913. var cur = feeder(i++);
  8914. while (cur) {
  8915. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8916. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8917. cur = feeder(i++);
  8918. }
  8919. if (bias) {
  8920. minimum.x -= minimum.x * bias.x + bias.y;
  8921. minimum.y -= minimum.y * bias.x + bias.y;
  8922. maximum.x += maximum.x * bias.x + bias.y;
  8923. maximum.y += maximum.y * bias.x + bias.y;
  8924. }
  8925. return {
  8926. minimum: minimum,
  8927. maximum: maximum
  8928. };
  8929. };
  8930. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8931. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8932. return null;
  8933. return Array.isArray(obj) ? obj : [obj];
  8934. };
  8935. // Misc.
  8936. Tools.GetPointerPrefix = function () {
  8937. var eventPrefix = "pointer";
  8938. // Check if pointer events are supported
  8939. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8940. eventPrefix = "mouse";
  8941. }
  8942. return eventPrefix;
  8943. };
  8944. /**
  8945. * @param func - the function to be called
  8946. * @param requester - the object that will request the next frame. Falls back to window.
  8947. */
  8948. Tools.QueueNewFrame = function (func, requester) {
  8949. if (!Tools.IsWindowObjectExist()) {
  8950. return setTimeout(func, 16);
  8951. }
  8952. if (!requester) {
  8953. requester = window;
  8954. }
  8955. if (requester.requestAnimationFrame) {
  8956. return requester.requestAnimationFrame(func);
  8957. }
  8958. else if (requester.msRequestAnimationFrame) {
  8959. return requester.msRequestAnimationFrame(func);
  8960. }
  8961. else if (requester.webkitRequestAnimationFrame) {
  8962. return requester.webkitRequestAnimationFrame(func);
  8963. }
  8964. else if (requester.mozRequestAnimationFrame) {
  8965. return requester.mozRequestAnimationFrame(func);
  8966. }
  8967. else if (requester.oRequestAnimationFrame) {
  8968. return requester.oRequestAnimationFrame(func);
  8969. }
  8970. else {
  8971. return window.setTimeout(func, 16);
  8972. }
  8973. };
  8974. Tools.RequestFullscreen = function (element) {
  8975. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8976. if (!requestFunction)
  8977. return;
  8978. requestFunction.call(element);
  8979. };
  8980. Tools.ExitFullscreen = function () {
  8981. if (document.exitFullscreen) {
  8982. document.exitFullscreen();
  8983. }
  8984. else if (document.mozCancelFullScreen) {
  8985. document.mozCancelFullScreen();
  8986. }
  8987. else if (document.webkitCancelFullScreen) {
  8988. document.webkitCancelFullScreen();
  8989. }
  8990. else if (document.msCancelFullScreen) {
  8991. document.msCancelFullScreen();
  8992. }
  8993. };
  8994. Tools.SetCorsBehavior = function (url, element) {
  8995. if (url && url.indexOf("data:") === 0) {
  8996. return;
  8997. }
  8998. if (Tools.CorsBehavior) {
  8999. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9000. element.crossOrigin = Tools.CorsBehavior;
  9001. }
  9002. else {
  9003. var result = Tools.CorsBehavior(url);
  9004. if (result) {
  9005. element.crossOrigin = result;
  9006. }
  9007. }
  9008. }
  9009. };
  9010. // External files
  9011. Tools.CleanUrl = function (url) {
  9012. url = url.replace(/#/mg, "%23");
  9013. return url;
  9014. };
  9015. /**
  9016. * Loads an image as an HTMLImageElement.
  9017. * @param input url string, ArrayBuffer, or Blob to load
  9018. * @param onLoad callback called when the image successfully loads
  9019. * @param onError callback called when the image fails to load
  9020. * @param database database for caching
  9021. * @returns the HTMLImageElement of the loaded image
  9022. */
  9023. Tools.LoadImage = function (input, onLoad, onError, database) {
  9024. var url;
  9025. var usingObjectURL = false;
  9026. if (input instanceof ArrayBuffer) {
  9027. url = URL.createObjectURL(new Blob([input]));
  9028. usingObjectURL = true;
  9029. }
  9030. else if (input instanceof Blob) {
  9031. url = URL.createObjectURL(input);
  9032. usingObjectURL = true;
  9033. }
  9034. else {
  9035. url = Tools.CleanUrl(input);
  9036. url = Tools.PreprocessUrl(input);
  9037. }
  9038. var img = new Image();
  9039. Tools.SetCorsBehavior(url, img);
  9040. var loadHandler = function () {
  9041. if (usingObjectURL && img.src) {
  9042. URL.revokeObjectURL(img.src);
  9043. }
  9044. img.removeEventListener("load", loadHandler);
  9045. img.removeEventListener("error", errorHandler);
  9046. onLoad(img);
  9047. };
  9048. var errorHandler = function (err) {
  9049. if (usingObjectURL && img.src) {
  9050. URL.revokeObjectURL(img.src);
  9051. }
  9052. img.removeEventListener("load", loadHandler);
  9053. img.removeEventListener("error", errorHandler);
  9054. Tools.Error("Error while trying to load image: " + input);
  9055. if (onError) {
  9056. onError("Error while trying to load image: " + input, err);
  9057. }
  9058. };
  9059. img.addEventListener("load", loadHandler);
  9060. img.addEventListener("error", errorHandler);
  9061. var noIndexedDB = function () {
  9062. img.src = url;
  9063. };
  9064. var loadFromIndexedDB = function () {
  9065. if (database) {
  9066. database.loadImageFromDB(url, img);
  9067. }
  9068. };
  9069. //ANY database to do!
  9070. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9071. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9072. }
  9073. else {
  9074. if (url.indexOf("file:") !== -1) {
  9075. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9076. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9077. try {
  9078. var blobURL;
  9079. try {
  9080. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9081. }
  9082. catch (ex) {
  9083. // Chrome doesn't support oneTimeOnly parameter
  9084. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9085. }
  9086. img.src = blobURL;
  9087. usingObjectURL = true;
  9088. }
  9089. catch (e) {
  9090. img.src = "";
  9091. }
  9092. return img;
  9093. }
  9094. }
  9095. noIndexedDB();
  9096. }
  9097. return img;
  9098. };
  9099. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9100. url = Tools.CleanUrl(url);
  9101. url = Tools.PreprocessUrl(url);
  9102. // If file and file input are set
  9103. if (url.indexOf("file:") !== -1) {
  9104. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9105. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9106. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9107. }
  9108. }
  9109. var loadUrl = Tools.BaseUrl + url;
  9110. var aborted = false;
  9111. var fileRequest = {
  9112. onCompleteObservable: new BABYLON.Observable(),
  9113. abort: function () { return aborted = true; },
  9114. };
  9115. var requestFile = function () {
  9116. var request = new XMLHttpRequest();
  9117. var retryHandle = null;
  9118. fileRequest.abort = function () {
  9119. aborted = true;
  9120. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9121. request.abort();
  9122. }
  9123. if (retryHandle !== null) {
  9124. clearTimeout(retryHandle);
  9125. retryHandle = null;
  9126. }
  9127. };
  9128. var retryLoop = function (retryIndex) {
  9129. request.open('GET', loadUrl, true);
  9130. if (useArrayBuffer) {
  9131. request.responseType = "arraybuffer";
  9132. }
  9133. if (onProgress) {
  9134. request.addEventListener("progress", onProgress);
  9135. }
  9136. var onLoadEnd = function () {
  9137. request.removeEventListener("loadend", onLoadEnd);
  9138. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9139. fileRequest.onCompleteObservable.clear();
  9140. };
  9141. request.addEventListener("loadend", onLoadEnd);
  9142. var onReadyStateChange = function () {
  9143. if (aborted) {
  9144. return;
  9145. }
  9146. // In case of undefined state in some browsers.
  9147. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9148. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9149. request.removeEventListener("readystatechange", onReadyStateChange);
  9150. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9151. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9152. return;
  9153. }
  9154. var retryStrategy = Tools.DefaultRetryStrategy;
  9155. if (retryStrategy) {
  9156. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9157. if (waitTime !== -1) {
  9158. // Prevent the request from completing for retry.
  9159. request.removeEventListener("loadend", onLoadEnd);
  9160. request = new XMLHttpRequest();
  9161. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9162. return;
  9163. }
  9164. }
  9165. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9166. if (onError) {
  9167. onError(request, e);
  9168. }
  9169. else {
  9170. throw e;
  9171. }
  9172. }
  9173. };
  9174. request.addEventListener("readystatechange", onReadyStateChange);
  9175. request.send();
  9176. };
  9177. retryLoop(0);
  9178. };
  9179. // Caching all files
  9180. if (database && database.enableSceneOffline) {
  9181. var noIndexedDB_1 = function () {
  9182. if (!aborted) {
  9183. requestFile();
  9184. }
  9185. };
  9186. var loadFromIndexedDB = function () {
  9187. // TODO: database needs to support aborting and should return a IFileRequest
  9188. if (aborted) {
  9189. return;
  9190. }
  9191. if (database) {
  9192. database.loadFileFromDB(url, function (data) {
  9193. if (!aborted) {
  9194. onSuccess(data);
  9195. }
  9196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9197. }, onProgress ? function (event) {
  9198. if (!aborted) {
  9199. onProgress(event);
  9200. }
  9201. } : undefined, noIndexedDB_1, useArrayBuffer);
  9202. }
  9203. };
  9204. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9205. }
  9206. else {
  9207. requestFile();
  9208. }
  9209. return fileRequest;
  9210. };
  9211. /**
  9212. * Load a script (identified by an url). When the url returns, the
  9213. * content of this file is added into a new script element, attached to the DOM (body element)
  9214. */
  9215. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9216. var head = document.getElementsByTagName('head')[0];
  9217. var script = document.createElement('script');
  9218. script.type = 'text/javascript';
  9219. script.src = scriptUrl;
  9220. script.onload = function () {
  9221. if (onSuccess) {
  9222. onSuccess();
  9223. }
  9224. };
  9225. script.onerror = function (e) {
  9226. if (onError) {
  9227. onError("Unable to load script '" + scriptUrl + "'", e);
  9228. }
  9229. };
  9230. head.appendChild(script);
  9231. };
  9232. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9233. var reader = new FileReader();
  9234. var request = {
  9235. onCompleteObservable: new BABYLON.Observable(),
  9236. abort: function () { return reader.abort(); },
  9237. };
  9238. reader.onloadend = function (e) {
  9239. request.onCompleteObservable.notifyObservers(request);
  9240. };
  9241. reader.onload = function (e) {
  9242. //target doesn't have result from ts 1.3
  9243. callback(e.target['result']);
  9244. };
  9245. reader.onprogress = progressCallback;
  9246. reader.readAsDataURL(fileToLoad);
  9247. return request;
  9248. };
  9249. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9250. var reader = new FileReader();
  9251. var request = {
  9252. onCompleteObservable: new BABYLON.Observable(),
  9253. abort: function () { return reader.abort(); },
  9254. };
  9255. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9256. reader.onerror = function (e) {
  9257. Tools.Log("Error while reading file: " + fileToLoad.name);
  9258. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9259. };
  9260. reader.onload = function (e) {
  9261. //target doesn't have result from ts 1.3
  9262. callback(e.target['result']);
  9263. };
  9264. if (progressCallBack) {
  9265. reader.onprogress = progressCallBack;
  9266. }
  9267. if (!useArrayBuffer) {
  9268. // Asynchronous read
  9269. reader.readAsText(fileToLoad);
  9270. }
  9271. else {
  9272. reader.readAsArrayBuffer(fileToLoad);
  9273. }
  9274. return request;
  9275. };
  9276. //returns a downloadable url to a file content.
  9277. Tools.FileAsURL = function (content) {
  9278. var fileBlob = new Blob([content]);
  9279. var url = window.URL || window.webkitURL;
  9280. var link = url.createObjectURL(fileBlob);
  9281. return link;
  9282. };
  9283. // Misc.
  9284. Tools.Format = function (value, decimals) {
  9285. if (decimals === void 0) { decimals = 2; }
  9286. return value.toFixed(decimals);
  9287. };
  9288. Tools.CheckExtends = function (v, min, max) {
  9289. if (v.x < min.x)
  9290. min.x = v.x;
  9291. if (v.y < min.y)
  9292. min.y = v.y;
  9293. if (v.z < min.z)
  9294. min.z = v.z;
  9295. if (v.x > max.x)
  9296. max.x = v.x;
  9297. if (v.y > max.y)
  9298. max.y = v.y;
  9299. if (v.z > max.z)
  9300. max.z = v.z;
  9301. };
  9302. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9303. for (var prop in source) {
  9304. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9305. continue;
  9306. }
  9307. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9308. continue;
  9309. }
  9310. var sourceValue = source[prop];
  9311. var typeOfSourceValue = typeof sourceValue;
  9312. if (typeOfSourceValue === "function") {
  9313. continue;
  9314. }
  9315. try {
  9316. if (typeOfSourceValue === "object") {
  9317. if (sourceValue instanceof Array) {
  9318. destination[prop] = [];
  9319. if (sourceValue.length > 0) {
  9320. if (typeof sourceValue[0] == "object") {
  9321. for (var index = 0; index < sourceValue.length; index++) {
  9322. var clonedValue = cloneValue(sourceValue[index], destination);
  9323. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9324. destination[prop].push(clonedValue);
  9325. }
  9326. }
  9327. }
  9328. else {
  9329. destination[prop] = sourceValue.slice(0);
  9330. }
  9331. }
  9332. }
  9333. else {
  9334. destination[prop] = cloneValue(sourceValue, destination);
  9335. }
  9336. }
  9337. else {
  9338. destination[prop] = sourceValue;
  9339. }
  9340. }
  9341. catch (e) {
  9342. // Just ignore error (it could be because of a read-only property)
  9343. }
  9344. }
  9345. };
  9346. Tools.IsEmpty = function (obj) {
  9347. for (var i in obj) {
  9348. if (obj.hasOwnProperty(i)) {
  9349. return false;
  9350. }
  9351. }
  9352. return true;
  9353. };
  9354. Tools.RegisterTopRootEvents = function (events) {
  9355. for (var index = 0; index < events.length; index++) {
  9356. var event = events[index];
  9357. window.addEventListener(event.name, event.handler, false);
  9358. try {
  9359. if (window.parent) {
  9360. window.parent.addEventListener(event.name, event.handler, false);
  9361. }
  9362. }
  9363. catch (e) {
  9364. // Silently fails...
  9365. }
  9366. }
  9367. };
  9368. Tools.UnregisterTopRootEvents = function (events) {
  9369. for (var index = 0; index < events.length; index++) {
  9370. var event = events[index];
  9371. window.removeEventListener(event.name, event.handler);
  9372. try {
  9373. if (window.parent) {
  9374. window.parent.removeEventListener(event.name, event.handler);
  9375. }
  9376. }
  9377. catch (e) {
  9378. // Silently fails...
  9379. }
  9380. }
  9381. };
  9382. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9383. if (mimeType === void 0) { mimeType = "image/png"; }
  9384. // Read the contents of the framebuffer
  9385. var numberOfChannelsByLine = width * 4;
  9386. var halfHeight = height / 2;
  9387. //Reading datas from WebGL
  9388. var data = engine.readPixels(0, 0, width, height);
  9389. //To flip image on Y axis.
  9390. for (var i = 0; i < halfHeight; i++) {
  9391. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9392. var currentCell = j + i * numberOfChannelsByLine;
  9393. var targetLine = height - i - 1;
  9394. var targetCell = j + targetLine * numberOfChannelsByLine;
  9395. var temp = data[currentCell];
  9396. data[currentCell] = data[targetCell];
  9397. data[targetCell] = temp;
  9398. }
  9399. }
  9400. // Create a 2D canvas to store the result
  9401. if (!screenshotCanvas) {
  9402. screenshotCanvas = document.createElement('canvas');
  9403. }
  9404. screenshotCanvas.width = width;
  9405. screenshotCanvas.height = height;
  9406. var context = screenshotCanvas.getContext('2d');
  9407. if (context) {
  9408. // Copy the pixels to a 2D canvas
  9409. var imageData = context.createImageData(width, height);
  9410. var castData = (imageData.data);
  9411. castData.set(data);
  9412. context.putImageData(imageData, 0, 0);
  9413. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9414. }
  9415. };
  9416. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9417. if (mimeType === void 0) { mimeType = "image/png"; }
  9418. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9419. if (successCallback) {
  9420. successCallback(base64Image);
  9421. }
  9422. else {
  9423. // We need HTMLCanvasElement.toBlob for HD screenshots
  9424. if (!screenshotCanvas.toBlob) {
  9425. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9426. screenshotCanvas.toBlob = function (callback, type, quality) {
  9427. var _this = this;
  9428. setTimeout(function () {
  9429. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9430. for (var i = 0; i < len; i++) {
  9431. arr[i] = binStr.charCodeAt(i);
  9432. }
  9433. callback(new Blob([arr], { type: type || 'image/png' }));
  9434. });
  9435. };
  9436. }
  9437. screenshotCanvas.toBlob(function (blob) {
  9438. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9439. if (("download" in document.createElement("a"))) {
  9440. if (!fileName) {
  9441. var date = new Date();
  9442. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9443. fileName = "screenshot_" + stringDate + ".png";
  9444. }
  9445. Tools.Download(blob, fileName);
  9446. }
  9447. else {
  9448. var url = URL.createObjectURL(blob);
  9449. var newWindow = window.open("");
  9450. if (!newWindow)
  9451. return;
  9452. var img = newWindow.document.createElement("img");
  9453. img.onload = function () {
  9454. // no longer need to read the blob so it's revoked
  9455. URL.revokeObjectURL(url);
  9456. };
  9457. img.src = url;
  9458. newWindow.document.body.appendChild(img);
  9459. }
  9460. });
  9461. }
  9462. };
  9463. /**
  9464. * Downloads a blob in the browser
  9465. * @param blob defines the blob to download
  9466. * @param fileName defines the name of the downloaded file
  9467. */
  9468. Tools.Download = function (blob, fileName) {
  9469. var url = window.URL.createObjectURL(blob);
  9470. var a = document.createElement("a");
  9471. document.body.appendChild(a);
  9472. a.style.display = "none";
  9473. a.href = url;
  9474. a.download = fileName;
  9475. a.addEventListener("click", function () {
  9476. if (a.parentElement) {
  9477. a.parentElement.removeChild(a);
  9478. }
  9479. });
  9480. a.click();
  9481. window.URL.revokeObjectURL(url);
  9482. };
  9483. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9484. if (mimeType === void 0) { mimeType = "image/png"; }
  9485. var width;
  9486. var height;
  9487. // If a precision value is specified
  9488. if (size.precision) {
  9489. width = Math.round(engine.getRenderWidth() * size.precision);
  9490. height = Math.round(width / engine.getAspectRatio(camera));
  9491. }
  9492. else if (size.width && size.height) {
  9493. width = size.width;
  9494. height = size.height;
  9495. }
  9496. //If passing only width, computing height to keep display canvas ratio.
  9497. else if (size.width && !size.height) {
  9498. width = size.width;
  9499. height = Math.round(width / engine.getAspectRatio(camera));
  9500. }
  9501. //If passing only height, computing width to keep display canvas ratio.
  9502. else if (size.height && !size.width) {
  9503. height = size.height;
  9504. width = Math.round(height * engine.getAspectRatio(camera));
  9505. }
  9506. //Assuming here that "size" parameter is a number
  9507. else if (!isNaN(size)) {
  9508. height = size;
  9509. width = size;
  9510. }
  9511. else {
  9512. Tools.Error("Invalid 'size' parameter !");
  9513. return;
  9514. }
  9515. if (!screenshotCanvas) {
  9516. screenshotCanvas = document.createElement('canvas');
  9517. }
  9518. screenshotCanvas.width = width;
  9519. screenshotCanvas.height = height;
  9520. var renderContext = screenshotCanvas.getContext("2d");
  9521. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9522. var newWidth = width;
  9523. var newHeight = newWidth / ratio;
  9524. if (newHeight > height) {
  9525. newHeight = height;
  9526. newWidth = newHeight * ratio;
  9527. }
  9528. var offsetX = Math.max(0, width - newWidth) / 2;
  9529. var offsetY = Math.max(0, height - newHeight) / 2;
  9530. var renderingCanvas = engine.getRenderingCanvas();
  9531. if (renderContext && renderingCanvas) {
  9532. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9533. }
  9534. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9535. };
  9536. /**
  9537. * Generates an image screenshot from the specified camera.
  9538. *
  9539. * @param engine The engine to use for rendering
  9540. * @param camera The camera to use for rendering
  9541. * @param size This parameter can be set to a single number or to an object with the
  9542. * following (optional) properties: precision, width, height. If a single number is passed,
  9543. * it will be used for both width and height. If an object is passed, the screenshot size
  9544. * will be derived from the parameters. The precision property is a multiplier allowing
  9545. * rendering at a higher or lower resolution.
  9546. * @param successCallback The callback receives a single parameter which contains the
  9547. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9548. * src parameter of an <img> to display it.
  9549. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9550. * Check your browser for supported MIME types.
  9551. * @param samples Texture samples (default: 1)
  9552. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9553. * @param fileName A name for for the downloaded file.
  9554. * @constructor
  9555. */
  9556. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9557. if (mimeType === void 0) { mimeType = "image/png"; }
  9558. if (samples === void 0) { samples = 1; }
  9559. if (antialiasing === void 0) { antialiasing = false; }
  9560. var width;
  9561. var height;
  9562. //If a precision value is specified
  9563. if (size.precision) {
  9564. width = Math.round(engine.getRenderWidth() * size.precision);
  9565. height = Math.round(width / engine.getAspectRatio(camera));
  9566. size = { width: width, height: height };
  9567. }
  9568. else if (size.width && size.height) {
  9569. width = size.width;
  9570. height = size.height;
  9571. }
  9572. //If passing only width, computing height to keep display canvas ratio.
  9573. else if (size.width && !size.height) {
  9574. width = size.width;
  9575. height = Math.round(width / engine.getAspectRatio(camera));
  9576. size = { width: width, height: height };
  9577. }
  9578. //If passing only height, computing width to keep display canvas ratio.
  9579. else if (size.height && !size.width) {
  9580. height = size.height;
  9581. width = Math.round(height * engine.getAspectRatio(camera));
  9582. size = { width: width, height: height };
  9583. }
  9584. //Assuming here that "size" parameter is a number
  9585. else if (!isNaN(size)) {
  9586. height = size;
  9587. width = size;
  9588. }
  9589. else {
  9590. Tools.Error("Invalid 'size' parameter !");
  9591. return;
  9592. }
  9593. var scene = camera.getScene();
  9594. var previousCamera = null;
  9595. if (scene.activeCamera !== camera) {
  9596. previousCamera = scene.activeCamera;
  9597. scene.activeCamera = camera;
  9598. }
  9599. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9600. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9601. texture.renderList = null;
  9602. texture.samples = samples;
  9603. if (antialiasing) {
  9604. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9605. }
  9606. texture.onAfterRenderObservable.add(function () {
  9607. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9608. });
  9609. scene.incrementRenderId();
  9610. scene.resetCachedMaterial();
  9611. texture.render(true);
  9612. texture.dispose();
  9613. if (previousCamera) {
  9614. scene.activeCamera = previousCamera;
  9615. }
  9616. camera.getProjectionMatrix(true); // Force cache refresh;
  9617. };
  9618. // XHR response validator for local file scenario
  9619. Tools.ValidateXHRData = function (xhr, dataType) {
  9620. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9621. if (dataType === void 0) { dataType = 7; }
  9622. try {
  9623. if (dataType & 1) {
  9624. if (xhr.responseText && xhr.responseText.length > 0) {
  9625. return true;
  9626. }
  9627. else if (dataType === 1) {
  9628. return false;
  9629. }
  9630. }
  9631. if (dataType & 2) {
  9632. // Check header width and height since there is no "TGA" magic number
  9633. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9634. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9635. return true;
  9636. }
  9637. else if (dataType === 2) {
  9638. return false;
  9639. }
  9640. }
  9641. if (dataType & 4) {
  9642. // Check for the "DDS" magic number
  9643. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9644. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9645. return true;
  9646. }
  9647. else {
  9648. return false;
  9649. }
  9650. }
  9651. }
  9652. catch (e) {
  9653. // Global protection
  9654. }
  9655. return false;
  9656. };
  9657. /**
  9658. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9659. * Be aware Math.random() could cause collisions, but:
  9660. * "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"
  9661. */
  9662. Tools.RandomId = function () {
  9663. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9664. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9665. return v.toString(16);
  9666. });
  9667. };
  9668. /**
  9669. * Test if the given uri is a base64 string.
  9670. * @param uri The uri to test
  9671. * @return True if the uri is a base64 string or false otherwise.
  9672. */
  9673. Tools.IsBase64 = function (uri) {
  9674. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9675. };
  9676. /**
  9677. * Decode the given base64 uri.
  9678. * @param uri The uri to decode
  9679. * @return The decoded base64 data.
  9680. */
  9681. Tools.DecodeBase64 = function (uri) {
  9682. var decodedString = atob(uri.split(",")[1]);
  9683. var bufferLength = decodedString.length;
  9684. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9685. for (var i = 0; i < bufferLength; i++) {
  9686. bufferView[i] = decodedString.charCodeAt(i);
  9687. }
  9688. return bufferView.buffer;
  9689. };
  9690. Object.defineProperty(Tools, "NoneLogLevel", {
  9691. get: function () {
  9692. return Tools._NoneLogLevel;
  9693. },
  9694. enumerable: true,
  9695. configurable: true
  9696. });
  9697. Object.defineProperty(Tools, "MessageLogLevel", {
  9698. get: function () {
  9699. return Tools._MessageLogLevel;
  9700. },
  9701. enumerable: true,
  9702. configurable: true
  9703. });
  9704. Object.defineProperty(Tools, "WarningLogLevel", {
  9705. get: function () {
  9706. return Tools._WarningLogLevel;
  9707. },
  9708. enumerable: true,
  9709. configurable: true
  9710. });
  9711. Object.defineProperty(Tools, "ErrorLogLevel", {
  9712. get: function () {
  9713. return Tools._ErrorLogLevel;
  9714. },
  9715. enumerable: true,
  9716. configurable: true
  9717. });
  9718. Object.defineProperty(Tools, "AllLogLevel", {
  9719. get: function () {
  9720. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9721. },
  9722. enumerable: true,
  9723. configurable: true
  9724. });
  9725. Tools._AddLogEntry = function (entry) {
  9726. Tools._LogCache = entry + Tools._LogCache;
  9727. if (Tools.OnNewCacheEntry) {
  9728. Tools.OnNewCacheEntry(entry);
  9729. }
  9730. };
  9731. Tools._FormatMessage = function (message) {
  9732. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9733. var date = new Date();
  9734. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9735. };
  9736. Tools._LogDisabled = function (message) {
  9737. // nothing to do
  9738. };
  9739. Tools._LogEnabled = function (message) {
  9740. var formattedMessage = Tools._FormatMessage(message);
  9741. console.log("BJS - " + formattedMessage);
  9742. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9743. Tools._AddLogEntry(entry);
  9744. };
  9745. Tools._WarnDisabled = function (message) {
  9746. // nothing to do
  9747. };
  9748. Tools._WarnEnabled = function (message) {
  9749. var formattedMessage = Tools._FormatMessage(message);
  9750. console.warn("BJS - " + formattedMessage);
  9751. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9752. Tools._AddLogEntry(entry);
  9753. };
  9754. Tools._ErrorDisabled = function (message) {
  9755. // nothing to do
  9756. };
  9757. Tools._ErrorEnabled = function (message) {
  9758. Tools.errorsCount++;
  9759. var formattedMessage = Tools._FormatMessage(message);
  9760. console.error("BJS - " + formattedMessage);
  9761. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9762. Tools._AddLogEntry(entry);
  9763. };
  9764. Object.defineProperty(Tools, "LogCache", {
  9765. get: function () {
  9766. return Tools._LogCache;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Tools.ClearLogCache = function () {
  9772. Tools._LogCache = "";
  9773. Tools.errorsCount = 0;
  9774. };
  9775. Object.defineProperty(Tools, "LogLevels", {
  9776. set: function (level) {
  9777. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9778. Tools.Log = Tools._LogEnabled;
  9779. }
  9780. else {
  9781. Tools.Log = Tools._LogDisabled;
  9782. }
  9783. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9784. Tools.Warn = Tools._WarnEnabled;
  9785. }
  9786. else {
  9787. Tools.Warn = Tools._WarnDisabled;
  9788. }
  9789. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9790. Tools.Error = Tools._ErrorEnabled;
  9791. }
  9792. else {
  9793. Tools.Error = Tools._ErrorDisabled;
  9794. }
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Tools.IsWindowObjectExist = function () {
  9800. return (typeof window) !== "undefined";
  9801. };
  9802. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9803. get: function () {
  9804. return Tools._PerformanceNoneLogLevel;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9810. get: function () {
  9811. return Tools._PerformanceUserMarkLogLevel;
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9817. get: function () {
  9818. return Tools._PerformanceConsoleLogLevel;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9824. set: function (level) {
  9825. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9826. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9827. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9828. return;
  9829. }
  9830. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9831. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9832. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9833. return;
  9834. }
  9835. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9836. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9842. };
  9843. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9844. };
  9845. Tools._StartUserMark = function (counterName, condition) {
  9846. if (condition === void 0) { condition = true; }
  9847. if (!Tools._performance) {
  9848. if (!Tools.IsWindowObjectExist()) {
  9849. return;
  9850. }
  9851. Tools._performance = window.performance;
  9852. }
  9853. if (!condition || !Tools._performance.mark) {
  9854. return;
  9855. }
  9856. Tools._performance.mark(counterName + "-Begin");
  9857. };
  9858. Tools._EndUserMark = function (counterName, condition) {
  9859. if (condition === void 0) { condition = true; }
  9860. if (!condition || !Tools._performance.mark) {
  9861. return;
  9862. }
  9863. Tools._performance.mark(counterName + "-End");
  9864. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9865. };
  9866. Tools._StartPerformanceConsole = function (counterName, condition) {
  9867. if (condition === void 0) { condition = true; }
  9868. if (!condition) {
  9869. return;
  9870. }
  9871. Tools._StartUserMark(counterName, condition);
  9872. if (console.time) {
  9873. console.time(counterName);
  9874. }
  9875. };
  9876. Tools._EndPerformanceConsole = function (counterName, condition) {
  9877. if (condition === void 0) { condition = true; }
  9878. if (!condition) {
  9879. return;
  9880. }
  9881. Tools._EndUserMark(counterName, condition);
  9882. if (console.time) {
  9883. console.timeEnd(counterName);
  9884. }
  9885. };
  9886. Object.defineProperty(Tools, "Now", {
  9887. get: function () {
  9888. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9889. return window.performance.now();
  9890. }
  9891. return Date.now();
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. /**
  9897. * This method will return the name of the class used to create the instance of the given object.
  9898. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9899. * @param object the object to get the class name from
  9900. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9901. */
  9902. Tools.GetClassName = function (object, isType) {
  9903. if (isType === void 0) { isType = false; }
  9904. var name = null;
  9905. if (!isType && object.getClassName) {
  9906. name = object.getClassName();
  9907. }
  9908. else {
  9909. if (object instanceof Object) {
  9910. var classObj = isType ? object : Object.getPrototypeOf(object);
  9911. name = classObj.constructor["__bjsclassName__"];
  9912. }
  9913. if (!name) {
  9914. name = typeof object;
  9915. }
  9916. }
  9917. return name;
  9918. };
  9919. Tools.First = function (array, predicate) {
  9920. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9921. var el = array_1[_i];
  9922. if (predicate(el)) {
  9923. return el;
  9924. }
  9925. }
  9926. return null;
  9927. };
  9928. /**
  9929. * This method will return the name of the full name of the class, including its owning module (if any).
  9930. * 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).
  9931. * @param object the object to get the class name from
  9932. * @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.
  9933. */
  9934. Tools.getFullClassName = function (object, isType) {
  9935. if (isType === void 0) { isType = false; }
  9936. var className = null;
  9937. var moduleName = null;
  9938. if (!isType && object.getClassName) {
  9939. className = object.getClassName();
  9940. }
  9941. else {
  9942. if (object instanceof Object) {
  9943. var classObj = isType ? object : Object.getPrototypeOf(object);
  9944. className = classObj.constructor["__bjsclassName__"];
  9945. moduleName = classObj.constructor["__bjsmoduleName__"];
  9946. }
  9947. if (!className) {
  9948. className = typeof object;
  9949. }
  9950. }
  9951. if (!className) {
  9952. return null;
  9953. }
  9954. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9955. };
  9956. /**
  9957. * 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.
  9958. * @param array
  9959. */
  9960. Tools.arrayOrStringFeeder = function (array) {
  9961. return function (index) {
  9962. if (index >= array.length) {
  9963. return null;
  9964. }
  9965. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9966. if (val && val.getHashCode) {
  9967. val = val.getHashCode();
  9968. }
  9969. if (typeof val === "string") {
  9970. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9971. }
  9972. return val;
  9973. };
  9974. };
  9975. /**
  9976. * Compute the hashCode of a stream of number
  9977. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9978. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9979. * @return the hash code computed
  9980. */
  9981. Tools.hashCodeFromStream = function (feeder) {
  9982. // Based from here: http://stackoverflow.com/a/7616484/802124
  9983. var hash = 0;
  9984. var index = 0;
  9985. var chr = feeder(index++);
  9986. while (chr != null) {
  9987. hash = ((hash << 5) - hash) + chr;
  9988. hash |= 0; // Convert to 32bit integer
  9989. chr = feeder(index++);
  9990. }
  9991. return hash;
  9992. };
  9993. /**
  9994. * Returns a promise that resolves after the given amount of time.
  9995. * @param delay Number of milliseconds to delay
  9996. * @returns Promise that resolves after the given amount of time
  9997. */
  9998. Tools.DelayAsync = function (delay) {
  9999. return new Promise(function (resolve) {
  10000. setTimeout(function () {
  10001. resolve();
  10002. }, delay);
  10003. });
  10004. };
  10005. /**
  10006. * Gets the current gradient from an array of IValueGradient
  10007. * @param ratio defines the current ratio to get
  10008. * @param gradients defines the array of IValueGradient
  10009. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10010. */
  10011. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10012. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10013. var currentGradient = gradients[gradientIndex];
  10014. var nextGradient = gradients[gradientIndex + 1];
  10015. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10016. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10017. updateFunc(currentGradient, nextGradient, scale);
  10018. }
  10019. }
  10020. };
  10021. Tools.BaseUrl = "";
  10022. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10023. /**
  10024. * Default behaviour for cors in the application.
  10025. * It can be a string if the expected behavior is identical in the entire app.
  10026. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10027. */
  10028. Tools.CorsBehavior = "anonymous";
  10029. Tools.UseFallbackTexture = true;
  10030. /**
  10031. * Use this object to register external classes like custom textures or material
  10032. * to allow the laoders to instantiate them
  10033. */
  10034. Tools.RegisteredExternalClasses = {};
  10035. // Used in case of a texture loading problem
  10036. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQM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l+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";
  10037. Tools._tmpFloatArray = new Float32Array(1);
  10038. Tools.PreprocessUrl = function (url) {
  10039. return url;
  10040. };
  10041. // Logs
  10042. Tools._NoneLogLevel = 0;
  10043. Tools._MessageLogLevel = 1;
  10044. Tools._WarningLogLevel = 2;
  10045. Tools._ErrorLogLevel = 4;
  10046. Tools._LogCache = "";
  10047. Tools.errorsCount = 0;
  10048. Tools.Log = Tools._LogEnabled;
  10049. Tools.Warn = Tools._WarnEnabled;
  10050. Tools.Error = Tools._ErrorEnabled;
  10051. // Performances
  10052. Tools._PerformanceNoneLogLevel = 0;
  10053. Tools._PerformanceUserMarkLogLevel = 1;
  10054. Tools._PerformanceConsoleLogLevel = 2;
  10055. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10056. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10057. return Tools;
  10058. }());
  10059. BABYLON.Tools = Tools;
  10060. /**
  10061. * This class is used to track a performance counter which is number based.
  10062. * The user has access to many properties which give statistics of different nature
  10063. *
  10064. * The implementer can track two kinds of Performance Counter: time and count
  10065. * 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.
  10066. * 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.
  10067. */
  10068. var PerfCounter = /** @class */ (function () {
  10069. function PerfCounter() {
  10070. this._startMonitoringTime = 0;
  10071. this._min = 0;
  10072. this._max = 0;
  10073. this._average = 0;
  10074. this._lastSecAverage = 0;
  10075. this._current = 0;
  10076. this._totalValueCount = 0;
  10077. this._totalAccumulated = 0;
  10078. this._lastSecAccumulated = 0;
  10079. this._lastSecTime = 0;
  10080. this._lastSecValueCount = 0;
  10081. }
  10082. Object.defineProperty(PerfCounter.prototype, "min", {
  10083. /**
  10084. * Returns the smallest value ever
  10085. */
  10086. get: function () {
  10087. return this._min;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(PerfCounter.prototype, "max", {
  10093. /**
  10094. * Returns the biggest value ever
  10095. */
  10096. get: function () {
  10097. return this._max;
  10098. },
  10099. enumerable: true,
  10100. configurable: true
  10101. });
  10102. Object.defineProperty(PerfCounter.prototype, "average", {
  10103. /**
  10104. * Returns the average value since the performance counter is running
  10105. */
  10106. get: function () {
  10107. return this._average;
  10108. },
  10109. enumerable: true,
  10110. configurable: true
  10111. });
  10112. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10113. /**
  10114. * Returns the average value of the last second the counter was monitored
  10115. */
  10116. get: function () {
  10117. return this._lastSecAverage;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(PerfCounter.prototype, "current", {
  10123. /**
  10124. * Returns the current value
  10125. */
  10126. get: function () {
  10127. return this._current;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(PerfCounter.prototype, "total", {
  10133. get: function () {
  10134. return this._totalAccumulated;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(PerfCounter.prototype, "count", {
  10140. get: function () {
  10141. return this._totalValueCount;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. /**
  10147. * Call this method to start monitoring a new frame.
  10148. * 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.
  10149. */
  10150. PerfCounter.prototype.fetchNewFrame = function () {
  10151. this._totalValueCount++;
  10152. this._current = 0;
  10153. this._lastSecValueCount++;
  10154. };
  10155. /**
  10156. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10157. * @param newCount the count value to add to the monitored count
  10158. * @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.
  10159. */
  10160. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10161. if (!PerfCounter.Enabled) {
  10162. return;
  10163. }
  10164. this._current += newCount;
  10165. if (fetchResult) {
  10166. this._fetchResult();
  10167. }
  10168. };
  10169. /**
  10170. * Start monitoring this performance counter
  10171. */
  10172. PerfCounter.prototype.beginMonitoring = function () {
  10173. if (!PerfCounter.Enabled) {
  10174. return;
  10175. }
  10176. this._startMonitoringTime = Tools.Now;
  10177. };
  10178. /**
  10179. * Compute the time lapsed since the previous beginMonitoring() call.
  10180. * @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
  10181. */
  10182. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10183. if (newFrame === void 0) { newFrame = true; }
  10184. if (!PerfCounter.Enabled) {
  10185. return;
  10186. }
  10187. if (newFrame) {
  10188. this.fetchNewFrame();
  10189. }
  10190. var currentTime = Tools.Now;
  10191. this._current = currentTime - this._startMonitoringTime;
  10192. if (newFrame) {
  10193. this._fetchResult();
  10194. }
  10195. };
  10196. PerfCounter.prototype._fetchResult = function () {
  10197. this._totalAccumulated += this._current;
  10198. this._lastSecAccumulated += this._current;
  10199. // Min/Max update
  10200. this._min = Math.min(this._min, this._current);
  10201. this._max = Math.max(this._max, this._current);
  10202. this._average = this._totalAccumulated / this._totalValueCount;
  10203. // Reset last sec?
  10204. var now = Tools.Now;
  10205. if ((now - this._lastSecTime) > 1000) {
  10206. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10207. this._lastSecTime = now;
  10208. this._lastSecAccumulated = 0;
  10209. this._lastSecValueCount = 0;
  10210. }
  10211. };
  10212. PerfCounter.Enabled = true;
  10213. return PerfCounter;
  10214. }());
  10215. BABYLON.PerfCounter = PerfCounter;
  10216. /**
  10217. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10218. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10219. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10220. * @param name The name of the class, case should be preserved
  10221. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10222. */
  10223. function className(name, module) {
  10224. return function (target) {
  10225. target["__bjsclassName__"] = name;
  10226. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10227. };
  10228. }
  10229. BABYLON.className = className;
  10230. /**
  10231. * An implementation of a loop for asynchronous functions.
  10232. */
  10233. var AsyncLoop = /** @class */ (function () {
  10234. /**
  10235. * Constroctor.
  10236. * @param iterations the number of iterations.
  10237. * @param _fn the function to run each iteration
  10238. * @param _successCallback the callback that will be called upon succesful execution
  10239. * @param offset starting offset.
  10240. */
  10241. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10242. if (offset === void 0) { offset = 0; }
  10243. this.iterations = iterations;
  10244. this._fn = _fn;
  10245. this._successCallback = _successCallback;
  10246. this.index = offset - 1;
  10247. this._done = false;
  10248. }
  10249. /**
  10250. * Execute the next iteration. Must be called after the last iteration was finished.
  10251. */
  10252. AsyncLoop.prototype.executeNext = function () {
  10253. if (!this._done) {
  10254. if (this.index + 1 < this.iterations) {
  10255. ++this.index;
  10256. this._fn(this);
  10257. }
  10258. else {
  10259. this.breakLoop();
  10260. }
  10261. }
  10262. };
  10263. /**
  10264. * Break the loop and run the success callback.
  10265. */
  10266. AsyncLoop.prototype.breakLoop = function () {
  10267. this._done = true;
  10268. this._successCallback();
  10269. };
  10270. /**
  10271. * Helper function
  10272. */
  10273. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10274. if (offset === void 0) { offset = 0; }
  10275. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10276. loop.executeNext();
  10277. return loop;
  10278. };
  10279. /**
  10280. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10281. * @param iterations total number of iterations
  10282. * @param syncedIterations number of synchronous iterations in each async iteration.
  10283. * @param fn the function to call each iteration.
  10284. * @param callback a success call back that will be called when iterating stops.
  10285. * @param breakFunction a break condition (optional)
  10286. * @param timeout timeout settings for the setTimeout function. default - 0.
  10287. * @constructor
  10288. */
  10289. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10290. if (timeout === void 0) { timeout = 0; }
  10291. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10292. if (breakFunction && breakFunction())
  10293. loop.breakLoop();
  10294. else {
  10295. setTimeout(function () {
  10296. for (var i = 0; i < syncedIterations; ++i) {
  10297. var iteration = (loop.index * syncedIterations) + i;
  10298. if (iteration >= iterations)
  10299. break;
  10300. fn(iteration);
  10301. if (breakFunction && breakFunction()) {
  10302. loop.breakLoop();
  10303. break;
  10304. }
  10305. }
  10306. loop.executeNext();
  10307. }, timeout);
  10308. }
  10309. }, callback);
  10310. };
  10311. return AsyncLoop;
  10312. }());
  10313. BABYLON.AsyncLoop = AsyncLoop;
  10314. })(BABYLON || (BABYLON = {}));
  10315. //# sourceMappingURL=babylon.tools.js.map
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var PromiseStates;
  10319. (function (PromiseStates) {
  10320. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10321. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10322. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10323. })(PromiseStates || (PromiseStates = {}));
  10324. var FulFillmentAgregator = /** @class */ (function () {
  10325. function FulFillmentAgregator() {
  10326. this.count = 0;
  10327. this.target = 0;
  10328. this.results = [];
  10329. }
  10330. return FulFillmentAgregator;
  10331. }());
  10332. var InternalPromise = /** @class */ (function () {
  10333. function InternalPromise(resolver) {
  10334. var _this = this;
  10335. this._state = PromiseStates.Pending;
  10336. this._children = new Array();
  10337. this._rejectWasConsumed = false;
  10338. if (!resolver) {
  10339. return;
  10340. }
  10341. try {
  10342. resolver(function (value) {
  10343. _this._resolve(value);
  10344. }, function (reason) {
  10345. _this._reject(reason);
  10346. });
  10347. }
  10348. catch (e) {
  10349. this._reject(e);
  10350. }
  10351. }
  10352. Object.defineProperty(InternalPromise.prototype, "_result", {
  10353. get: function () {
  10354. return this._resultValue;
  10355. },
  10356. set: function (value) {
  10357. this._resultValue = value;
  10358. if (this._parent && this._parent._result === undefined) {
  10359. this._parent._result = value;
  10360. }
  10361. },
  10362. enumerable: true,
  10363. configurable: true
  10364. });
  10365. InternalPromise.prototype.catch = function (onRejected) {
  10366. return this.then(undefined, onRejected);
  10367. };
  10368. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10369. var _this = this;
  10370. var newPromise = new InternalPromise();
  10371. newPromise._onFulfilled = onFulfilled;
  10372. newPromise._onRejected = onRejected;
  10373. // Composition
  10374. this._children.push(newPromise);
  10375. newPromise._parent = this;
  10376. if (this._state !== PromiseStates.Pending) {
  10377. BABYLON.Tools.SetImmediate(function () {
  10378. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10379. var returnedValue = newPromise._resolve(_this._result);
  10380. if (returnedValue !== undefined && returnedValue !== null) {
  10381. if (returnedValue._state !== undefined) {
  10382. var returnedPromise = returnedValue;
  10383. newPromise._children.push(returnedPromise);
  10384. returnedPromise._parent = newPromise;
  10385. newPromise = returnedPromise;
  10386. }
  10387. else {
  10388. newPromise._result = returnedValue;
  10389. }
  10390. }
  10391. }
  10392. else {
  10393. newPromise._reject(_this._reason);
  10394. }
  10395. });
  10396. }
  10397. return newPromise;
  10398. };
  10399. InternalPromise.prototype._moveChildren = function (children) {
  10400. var _this = this;
  10401. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10402. this._children.forEach(function (child) {
  10403. child._parent = _this;
  10404. });
  10405. if (this._state === PromiseStates.Fulfilled) {
  10406. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10407. var child = _b[_i];
  10408. child._resolve(this._result);
  10409. }
  10410. }
  10411. else if (this._state === PromiseStates.Rejected) {
  10412. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10413. var child = _d[_c];
  10414. child._reject(this._reason);
  10415. }
  10416. }
  10417. var _a;
  10418. };
  10419. InternalPromise.prototype._resolve = function (value) {
  10420. try {
  10421. this._state = PromiseStates.Fulfilled;
  10422. var returnedValue = null;
  10423. if (this._onFulfilled) {
  10424. returnedValue = this._onFulfilled(value);
  10425. }
  10426. if (returnedValue !== undefined && returnedValue !== null) {
  10427. if (returnedValue._state !== undefined) {
  10428. // Transmit children
  10429. var returnedPromise = returnedValue;
  10430. returnedPromise._parent = this;
  10431. returnedPromise._moveChildren(this._children);
  10432. value = returnedPromise._result;
  10433. }
  10434. else {
  10435. value = returnedValue;
  10436. }
  10437. }
  10438. this._result = value;
  10439. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10440. var child = _a[_i];
  10441. child._resolve(value);
  10442. }
  10443. this._children.length = 0;
  10444. delete this._onFulfilled;
  10445. delete this._onRejected;
  10446. }
  10447. catch (e) {
  10448. this._reject(e, true);
  10449. }
  10450. };
  10451. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10452. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10453. this._state = PromiseStates.Rejected;
  10454. this._reason = reason;
  10455. if (this._onRejected && !onLocalThrow) {
  10456. try {
  10457. this._onRejected(reason);
  10458. this._rejectWasConsumed = true;
  10459. }
  10460. catch (e) {
  10461. reason = e;
  10462. }
  10463. }
  10464. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10465. var child = _a[_i];
  10466. if (this._rejectWasConsumed) {
  10467. child._resolve(null);
  10468. }
  10469. else {
  10470. child._reject(reason);
  10471. }
  10472. }
  10473. this._children.length = 0;
  10474. delete this._onFulfilled;
  10475. delete this._onRejected;
  10476. };
  10477. InternalPromise.resolve = function (value) {
  10478. var newPromise = new InternalPromise();
  10479. newPromise._resolve(value);
  10480. return newPromise;
  10481. };
  10482. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10483. promise.then(function (value) {
  10484. agregator.results[index] = value;
  10485. agregator.count++;
  10486. if (agregator.count === agregator.target) {
  10487. agregator.rootPromise._resolve(agregator.results);
  10488. }
  10489. return null;
  10490. }, function (reason) {
  10491. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10492. agregator.rootPromise._reject(reason);
  10493. }
  10494. });
  10495. };
  10496. InternalPromise.all = function (promises) {
  10497. var newPromise = new InternalPromise();
  10498. var agregator = new FulFillmentAgregator();
  10499. agregator.target = promises.length;
  10500. agregator.rootPromise = newPromise;
  10501. if (promises.length) {
  10502. for (var index = 0; index < promises.length; index++) {
  10503. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10504. }
  10505. }
  10506. else {
  10507. newPromise._resolve([]);
  10508. }
  10509. return newPromise;
  10510. };
  10511. InternalPromise.race = function (promises) {
  10512. var newPromise = new InternalPromise();
  10513. if (promises.length) {
  10514. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10515. var promise = promises_1[_i];
  10516. promise.then(function (value) {
  10517. if (newPromise) {
  10518. newPromise._resolve(value);
  10519. newPromise = null;
  10520. }
  10521. return null;
  10522. }, function (reason) {
  10523. if (newPromise) {
  10524. newPromise._reject(reason);
  10525. newPromise = null;
  10526. }
  10527. });
  10528. }
  10529. }
  10530. return newPromise;
  10531. };
  10532. return InternalPromise;
  10533. }());
  10534. /**
  10535. * Helper class that provides a small promise polyfill
  10536. */
  10537. var PromisePolyfill = /** @class */ (function () {
  10538. function PromisePolyfill() {
  10539. }
  10540. /**
  10541. * Static function used to check if the polyfill is required
  10542. * If this is the case then the function will inject the polyfill to window.Promise
  10543. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10544. */
  10545. PromisePolyfill.Apply = function (force) {
  10546. if (force === void 0) { force = false; }
  10547. if (force || typeof Promise === 'undefined') {
  10548. var root = window;
  10549. root.Promise = InternalPromise;
  10550. }
  10551. };
  10552. return PromisePolyfill;
  10553. }());
  10554. BABYLON.PromisePolyfill = PromisePolyfill;
  10555. })(BABYLON || (BABYLON = {}));
  10556. //# sourceMappingURL=babylon.promise.js.map
  10557. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. /**
  10561. * Helper class to push actions to a pool of workers.
  10562. */
  10563. var WorkerPool = /** @class */ (function () {
  10564. /**
  10565. * Constructor
  10566. * @param workers Array of workers to use for actions
  10567. */
  10568. function WorkerPool(workers) {
  10569. this._pendingActions = new Array();
  10570. this._workerInfos = workers.map(function (worker) { return ({
  10571. worker: worker,
  10572. active: false
  10573. }); });
  10574. }
  10575. /**
  10576. * Terminates all workers and clears any pending actions.
  10577. */
  10578. WorkerPool.prototype.dispose = function () {
  10579. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10580. var workerInfo = _a[_i];
  10581. workerInfo.worker.terminate();
  10582. }
  10583. delete this._workerInfos;
  10584. delete this._pendingActions;
  10585. };
  10586. /**
  10587. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10588. * pended until a worker has completed its action.
  10589. * @param action The action to perform. Call onComplete when the action is complete.
  10590. */
  10591. WorkerPool.prototype.push = function (action) {
  10592. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10593. var workerInfo = _a[_i];
  10594. if (!workerInfo.active) {
  10595. this._execute(workerInfo, action);
  10596. return;
  10597. }
  10598. }
  10599. this._pendingActions.push(action);
  10600. };
  10601. WorkerPool.prototype._execute = function (workerInfo, action) {
  10602. var _this = this;
  10603. workerInfo.active = true;
  10604. action(workerInfo.worker, function () {
  10605. workerInfo.active = false;
  10606. var nextAction = _this._pendingActions.shift();
  10607. if (nextAction) {
  10608. _this._execute(workerInfo, nextAction);
  10609. }
  10610. });
  10611. };
  10612. return WorkerPool;
  10613. }());
  10614. BABYLON.WorkerPool = WorkerPool;
  10615. })(BABYLON || (BABYLON = {}));
  10616. //# sourceMappingURL=babylon.workerPool.js.map
  10617. var BABYLON;
  10618. (function (BABYLON) {
  10619. /**
  10620. * @hidden
  10621. **/
  10622. var _AlphaState = /** @class */ (function () {
  10623. /**
  10624. * Initializes the state.
  10625. */
  10626. function _AlphaState() {
  10627. this._isAlphaBlendDirty = false;
  10628. this._isBlendFunctionParametersDirty = false;
  10629. this._isBlendEquationParametersDirty = false;
  10630. this._isBlendConstantsDirty = false;
  10631. this._alphaBlend = false;
  10632. this._blendFunctionParameters = new Array(4);
  10633. this._blendEquationParameters = new Array(2);
  10634. this._blendConstants = new Array(4);
  10635. this.reset();
  10636. }
  10637. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10638. get: function () {
  10639. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10645. get: function () {
  10646. return this._alphaBlend;
  10647. },
  10648. set: function (value) {
  10649. if (this._alphaBlend === value) {
  10650. return;
  10651. }
  10652. this._alphaBlend = value;
  10653. this._isAlphaBlendDirty = true;
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10659. if (this._blendConstants[0] === r &&
  10660. this._blendConstants[1] === g &&
  10661. this._blendConstants[2] === b &&
  10662. this._blendConstants[3] === a) {
  10663. return;
  10664. }
  10665. this._blendConstants[0] = r;
  10666. this._blendConstants[1] = g;
  10667. this._blendConstants[2] = b;
  10668. this._blendConstants[3] = a;
  10669. this._isBlendConstantsDirty = true;
  10670. };
  10671. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10672. if (this._blendFunctionParameters[0] === value0 &&
  10673. this._blendFunctionParameters[1] === value1 &&
  10674. this._blendFunctionParameters[2] === value2 &&
  10675. this._blendFunctionParameters[3] === value3) {
  10676. return;
  10677. }
  10678. this._blendFunctionParameters[0] = value0;
  10679. this._blendFunctionParameters[1] = value1;
  10680. this._blendFunctionParameters[2] = value2;
  10681. this._blendFunctionParameters[3] = value3;
  10682. this._isBlendFunctionParametersDirty = true;
  10683. };
  10684. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10685. if (this._blendEquationParameters[0] === rgb &&
  10686. this._blendEquationParameters[1] === alpha) {
  10687. return;
  10688. }
  10689. this._blendEquationParameters[0] = rgb;
  10690. this._blendEquationParameters[1] = alpha;
  10691. this._isBlendEquationParametersDirty = true;
  10692. };
  10693. _AlphaState.prototype.reset = function () {
  10694. this._alphaBlend = false;
  10695. this._blendFunctionParameters[0] = null;
  10696. this._blendFunctionParameters[1] = null;
  10697. this._blendFunctionParameters[2] = null;
  10698. this._blendFunctionParameters[3] = null;
  10699. this._blendEquationParameters[0] = null;
  10700. this._blendEquationParameters[1] = null;
  10701. this._blendConstants[0] = null;
  10702. this._blendConstants[1] = null;
  10703. this._blendConstants[2] = null;
  10704. this._blendConstants[3] = null;
  10705. this._isAlphaBlendDirty = true;
  10706. this._isBlendFunctionParametersDirty = false;
  10707. this._isBlendEquationParametersDirty = false;
  10708. this._isBlendConstantsDirty = false;
  10709. };
  10710. _AlphaState.prototype.apply = function (gl) {
  10711. if (!this.isDirty) {
  10712. return;
  10713. }
  10714. // Alpha blend
  10715. if (this._isAlphaBlendDirty) {
  10716. if (this._alphaBlend) {
  10717. gl.enable(gl.BLEND);
  10718. }
  10719. else {
  10720. gl.disable(gl.BLEND);
  10721. }
  10722. this._isAlphaBlendDirty = false;
  10723. }
  10724. // Alpha function
  10725. if (this._isBlendFunctionParametersDirty) {
  10726. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10727. this._isBlendFunctionParametersDirty = false;
  10728. }
  10729. // Alpha equation
  10730. if (this._isBlendEquationParametersDirty) {
  10731. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10732. this._isBlendEquationParametersDirty = false;
  10733. }
  10734. // Constants
  10735. if (this._isBlendConstantsDirty) {
  10736. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10737. this._isBlendConstantsDirty = false;
  10738. }
  10739. };
  10740. return _AlphaState;
  10741. }());
  10742. BABYLON._AlphaState = _AlphaState;
  10743. })(BABYLON || (BABYLON = {}));
  10744. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10745. var BABYLON;
  10746. (function (BABYLON) {
  10747. /**
  10748. * @hidden
  10749. **/
  10750. var _DepthCullingState = /** @class */ (function () {
  10751. /**
  10752. * Initializes the state.
  10753. */
  10754. function _DepthCullingState() {
  10755. this._isDepthTestDirty = false;
  10756. this._isDepthMaskDirty = false;
  10757. this._isDepthFuncDirty = false;
  10758. this._isCullFaceDirty = false;
  10759. this._isCullDirty = false;
  10760. this._isZOffsetDirty = false;
  10761. this._isFrontFaceDirty = false;
  10762. this.reset();
  10763. }
  10764. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10765. get: function () {
  10766. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10772. get: function () {
  10773. return this._zOffset;
  10774. },
  10775. set: function (value) {
  10776. if (this._zOffset === value) {
  10777. return;
  10778. }
  10779. this._zOffset = value;
  10780. this._isZOffsetDirty = true;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10786. get: function () {
  10787. return this._cullFace;
  10788. },
  10789. set: function (value) {
  10790. if (this._cullFace === value) {
  10791. return;
  10792. }
  10793. this._cullFace = value;
  10794. this._isCullFaceDirty = true;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10800. get: function () {
  10801. return this._cull;
  10802. },
  10803. set: function (value) {
  10804. if (this._cull === value) {
  10805. return;
  10806. }
  10807. this._cull = value;
  10808. this._isCullDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10814. get: function () {
  10815. return this._depthFunc;
  10816. },
  10817. set: function (value) {
  10818. if (this._depthFunc === value) {
  10819. return;
  10820. }
  10821. this._depthFunc = value;
  10822. this._isDepthFuncDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10828. get: function () {
  10829. return this._depthMask;
  10830. },
  10831. set: function (value) {
  10832. if (this._depthMask === value) {
  10833. return;
  10834. }
  10835. this._depthMask = value;
  10836. this._isDepthMaskDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10842. get: function () {
  10843. return this._depthTest;
  10844. },
  10845. set: function (value) {
  10846. if (this._depthTest === value) {
  10847. return;
  10848. }
  10849. this._depthTest = value;
  10850. this._isDepthTestDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10856. get: function () {
  10857. return this._frontFace;
  10858. },
  10859. set: function (value) {
  10860. if (this._frontFace === value) {
  10861. return;
  10862. }
  10863. this._frontFace = value;
  10864. this._isFrontFaceDirty = true;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. _DepthCullingState.prototype.reset = function () {
  10870. this._depthMask = true;
  10871. this._depthTest = true;
  10872. this._depthFunc = null;
  10873. this._cullFace = null;
  10874. this._cull = null;
  10875. this._zOffset = 0;
  10876. this._frontFace = null;
  10877. this._isDepthTestDirty = true;
  10878. this._isDepthMaskDirty = true;
  10879. this._isDepthFuncDirty = false;
  10880. this._isCullFaceDirty = false;
  10881. this._isCullDirty = false;
  10882. this._isZOffsetDirty = false;
  10883. this._isFrontFaceDirty = false;
  10884. };
  10885. _DepthCullingState.prototype.apply = function (gl) {
  10886. if (!this.isDirty) {
  10887. return;
  10888. }
  10889. // Cull
  10890. if (this._isCullDirty) {
  10891. if (this.cull) {
  10892. gl.enable(gl.CULL_FACE);
  10893. }
  10894. else {
  10895. gl.disable(gl.CULL_FACE);
  10896. }
  10897. this._isCullDirty = false;
  10898. }
  10899. // Cull face
  10900. if (this._isCullFaceDirty) {
  10901. gl.cullFace(this.cullFace);
  10902. this._isCullFaceDirty = false;
  10903. }
  10904. // Depth mask
  10905. if (this._isDepthMaskDirty) {
  10906. gl.depthMask(this.depthMask);
  10907. this._isDepthMaskDirty = false;
  10908. }
  10909. // Depth test
  10910. if (this._isDepthTestDirty) {
  10911. if (this.depthTest) {
  10912. gl.enable(gl.DEPTH_TEST);
  10913. }
  10914. else {
  10915. gl.disable(gl.DEPTH_TEST);
  10916. }
  10917. this._isDepthTestDirty = false;
  10918. }
  10919. // Depth func
  10920. if (this._isDepthFuncDirty) {
  10921. gl.depthFunc(this.depthFunc);
  10922. this._isDepthFuncDirty = false;
  10923. }
  10924. // zOffset
  10925. if (this._isZOffsetDirty) {
  10926. if (this.zOffset) {
  10927. gl.enable(gl.POLYGON_OFFSET_FILL);
  10928. gl.polygonOffset(this.zOffset, 0);
  10929. }
  10930. else {
  10931. gl.disable(gl.POLYGON_OFFSET_FILL);
  10932. }
  10933. this._isZOffsetDirty = false;
  10934. }
  10935. // Front face
  10936. if (this._isFrontFaceDirty) {
  10937. gl.frontFace(this.frontFace);
  10938. this._isFrontFaceDirty = false;
  10939. }
  10940. };
  10941. return _DepthCullingState;
  10942. }());
  10943. BABYLON._DepthCullingState = _DepthCullingState;
  10944. })(BABYLON || (BABYLON = {}));
  10945. //# sourceMappingURL=babylon.depthCullingState.js.map
  10946. var BABYLON;
  10947. (function (BABYLON) {
  10948. /**
  10949. * @hidden
  10950. **/
  10951. var _StencilState = /** @class */ (function () {
  10952. function _StencilState() {
  10953. this._isStencilTestDirty = false;
  10954. this._isStencilMaskDirty = false;
  10955. this._isStencilFuncDirty = false;
  10956. this._isStencilOpDirty = false;
  10957. this.reset();
  10958. }
  10959. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10960. get: function () {
  10961. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10967. get: function () {
  10968. return this._stencilFunc;
  10969. },
  10970. set: function (value) {
  10971. if (this._stencilFunc === value) {
  10972. return;
  10973. }
  10974. this._stencilFunc = value;
  10975. this._isStencilFuncDirty = true;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10981. get: function () {
  10982. return this._stencilFuncRef;
  10983. },
  10984. set: function (value) {
  10985. if (this._stencilFuncRef === value) {
  10986. return;
  10987. }
  10988. this._stencilFuncRef = value;
  10989. this._isStencilFuncDirty = true;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10995. get: function () {
  10996. return this._stencilFuncMask;
  10997. },
  10998. set: function (value) {
  10999. if (this._stencilFuncMask === value) {
  11000. return;
  11001. }
  11002. this._stencilFuncMask = value;
  11003. this._isStencilFuncDirty = true;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11009. get: function () {
  11010. return this._stencilOpStencilFail;
  11011. },
  11012. set: function (value) {
  11013. if (this._stencilOpStencilFail === value) {
  11014. return;
  11015. }
  11016. this._stencilOpStencilFail = value;
  11017. this._isStencilOpDirty = true;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11023. get: function () {
  11024. return this._stencilOpDepthFail;
  11025. },
  11026. set: function (value) {
  11027. if (this._stencilOpDepthFail === value) {
  11028. return;
  11029. }
  11030. this._stencilOpDepthFail = value;
  11031. this._isStencilOpDirty = true;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11037. get: function () {
  11038. return this._stencilOpStencilDepthPass;
  11039. },
  11040. set: function (value) {
  11041. if (this._stencilOpStencilDepthPass === value) {
  11042. return;
  11043. }
  11044. this._stencilOpStencilDepthPass = value;
  11045. this._isStencilOpDirty = true;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11051. get: function () {
  11052. return this._stencilMask;
  11053. },
  11054. set: function (value) {
  11055. if (this._stencilMask === value) {
  11056. return;
  11057. }
  11058. this._stencilMask = value;
  11059. this._isStencilMaskDirty = true;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11065. get: function () {
  11066. return this._stencilTest;
  11067. },
  11068. set: function (value) {
  11069. if (this._stencilTest === value) {
  11070. return;
  11071. }
  11072. this._stencilTest = value;
  11073. this._isStencilTestDirty = true;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. _StencilState.prototype.reset = function () {
  11079. this._stencilTest = false;
  11080. this._stencilMask = 0xFF;
  11081. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11082. this._stencilFuncRef = 1;
  11083. this._stencilFuncMask = 0xFF;
  11084. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11085. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11086. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11087. this._isStencilTestDirty = true;
  11088. this._isStencilMaskDirty = true;
  11089. this._isStencilFuncDirty = true;
  11090. this._isStencilOpDirty = true;
  11091. };
  11092. _StencilState.prototype.apply = function (gl) {
  11093. if (!this.isDirty) {
  11094. return;
  11095. }
  11096. // Stencil test
  11097. if (this._isStencilTestDirty) {
  11098. if (this.stencilTest) {
  11099. gl.enable(gl.STENCIL_TEST);
  11100. }
  11101. else {
  11102. gl.disable(gl.STENCIL_TEST);
  11103. }
  11104. this._isStencilTestDirty = false;
  11105. }
  11106. // Stencil mask
  11107. if (this._isStencilMaskDirty) {
  11108. gl.stencilMask(this.stencilMask);
  11109. this._isStencilMaskDirty = false;
  11110. }
  11111. // Stencil func
  11112. if (this._isStencilFuncDirty) {
  11113. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11114. this._isStencilFuncDirty = false;
  11115. }
  11116. // Stencil op
  11117. if (this._isStencilOpDirty) {
  11118. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11119. this._isStencilOpDirty = false;
  11120. }
  11121. };
  11122. return _StencilState;
  11123. }());
  11124. BABYLON._StencilState = _StencilState;
  11125. })(BABYLON || (BABYLON = {}));
  11126. //# sourceMappingURL=babylon.stencilState.js.map
  11127. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11128. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11129. s = arguments[i];
  11130. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11131. t[p] = s[p];
  11132. }
  11133. return t;
  11134. };
  11135. var BABYLON;
  11136. (function (BABYLON) {
  11137. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11138. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11139. };
  11140. var compileRawShader = function (gl, source, type) {
  11141. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11142. gl.shaderSource(shader, source);
  11143. gl.compileShader(shader);
  11144. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11145. var log = gl.getShaderInfoLog(shader);
  11146. if (log) {
  11147. throw new Error(log);
  11148. }
  11149. }
  11150. if (!shader) {
  11151. throw new Error("Something went wrong while compile the shader.");
  11152. }
  11153. return shader;
  11154. };
  11155. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11156. var magFilter = gl.NEAREST;
  11157. var minFilter = gl.NEAREST;
  11158. switch (samplingMode) {
  11159. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11160. magFilter = gl.LINEAR;
  11161. if (generateMipMaps) {
  11162. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11163. }
  11164. else {
  11165. minFilter = gl.LINEAR;
  11166. }
  11167. break;
  11168. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11169. magFilter = gl.LINEAR;
  11170. if (generateMipMaps) {
  11171. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11172. }
  11173. else {
  11174. minFilter = gl.LINEAR;
  11175. }
  11176. break;
  11177. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11178. magFilter = gl.NEAREST;
  11179. if (generateMipMaps) {
  11180. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11181. }
  11182. else {
  11183. minFilter = gl.NEAREST;
  11184. }
  11185. break;
  11186. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11187. magFilter = gl.NEAREST;
  11188. if (generateMipMaps) {
  11189. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11190. }
  11191. else {
  11192. minFilter = gl.NEAREST;
  11193. }
  11194. break;
  11195. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11196. magFilter = gl.NEAREST;
  11197. if (generateMipMaps) {
  11198. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11199. }
  11200. else {
  11201. minFilter = gl.LINEAR;
  11202. }
  11203. break;
  11204. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11205. magFilter = gl.NEAREST;
  11206. if (generateMipMaps) {
  11207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11208. }
  11209. else {
  11210. minFilter = gl.LINEAR;
  11211. }
  11212. break;
  11213. case BABYLON.Texture.NEAREST_LINEAR:
  11214. magFilter = gl.NEAREST;
  11215. minFilter = gl.LINEAR;
  11216. break;
  11217. case BABYLON.Texture.NEAREST_NEAREST:
  11218. magFilter = gl.NEAREST;
  11219. minFilter = gl.NEAREST;
  11220. break;
  11221. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11222. magFilter = gl.LINEAR;
  11223. if (generateMipMaps) {
  11224. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11225. }
  11226. else {
  11227. minFilter = gl.NEAREST;
  11228. }
  11229. break;
  11230. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11231. magFilter = gl.LINEAR;
  11232. if (generateMipMaps) {
  11233. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11234. }
  11235. else {
  11236. minFilter = gl.NEAREST;
  11237. }
  11238. break;
  11239. case BABYLON.Texture.LINEAR_LINEAR:
  11240. magFilter = gl.LINEAR;
  11241. minFilter = gl.LINEAR;
  11242. break;
  11243. case BABYLON.Texture.LINEAR_NEAREST:
  11244. magFilter = gl.LINEAR;
  11245. minFilter = gl.NEAREST;
  11246. break;
  11247. }
  11248. return {
  11249. min: minFilter,
  11250. mag: magFilter
  11251. };
  11252. };
  11253. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11254. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11255. var img;
  11256. var onload = function () {
  11257. loadedImages[index] = img;
  11258. loadedImages._internalCount++;
  11259. if (scene) {
  11260. scene._removePendingData(img);
  11261. }
  11262. if (loadedImages._internalCount === 6) {
  11263. onfinish(loadedImages);
  11264. }
  11265. };
  11266. var onerror = function (message, exception) {
  11267. if (scene) {
  11268. scene._removePendingData(img);
  11269. }
  11270. if (onErrorCallBack) {
  11271. onErrorCallBack(message, exception);
  11272. }
  11273. };
  11274. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11275. if (scene) {
  11276. scene._addPendingData(img);
  11277. }
  11278. };
  11279. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11280. if (onError === void 0) { onError = null; }
  11281. var loadedImages = [];
  11282. loadedImages._internalCount = 0;
  11283. for (var index = 0; index < 6; index++) {
  11284. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11285. }
  11286. };
  11287. var BufferPointer = /** @class */ (function () {
  11288. function BufferPointer() {
  11289. }
  11290. return BufferPointer;
  11291. }());
  11292. /**
  11293. * Interface for attribute information associated with buffer instanciation
  11294. */
  11295. var InstancingAttributeInfo = /** @class */ (function () {
  11296. function InstancingAttributeInfo() {
  11297. }
  11298. return InstancingAttributeInfo;
  11299. }());
  11300. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11301. /**
  11302. * Define options used to create a render target texture
  11303. */
  11304. var RenderTargetCreationOptions = /** @class */ (function () {
  11305. function RenderTargetCreationOptions() {
  11306. }
  11307. return RenderTargetCreationOptions;
  11308. }());
  11309. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11310. /**
  11311. * Define options used to create a depth texture
  11312. */
  11313. var DepthTextureCreationOptions = /** @class */ (function () {
  11314. function DepthTextureCreationOptions() {
  11315. }
  11316. return DepthTextureCreationOptions;
  11317. }());
  11318. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11319. /**
  11320. * Class used to describe the capabilities of the engine relatively to the current browser
  11321. */
  11322. var EngineCapabilities = /** @class */ (function () {
  11323. function EngineCapabilities() {
  11324. }
  11325. return EngineCapabilities;
  11326. }());
  11327. BABYLON.EngineCapabilities = EngineCapabilities;
  11328. /**
  11329. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11330. */
  11331. var Engine = /** @class */ (function () {
  11332. /**
  11333. * Creates a new engine
  11334. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11335. * @param antialias defines enable antialiasing (default: false)
  11336. * @param options defines further options to be sent to the getContext() function
  11337. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11338. */
  11339. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11340. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11341. var _this = this;
  11342. // Public members
  11343. /**
  11344. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11345. */
  11346. this.forcePOTTextures = false;
  11347. /**
  11348. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11349. */
  11350. this.isFullscreen = false;
  11351. /**
  11352. * Gets a boolean indicating if the pointer is currently locked
  11353. */
  11354. this.isPointerLock = false;
  11355. /**
  11356. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11357. */
  11358. this.cullBackFaces = true;
  11359. /**
  11360. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11361. */
  11362. this.renderEvenInBackground = true;
  11363. /**
  11364. * Gets or sets a boolean indicating that cache can be kept between frames
  11365. */
  11366. this.preventCacheWipeBetweenFrames = false;
  11367. /**
  11368. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11369. **/
  11370. this.enableOfflineSupport = false;
  11371. /**
  11372. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11373. **/
  11374. this.disableManifestCheck = false;
  11375. /**
  11376. * Gets the list of created scenes
  11377. */
  11378. this.scenes = new Array();
  11379. /**
  11380. * Gets the list of created postprocesses
  11381. */
  11382. this.postProcesses = new Array();
  11383. // Observables
  11384. /**
  11385. * Observable event triggered each time the rendering canvas is resized
  11386. */
  11387. this.onResizeObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable event triggered each time the canvas loses focus
  11390. */
  11391. this.onCanvasBlurObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable event triggered each time the canvas gains focus
  11394. */
  11395. this.onCanvasFocusObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable event triggered each time the canvas receives pointerout event
  11398. */
  11399. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11400. /**
  11401. * Observable event triggered before each texture is initialized
  11402. */
  11403. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11404. //WebVR
  11405. this._vrDisplay = undefined;
  11406. this._vrSupported = false;
  11407. this._vrExclusivePointerMode = false;
  11408. // Uniform buffers list
  11409. /**
  11410. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11411. */
  11412. this.disableUniformBuffers = false;
  11413. /** @hidden */
  11414. this._uniformBuffers = new Array();
  11415. // Observables
  11416. /**
  11417. * Observable raised when the engine begins a new frame
  11418. */
  11419. this.onBeginFrameObservable = new BABYLON.Observable();
  11420. /**
  11421. * Observable raised when the engine ends the current frame
  11422. */
  11423. this.onEndFrameObservable = new BABYLON.Observable();
  11424. /**
  11425. * Observable raised when the engine is about to compile a shader
  11426. */
  11427. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11428. /**
  11429. * Observable raised when the engine has jsut compiled a shader
  11430. */
  11431. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11432. this._windowIsBackground = false;
  11433. this._webGLVersion = 1.0;
  11434. /** @hidden */
  11435. this._badOS = false;
  11436. /** @hidden */
  11437. this._badDesktopOS = false;
  11438. /**
  11439. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11440. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11441. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11442. */
  11443. this.disableTextureBindingOptimization = false;
  11444. /**
  11445. * Observable signaled when VR display mode changes
  11446. */
  11447. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11448. /**
  11449. * Observable signaled when VR request present is complete
  11450. */
  11451. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11452. /**
  11453. * Observable signaled when VR request present starts
  11454. */
  11455. this.onVRRequestPresentStart = new BABYLON.Observable();
  11456. this._colorWrite = true;
  11457. /** @hidden */
  11458. this._drawCalls = new BABYLON.PerfCounter();
  11459. /** @hidden */
  11460. this._textureCollisions = new BABYLON.PerfCounter();
  11461. this._renderingQueueLaunched = false;
  11462. this._activeRenderLoops = new Array();
  11463. // Deterministic lockstepMaxSteps
  11464. this._deterministicLockstep = false;
  11465. this._lockstepMaxSteps = 4;
  11466. // Lost context
  11467. /**
  11468. * Observable signaled when a context lost event is raised
  11469. */
  11470. this.onContextLostObservable = new BABYLON.Observable();
  11471. /**
  11472. * Observable signaled when a context restored event is raised
  11473. */
  11474. this.onContextRestoredObservable = new BABYLON.Observable();
  11475. this._contextWasLost = false;
  11476. this._doNotHandleContextLost = false;
  11477. // FPS
  11478. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11479. this._fps = 60;
  11480. this._deltaTime = 0;
  11481. /**
  11482. * Turn this value on if you want to pause FPS computation when in background
  11483. */
  11484. this.disablePerformanceMonitorInBackground = false;
  11485. // States
  11486. /** @hidden */
  11487. this._depthCullingState = new BABYLON._DepthCullingState();
  11488. /** @hidden */
  11489. this._stencilState = new BABYLON._StencilState();
  11490. /** @hidden */
  11491. this._alphaState = new BABYLON._AlphaState();
  11492. /** @hidden */
  11493. this._alphaMode = Engine.ALPHA_DISABLE;
  11494. // Cache
  11495. this._internalTexturesCache = new Array();
  11496. /** @hidden */
  11497. this._activeChannel = 0;
  11498. this._currentTextureChannel = -1;
  11499. /** @hidden */
  11500. this._boundTexturesCache = {};
  11501. this._compiledEffects = {};
  11502. this._vertexAttribArraysEnabled = [];
  11503. this._uintIndicesCurrentlySet = false;
  11504. this._currentBoundBuffer = new Array();
  11505. this._currentBufferPointers = new Array();
  11506. this._currentInstanceLocations = new Array();
  11507. this._currentInstanceBuffers = new Array();
  11508. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11509. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11510. this._vaoRecordInProgress = false;
  11511. this._mustWipeVertexAttributes = false;
  11512. this._nextFreeTextureSlots = new Array();
  11513. this._maxSimultaneousTextures = 0;
  11514. this._activeRequests = new Array();
  11515. // Hardware supported Compressed Textures
  11516. this._texturesSupported = new Array();
  11517. /**
  11518. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11519. */
  11520. this.premultipliedAlpha = true;
  11521. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11522. this._onVRFullScreenTriggered = function () {
  11523. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11524. //get the old size before we change
  11525. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11526. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11527. //get the width and height, change the render size
  11528. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11529. _this.setHardwareScalingLevel(1);
  11530. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11531. }
  11532. else {
  11533. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11534. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11535. }
  11536. };
  11537. this._unpackFlipYCached = null;
  11538. this._boundUniforms = {};
  11539. // Register promises
  11540. BABYLON.PromisePolyfill.Apply();
  11541. var canvas = null;
  11542. Engine.Instances.push(this);
  11543. if (!canvasOrContext) {
  11544. return;
  11545. }
  11546. options = options || {};
  11547. if (canvasOrContext.getContext) {
  11548. canvas = canvasOrContext;
  11549. this._renderingCanvas = canvas;
  11550. if (antialias != null) {
  11551. options.antialias = antialias;
  11552. }
  11553. if (options.deterministicLockstep === undefined) {
  11554. options.deterministicLockstep = false;
  11555. }
  11556. if (options.lockstepMaxSteps === undefined) {
  11557. options.lockstepMaxSteps = 4;
  11558. }
  11559. if (options.preserveDrawingBuffer === undefined) {
  11560. options.preserveDrawingBuffer = false;
  11561. }
  11562. if (options.audioEngine === undefined) {
  11563. options.audioEngine = true;
  11564. }
  11565. if (options.stencil === undefined) {
  11566. options.stencil = true;
  11567. }
  11568. if (options.premultipliedAlpha === false) {
  11569. this.premultipliedAlpha = false;
  11570. }
  11571. this._deterministicLockstep = options.deterministicLockstep;
  11572. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11573. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11574. // Exceptions
  11575. if (navigator && navigator.userAgent) {
  11576. var ua = navigator.userAgent;
  11577. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11578. var exception = _a[_i];
  11579. var key = exception.key;
  11580. var targets = exception.targets;
  11581. if (ua.indexOf(key) > -1) {
  11582. if (exception.capture && exception.captureConstraint) {
  11583. var capture = exception.capture;
  11584. var constraint = exception.captureConstraint;
  11585. var regex = new RegExp(capture);
  11586. var matches = regex.exec(ua);
  11587. if (matches && matches.length > 0) {
  11588. var capturedValue = parseInt(matches[matches.length - 1]);
  11589. if (capturedValue >= constraint) {
  11590. continue;
  11591. }
  11592. }
  11593. }
  11594. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11595. var target = targets_1[_b];
  11596. switch (target) {
  11597. case "uniformBuffer":
  11598. this.disableUniformBuffers = true;
  11599. break;
  11600. case "textureBindingOptimization":
  11601. this.disableTextureBindingOptimization = true;
  11602. break;
  11603. }
  11604. }
  11605. }
  11606. }
  11607. }
  11608. // GL
  11609. if (!options.disableWebGL2Support) {
  11610. try {
  11611. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11612. if (this._gl) {
  11613. this._webGLVersion = 2.0;
  11614. }
  11615. }
  11616. catch (e) {
  11617. // Do nothing
  11618. }
  11619. }
  11620. if (!this._gl) {
  11621. if (!canvas) {
  11622. throw new Error("The provided canvas is null or undefined.");
  11623. }
  11624. try {
  11625. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11626. }
  11627. catch (e) {
  11628. throw new Error("WebGL not supported");
  11629. }
  11630. }
  11631. if (!this._gl) {
  11632. throw new Error("WebGL not supported");
  11633. }
  11634. this._onCanvasFocus = function () {
  11635. _this.onCanvasFocusObservable.notifyObservers(_this);
  11636. };
  11637. this._onCanvasBlur = function () {
  11638. _this.onCanvasBlurObservable.notifyObservers(_this);
  11639. };
  11640. canvas.addEventListener("focus", this._onCanvasFocus);
  11641. canvas.addEventListener("blur", this._onCanvasBlur);
  11642. this._onBlur = function () {
  11643. if (_this.disablePerformanceMonitorInBackground) {
  11644. _this._performanceMonitor.disable();
  11645. }
  11646. _this._windowIsBackground = true;
  11647. };
  11648. this._onFocus = function () {
  11649. if (_this.disablePerformanceMonitorInBackground) {
  11650. _this._performanceMonitor.enable();
  11651. }
  11652. _this._windowIsBackground = false;
  11653. };
  11654. this._onCanvasPointerOut = function (ev) {
  11655. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11656. };
  11657. window.addEventListener("blur", this._onBlur);
  11658. window.addEventListener("focus", this._onFocus);
  11659. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11660. // Context lost
  11661. if (!this._doNotHandleContextLost) {
  11662. this._onContextLost = function (evt) {
  11663. evt.preventDefault();
  11664. _this._contextWasLost = true;
  11665. BABYLON.Tools.Warn("WebGL context lost.");
  11666. _this.onContextLostObservable.notifyObservers(_this);
  11667. };
  11668. this._onContextRestored = function (evt) {
  11669. // Adding a timeout to avoid race condition at browser level
  11670. setTimeout(function () {
  11671. // Rebuild gl context
  11672. _this._initGLContext();
  11673. // Rebuild effects
  11674. _this._rebuildEffects();
  11675. // Rebuild textures
  11676. _this._rebuildInternalTextures();
  11677. // Rebuild buffers
  11678. _this._rebuildBuffers();
  11679. // Cache
  11680. _this.wipeCaches(true);
  11681. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11682. _this.onContextRestoredObservable.notifyObservers(_this);
  11683. _this._contextWasLost = false;
  11684. }, 0);
  11685. };
  11686. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11687. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11688. }
  11689. }
  11690. else {
  11691. this._gl = canvasOrContext;
  11692. this._renderingCanvas = this._gl.canvas;
  11693. if (this._gl.renderbufferStorageMultisample) {
  11694. this._webGLVersion = 2.0;
  11695. }
  11696. options.stencil = this._gl.getContextAttributes().stencil;
  11697. }
  11698. // Viewport
  11699. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11700. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11701. this.resize();
  11702. this._isStencilEnable = options.stencil ? true : false;
  11703. this._initGLContext();
  11704. if (canvas) {
  11705. // Fullscreen
  11706. this._onFullscreenChange = function () {
  11707. if (document.fullscreen !== undefined) {
  11708. _this.isFullscreen = document.fullscreen;
  11709. }
  11710. else if (document.mozFullScreen !== undefined) {
  11711. _this.isFullscreen = document.mozFullScreen;
  11712. }
  11713. else if (document.webkitIsFullScreen !== undefined) {
  11714. _this.isFullscreen = document.webkitIsFullScreen;
  11715. }
  11716. else if (document.msIsFullScreen !== undefined) {
  11717. _this.isFullscreen = document.msIsFullScreen;
  11718. }
  11719. // Pointer lock
  11720. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11721. canvas.requestPointerLock = canvas.requestPointerLock ||
  11722. canvas.msRequestPointerLock ||
  11723. canvas.mozRequestPointerLock ||
  11724. canvas.webkitRequestPointerLock;
  11725. if (canvas.requestPointerLock) {
  11726. canvas.requestPointerLock();
  11727. }
  11728. }
  11729. };
  11730. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11731. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11732. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11733. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11734. // Pointer lock
  11735. this._onPointerLockChange = function () {
  11736. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11737. document.webkitPointerLockElement === canvas ||
  11738. document.msPointerLockElement === canvas ||
  11739. document.pointerLockElement === canvas);
  11740. };
  11741. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11742. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11743. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11744. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11745. this._onVRDisplayPointerRestricted = function () {
  11746. if (canvas) {
  11747. canvas.requestPointerLock();
  11748. }
  11749. };
  11750. this._onVRDisplayPointerUnrestricted = function () {
  11751. document.exitPointerLock();
  11752. };
  11753. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11754. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11755. }
  11756. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11757. Engine.audioEngine = new BABYLON.AudioEngine();
  11758. }
  11759. // Prepare buffer pointers
  11760. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11761. this._currentBufferPointers[i] = new BufferPointer();
  11762. }
  11763. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11764. // Load WebVR Devices
  11765. if (options.autoEnableWebVR) {
  11766. this.initWebVR();
  11767. }
  11768. // Detect if we are running on a faulty buggy OS.
  11769. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11770. // Detect if we are running on a faulty buggy desktop OS.
  11771. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11772. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11773. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11774. }
  11775. Object.defineProperty(Engine, "LastCreatedEngine", {
  11776. /**
  11777. * Gets the latest created engine
  11778. */
  11779. get: function () {
  11780. if (Engine.Instances.length === 0) {
  11781. return null;
  11782. }
  11783. return Engine.Instances[Engine.Instances.length - 1];
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "LastCreatedScene", {
  11789. /**
  11790. * Gets the latest created scene
  11791. */
  11792. get: function () {
  11793. var lastCreatedEngine = Engine.LastCreatedEngine;
  11794. if (!lastCreatedEngine) {
  11795. return null;
  11796. }
  11797. if (lastCreatedEngine.scenes.length === 0) {
  11798. return null;
  11799. }
  11800. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. /**
  11806. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11807. * @param flag defines which part of the materials must be marked as dirty
  11808. * @param predicate defines a predicate used to filter which materials should be affected
  11809. */
  11810. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11811. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11812. var engine = Engine.Instances[engineIndex];
  11813. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11814. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11815. }
  11816. }
  11817. };
  11818. Object.defineProperty(Engine, "NEVER", {
  11819. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11820. get: function () {
  11821. return Engine._NEVER;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "ALWAYS", {
  11827. /** 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 */
  11828. get: function () {
  11829. return Engine._ALWAYS;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "LESS", {
  11835. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11836. get: function () {
  11837. return Engine._LESS;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "EQUAL", {
  11843. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11844. get: function () {
  11845. return Engine._EQUAL;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "LEQUAL", {
  11851. /** 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 */
  11852. get: function () {
  11853. return Engine._LEQUAL;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "GREATER", {
  11859. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11860. get: function () {
  11861. return Engine._GREATER;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "GEQUAL", {
  11867. /** 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 */
  11868. get: function () {
  11869. return Engine._GEQUAL;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "NOTEQUAL", {
  11875. /** 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 */
  11876. get: function () {
  11877. return Engine._NOTEQUAL;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "KEEP", {
  11883. /** Passed to stencilOperation to specify that stencil value must be kept */
  11884. get: function () {
  11885. return Engine._KEEP;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "REPLACE", {
  11891. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11892. get: function () {
  11893. return Engine._REPLACE;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "INCR", {
  11899. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11900. get: function () {
  11901. return Engine._INCR;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "DECR", {
  11907. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11908. get: function () {
  11909. return Engine._DECR;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "INVERT", {
  11915. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11916. get: function () {
  11917. return Engine._INVERT;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "INCR_WRAP", {
  11923. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11924. get: function () {
  11925. return Engine._INCR_WRAP;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "DECR_WRAP", {
  11931. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11932. get: function () {
  11933. return Engine._DECR_WRAP;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11939. // Alpha
  11940. /** Defines that alpha blending is disabled */
  11941. get: function () {
  11942. return Engine._ALPHA_DISABLE;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11948. /** Defines that alpha blending to SRC + DEST */
  11949. get: function () {
  11950. return Engine._ALPHA_ONEONE;
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Engine, "ALPHA_ADD", {
  11956. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11957. get: function () {
  11958. return Engine._ALPHA_ADD;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11964. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11965. get: function () {
  11966. return Engine._ALPHA_COMBINE;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11972. /** Defines that alpha blending to DEST - SRC * DEST */
  11973. get: function () {
  11974. return Engine._ALPHA_SUBTRACT;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11980. /** Defines that alpha blending to SRC * DEST */
  11981. get: function () {
  11982. return Engine._ALPHA_MULTIPLY;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11988. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11989. get: function () {
  11990. return Engine._ALPHA_MAXIMIZED;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11996. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11997. get: function () {
  11998. return Engine._ALPHA_PREMULTIPLIED;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  12004. /**
  12005. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  12006. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  12007. */
  12008. get: function () {
  12009. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  12015. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  12016. get: function () {
  12017. return Engine._ALPHA_INTERPOLATE;
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  12023. /**
  12024. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  12025. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  12026. */
  12027. get: function () {
  12028. return Engine._ALPHA_SCREENMODE;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  12034. // Delays
  12035. /** Defines that the ressource is not delayed*/
  12036. get: function () {
  12037. return Engine._DELAYLOADSTATE_NONE;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  12043. /** Defines that the ressource was successfully delay loaded */
  12044. get: function () {
  12045. return Engine._DELAYLOADSTATE_LOADED;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12051. /** Defines that the ressource is currently delay loading */
  12052. get: function () {
  12053. return Engine._DELAYLOADSTATE_LOADING;
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12059. /** Defines that the ressource is delayed and has not started loading */
  12060. get: function () {
  12061. return Engine._DELAYLOADSTATE_NOTLOADED;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12067. /** ALPHA */
  12068. get: function () {
  12069. return Engine._TEXTUREFORMAT_ALPHA;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12075. /** LUMINANCE */
  12076. get: function () {
  12077. return Engine._TEXTUREFORMAT_LUMINANCE;
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12083. /**
  12084. * R
  12085. */
  12086. get: function () {
  12087. return Engine._TEXTUREFORMAT_R;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12093. /**
  12094. * RG
  12095. */
  12096. get: function () {
  12097. return Engine._TEXTUREFORMAT_RG;
  12098. },
  12099. enumerable: true,
  12100. configurable: true
  12101. });
  12102. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12103. /** LUMINANCE_ALPHA */
  12104. get: function () {
  12105. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12111. /** RGB */
  12112. get: function () {
  12113. return Engine._TEXTUREFORMAT_RGB;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12119. /** RGBA */
  12120. get: function () {
  12121. return Engine._TEXTUREFORMAT_RGBA;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12127. /** UNSIGNED_INT */
  12128. get: function () {
  12129. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12130. },
  12131. enumerable: true,
  12132. configurable: true
  12133. });
  12134. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12135. /** FLOAT */
  12136. get: function () {
  12137. return Engine._TEXTURETYPE_FLOAT;
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12143. /** HALF_FLOAT */
  12144. get: function () {
  12145. return Engine._TEXTURETYPE_HALF_FLOAT;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12151. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12152. get: function () {
  12153. return Engine._SCALEMODE_FLOOR;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12159. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12160. get: function () {
  12161. return Engine._SCALEMODE_NEAREST;
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12167. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12168. get: function () {
  12169. return Engine._SCALEMODE_CEILING;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Engine, "Version", {
  12175. /**
  12176. * Returns the current version of the framework
  12177. */
  12178. get: function () {
  12179. return "3.3.0-alpha.8";
  12180. },
  12181. enumerable: true,
  12182. configurable: true
  12183. });
  12184. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12185. /**
  12186. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12187. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12188. */
  12189. get: function () {
  12190. return this._vrExclusivePointerMode;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12196. /**
  12197. * Gets a boolean indicating that the engine supports uniform buffers
  12198. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12199. */
  12200. get: function () {
  12201. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12207. /**
  12208. * Gets a boolean indicating that only power of 2 textures are supported
  12209. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12210. */
  12211. get: function () {
  12212. return this._webGLVersion < 2 || this.forcePOTTextures;
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12218. /**
  12219. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12220. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12221. */
  12222. get: function () {
  12223. return this._doNotHandleContextLost;
  12224. },
  12225. set: function (value) {
  12226. this._doNotHandleContextLost = value;
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12232. /**
  12233. * Gets the performance monitor attached to this engine
  12234. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12235. */
  12236. get: function () {
  12237. return this._performanceMonitor;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12243. /**
  12244. * Gets the list of texture formats supported
  12245. */
  12246. get: function () {
  12247. return this._texturesSupported;
  12248. },
  12249. enumerable: true,
  12250. configurable: true
  12251. });
  12252. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12253. /**
  12254. * Gets the list of texture formats in use
  12255. */
  12256. get: function () {
  12257. return this._textureFormatInUse;
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(Engine.prototype, "currentViewport", {
  12263. /**
  12264. * Gets the current viewport
  12265. */
  12266. get: function () {
  12267. return this._cachedViewport;
  12268. },
  12269. enumerable: true,
  12270. configurable: true
  12271. });
  12272. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12273. /**
  12274. * Gets the default empty texture
  12275. */
  12276. get: function () {
  12277. if (!this._emptyTexture) {
  12278. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12279. }
  12280. return this._emptyTexture;
  12281. },
  12282. enumerable: true,
  12283. configurable: true
  12284. });
  12285. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12286. /**
  12287. * Gets the default empty 3D texture
  12288. */
  12289. get: function () {
  12290. if (!this._emptyTexture3D) {
  12291. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12292. }
  12293. return this._emptyTexture3D;
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12299. /**
  12300. * Gets the default empty cube texture
  12301. */
  12302. get: function () {
  12303. if (!this._emptyCubeTexture) {
  12304. var faceData = new Uint8Array(4);
  12305. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12306. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12307. }
  12308. return this._emptyCubeTexture;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Engine.prototype._rebuildInternalTextures = function () {
  12314. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12315. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12316. var internalTexture = currentState_1[_i];
  12317. internalTexture._rebuild();
  12318. }
  12319. };
  12320. Engine.prototype._rebuildEffects = function () {
  12321. for (var key in this._compiledEffects) {
  12322. var effect = this._compiledEffects[key];
  12323. effect._prepareEffect();
  12324. }
  12325. BABYLON.Effect.ResetCache();
  12326. };
  12327. Engine.prototype._rebuildBuffers = function () {
  12328. // Index / Vertex
  12329. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12330. var scene = _a[_i];
  12331. scene.resetCachedMaterial();
  12332. scene._rebuildGeometries();
  12333. scene._rebuildTextures();
  12334. }
  12335. // Uniforms
  12336. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12337. var uniformBuffer = _c[_b];
  12338. uniformBuffer._rebuild();
  12339. }
  12340. };
  12341. Engine.prototype._initGLContext = function () {
  12342. // Caps
  12343. this._caps = new EngineCapabilities();
  12344. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12345. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12346. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12347. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12348. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12349. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12350. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12351. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12352. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12353. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12354. // Infos
  12355. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12356. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12357. if (rendererInfo != null) {
  12358. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12359. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12360. }
  12361. if (!this._glVendor) {
  12362. this._glVendor = "Unknown vendor";
  12363. }
  12364. if (!this._glRenderer) {
  12365. this._glRenderer = "Unknown renderer";
  12366. }
  12367. // Constants
  12368. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12369. if (this._gl.RGBA16F !== 0x881A) {
  12370. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12371. }
  12372. if (this._gl.RGBA32F !== 0x8814) {
  12373. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12374. }
  12375. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12376. this._gl.DEPTH24_STENCIL8 = 35056;
  12377. }
  12378. // Extensions
  12379. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12380. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12381. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12382. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12383. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12384. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12385. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12386. 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');
  12387. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12388. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12389. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12390. this._caps.highPrecisionShaderSupported = true;
  12391. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12392. if (this._caps.timerQuery) {
  12393. if (this._webGLVersion === 1) {
  12394. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12395. }
  12396. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12397. }
  12398. // Checks if some of the format renders first to allow the use of webgl inspector.
  12399. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12400. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12401. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12402. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12403. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12404. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12405. if (this._webGLVersion > 1) {
  12406. this._gl.HALF_FLOAT_OES = 0x140B;
  12407. }
  12408. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12409. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12410. // Draw buffers
  12411. if (this._webGLVersion > 1) {
  12412. this._caps.drawBuffersExtension = true;
  12413. }
  12414. else {
  12415. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12416. if (drawBuffersExtension !== null) {
  12417. this._caps.drawBuffersExtension = true;
  12418. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12419. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12420. for (var i = 0; i < 16; i++) {
  12421. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12422. }
  12423. }
  12424. else {
  12425. this._caps.drawBuffersExtension = false;
  12426. }
  12427. }
  12428. // Depth Texture
  12429. if (this._webGLVersion > 1) {
  12430. this._caps.depthTextureExtension = true;
  12431. }
  12432. else {
  12433. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12434. if (depthTextureExtension != null) {
  12435. this._caps.depthTextureExtension = true;
  12436. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12437. }
  12438. }
  12439. // Vertex array object
  12440. if (this._webGLVersion > 1) {
  12441. this._caps.vertexArrayObject = true;
  12442. }
  12443. else {
  12444. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12445. if (vertexArrayObjectExtension != null) {
  12446. this._caps.vertexArrayObject = true;
  12447. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12448. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12449. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12450. }
  12451. else {
  12452. this._caps.vertexArrayObject = false;
  12453. }
  12454. }
  12455. // Instances count
  12456. if (this._webGLVersion > 1) {
  12457. this._caps.instancedArrays = true;
  12458. }
  12459. else {
  12460. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12461. if (instanceExtension != null) {
  12462. this._caps.instancedArrays = true;
  12463. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12464. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12465. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12466. }
  12467. else {
  12468. this._caps.instancedArrays = false;
  12469. }
  12470. }
  12471. // Intelligently add supported compressed formats in order to check for.
  12472. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12473. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12474. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12475. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12476. if (this._caps.astc)
  12477. this.texturesSupported.push('-astc.ktx');
  12478. if (this._caps.s3tc)
  12479. this.texturesSupported.push('-dxt.ktx');
  12480. if (this._caps.pvrtc)
  12481. this.texturesSupported.push('-pvrtc.ktx');
  12482. if (this._caps.etc2)
  12483. this.texturesSupported.push('-etc2.ktx');
  12484. if (this._caps.etc1)
  12485. this.texturesSupported.push('-etc1.ktx');
  12486. if (this._gl.getShaderPrecisionFormat) {
  12487. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12488. if (highp) {
  12489. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12490. }
  12491. }
  12492. // Depth buffer
  12493. this.setDepthBuffer(true);
  12494. this.setDepthFunctionToLessOrEqual();
  12495. this.setDepthWrite(true);
  12496. // Texture maps
  12497. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12498. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12499. this._nextFreeTextureSlots.push(slot);
  12500. }
  12501. };
  12502. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12503. /**
  12504. * Gets version of the current webGL context
  12505. */
  12506. get: function () {
  12507. return this._webGLVersion;
  12508. },
  12509. enumerable: true,
  12510. configurable: true
  12511. });
  12512. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12513. /**
  12514. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12515. */
  12516. get: function () {
  12517. return this._isStencilEnable;
  12518. },
  12519. enumerable: true,
  12520. configurable: true
  12521. });
  12522. Engine.prototype._prepareWorkingCanvas = function () {
  12523. if (this._workingCanvas) {
  12524. return;
  12525. }
  12526. this._workingCanvas = document.createElement("canvas");
  12527. var context = this._workingCanvas.getContext("2d");
  12528. if (context) {
  12529. this._workingContext = context;
  12530. }
  12531. };
  12532. /**
  12533. * Reset the texture cache to empty state
  12534. */
  12535. Engine.prototype.resetTextureCache = function () {
  12536. for (var key in this._boundTexturesCache) {
  12537. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12538. continue;
  12539. }
  12540. var boundTexture = this._boundTexturesCache[key];
  12541. if (boundTexture) {
  12542. this._removeDesignatedSlot(boundTexture);
  12543. }
  12544. this._boundTexturesCache[key] = null;
  12545. }
  12546. if (!this.disableTextureBindingOptimization) {
  12547. this._nextFreeTextureSlots = [];
  12548. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12549. this._nextFreeTextureSlots.push(slot);
  12550. }
  12551. }
  12552. this._currentTextureChannel = -1;
  12553. };
  12554. /**
  12555. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12556. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12557. * @returns true if engine is in deterministic lock step mode
  12558. */
  12559. Engine.prototype.isDeterministicLockStep = function () {
  12560. return this._deterministicLockstep;
  12561. };
  12562. /**
  12563. * Gets the max steps when engine is running in deterministic lock step
  12564. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12565. * @returns the max steps
  12566. */
  12567. Engine.prototype.getLockstepMaxSteps = function () {
  12568. return this._lockstepMaxSteps;
  12569. };
  12570. /**
  12571. * Gets an object containing information about the current webGL context
  12572. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12573. */
  12574. Engine.prototype.getGlInfo = function () {
  12575. return {
  12576. vendor: this._glVendor,
  12577. renderer: this._glRenderer,
  12578. version: this._glVersion
  12579. };
  12580. };
  12581. /**
  12582. * Gets current aspect ratio
  12583. * @param camera defines the camera to use to get the aspect ratio
  12584. * @param useScreen defines if screen size must be used (or the current render target if any)
  12585. * @returns a number defining the aspect ratio
  12586. */
  12587. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12588. if (useScreen === void 0) { useScreen = false; }
  12589. var viewport = camera.viewport;
  12590. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12591. };
  12592. /**
  12593. * Gets current screen aspect ratio
  12594. * @returns a number defining the aspect ratio
  12595. */
  12596. Engine.prototype.getScreenAspectRatio = function () {
  12597. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12598. };
  12599. /**
  12600. * Gets the current render width
  12601. * @param useScreen defines if screen size must be used (or the current render target if any)
  12602. * @returns a number defining the current render width
  12603. */
  12604. Engine.prototype.getRenderWidth = function (useScreen) {
  12605. if (useScreen === void 0) { useScreen = false; }
  12606. if (!useScreen && this._currentRenderTarget) {
  12607. return this._currentRenderTarget.width;
  12608. }
  12609. return this._gl.drawingBufferWidth;
  12610. };
  12611. /**
  12612. * Gets the current render height
  12613. * @param useScreen defines if screen size must be used (or the current render target if any)
  12614. * @returns a number defining the current render height
  12615. */
  12616. Engine.prototype.getRenderHeight = function (useScreen) {
  12617. if (useScreen === void 0) { useScreen = false; }
  12618. if (!useScreen && this._currentRenderTarget) {
  12619. return this._currentRenderTarget.height;
  12620. }
  12621. return this._gl.drawingBufferHeight;
  12622. };
  12623. /**
  12624. * Gets the HTML canvas attached with the current webGL context
  12625. * @returns a HTML canvas
  12626. */
  12627. Engine.prototype.getRenderingCanvas = function () {
  12628. return this._renderingCanvas;
  12629. };
  12630. /**
  12631. * Gets the client rect of the HTML canvas attached with the current webGL context
  12632. * @returns a client rectanglee
  12633. */
  12634. Engine.prototype.getRenderingCanvasClientRect = function () {
  12635. if (!this._renderingCanvas) {
  12636. return null;
  12637. }
  12638. return this._renderingCanvas.getBoundingClientRect();
  12639. };
  12640. /**
  12641. * Defines the hardware scaling level.
  12642. * By default the hardware scaling level is computed from the window device ratio.
  12643. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12644. * @param level defines the level to use
  12645. */
  12646. Engine.prototype.setHardwareScalingLevel = function (level) {
  12647. this._hardwareScalingLevel = level;
  12648. this.resize();
  12649. };
  12650. /**
  12651. * Gets the current hardware scaling level.
  12652. * By default the hardware scaling level is computed from the window device ratio.
  12653. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12654. * @returns a number indicating the current hardware scaling level
  12655. */
  12656. Engine.prototype.getHardwareScalingLevel = function () {
  12657. return this._hardwareScalingLevel;
  12658. };
  12659. /**
  12660. * Gets the list of loaded textures
  12661. * @returns an array containing all loaded textures
  12662. */
  12663. Engine.prototype.getLoadedTexturesCache = function () {
  12664. return this._internalTexturesCache;
  12665. };
  12666. /**
  12667. * Gets the object containing all engine capabilities
  12668. * @returns the EngineCapabilities object
  12669. */
  12670. Engine.prototype.getCaps = function () {
  12671. return this._caps;
  12672. };
  12673. Object.defineProperty(Engine.prototype, "drawCalls", {
  12674. /** @hidden */
  12675. get: function () {
  12676. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12677. return 0;
  12678. },
  12679. enumerable: true,
  12680. configurable: true
  12681. });
  12682. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12683. /** @hidden */
  12684. get: function () {
  12685. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12686. return null;
  12687. },
  12688. enumerable: true,
  12689. configurable: true
  12690. });
  12691. /**
  12692. * Gets the current depth function
  12693. * @returns a number defining the depth function
  12694. */
  12695. Engine.prototype.getDepthFunction = function () {
  12696. return this._depthCullingState.depthFunc;
  12697. };
  12698. /**
  12699. * Sets the current depth function
  12700. * @param depthFunc defines the function to use
  12701. */
  12702. Engine.prototype.setDepthFunction = function (depthFunc) {
  12703. this._depthCullingState.depthFunc = depthFunc;
  12704. };
  12705. /**
  12706. * Sets the current depth function to GREATER
  12707. */
  12708. Engine.prototype.setDepthFunctionToGreater = function () {
  12709. this._depthCullingState.depthFunc = this._gl.GREATER;
  12710. };
  12711. /**
  12712. * Sets the current depth function to GEQUAL
  12713. */
  12714. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12715. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12716. };
  12717. /**
  12718. * Sets the current depth function to LESS
  12719. */
  12720. Engine.prototype.setDepthFunctionToLess = function () {
  12721. this._depthCullingState.depthFunc = this._gl.LESS;
  12722. };
  12723. /**
  12724. * Sets the current depth function to LEQUAL
  12725. */
  12726. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12727. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12728. };
  12729. /**
  12730. * Gets a boolean indicating if stencil buffer is enabled
  12731. * @returns the current stencil buffer state
  12732. */
  12733. Engine.prototype.getStencilBuffer = function () {
  12734. return this._stencilState.stencilTest;
  12735. };
  12736. /**
  12737. * Enable or disable the stencil buffer
  12738. * @param enable defines if the stencil buffer must be enabled or disabled
  12739. */
  12740. Engine.prototype.setStencilBuffer = function (enable) {
  12741. this._stencilState.stencilTest = enable;
  12742. };
  12743. /**
  12744. * Gets the current stencil mask
  12745. * @returns a number defining the new stencil mask to use
  12746. */
  12747. Engine.prototype.getStencilMask = function () {
  12748. return this._stencilState.stencilMask;
  12749. };
  12750. /**
  12751. * Sets the current stencil mask
  12752. * @param mask defines the new stencil mask to use
  12753. */
  12754. Engine.prototype.setStencilMask = function (mask) {
  12755. this._stencilState.stencilMask = mask;
  12756. };
  12757. /**
  12758. * Gets the current stencil function
  12759. * @returns a number defining the stencil function to use
  12760. */
  12761. Engine.prototype.getStencilFunction = function () {
  12762. return this._stencilState.stencilFunc;
  12763. };
  12764. /**
  12765. * Gets the current stencil reference value
  12766. * @returns a number defining the stencil reference value to use
  12767. */
  12768. Engine.prototype.getStencilFunctionReference = function () {
  12769. return this._stencilState.stencilFuncRef;
  12770. };
  12771. /**
  12772. * Gets the current stencil mask
  12773. * @returns a number defining the stencil mask to use
  12774. */
  12775. Engine.prototype.getStencilFunctionMask = function () {
  12776. return this._stencilState.stencilFuncMask;
  12777. };
  12778. /**
  12779. * Sets the current stencil function
  12780. * @param stencilFunc defines the new stencil function to use
  12781. */
  12782. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12783. this._stencilState.stencilFunc = stencilFunc;
  12784. };
  12785. /**
  12786. * Sets the current stencil reference
  12787. * @param reference defines the new stencil reference to use
  12788. */
  12789. Engine.prototype.setStencilFunctionReference = function (reference) {
  12790. this._stencilState.stencilFuncRef = reference;
  12791. };
  12792. /**
  12793. * Sets the current stencil mask
  12794. * @param mask defines the new stencil mask to use
  12795. */
  12796. Engine.prototype.setStencilFunctionMask = function (mask) {
  12797. this._stencilState.stencilFuncMask = mask;
  12798. };
  12799. /**
  12800. * Gets the current stencil operation when stencil fails
  12801. * @returns a number defining stencil operation to use when stencil fails
  12802. */
  12803. Engine.prototype.getStencilOperationFail = function () {
  12804. return this._stencilState.stencilOpStencilFail;
  12805. };
  12806. /**
  12807. * Gets the current stencil operation when depth fails
  12808. * @returns a number defining stencil operation to use when depth fails
  12809. */
  12810. Engine.prototype.getStencilOperationDepthFail = function () {
  12811. return this._stencilState.stencilOpDepthFail;
  12812. };
  12813. /**
  12814. * Gets the current stencil operation when stencil passes
  12815. * @returns a number defining stencil operation to use when stencil passes
  12816. */
  12817. Engine.prototype.getStencilOperationPass = function () {
  12818. return this._stencilState.stencilOpStencilDepthPass;
  12819. };
  12820. /**
  12821. * Sets the stencil operation to use when stencil fails
  12822. * @param operation defines the stencil operation to use when stencil fails
  12823. */
  12824. Engine.prototype.setStencilOperationFail = function (operation) {
  12825. this._stencilState.stencilOpStencilFail = operation;
  12826. };
  12827. /**
  12828. * Sets the stencil operation to use when depth fails
  12829. * @param operation defines the stencil operation to use when depth fails
  12830. */
  12831. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12832. this._stencilState.stencilOpDepthFail = operation;
  12833. };
  12834. /**
  12835. * Sets the stencil operation to use when stencil passes
  12836. * @param operation defines the stencil operation to use when stencil passes
  12837. */
  12838. Engine.prototype.setStencilOperationPass = function (operation) {
  12839. this._stencilState.stencilOpStencilDepthPass = operation;
  12840. };
  12841. /**
  12842. * Sets a boolean indicating if the dithering state is enabled or disabled
  12843. * @param value defines the dithering state
  12844. */
  12845. Engine.prototype.setDitheringState = function (value) {
  12846. if (value) {
  12847. this._gl.enable(this._gl.DITHER);
  12848. }
  12849. else {
  12850. this._gl.disable(this._gl.DITHER);
  12851. }
  12852. };
  12853. /**
  12854. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12855. * @param value defines the rasterizer state
  12856. */
  12857. Engine.prototype.setRasterizerState = function (value) {
  12858. if (value) {
  12859. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12860. }
  12861. else {
  12862. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12863. }
  12864. };
  12865. /**
  12866. * stop executing a render loop function and remove it from the execution array
  12867. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12868. */
  12869. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12870. if (!renderFunction) {
  12871. this._activeRenderLoops = [];
  12872. return;
  12873. }
  12874. var index = this._activeRenderLoops.indexOf(renderFunction);
  12875. if (index >= 0) {
  12876. this._activeRenderLoops.splice(index, 1);
  12877. }
  12878. };
  12879. /** @hidden */
  12880. Engine.prototype._renderLoop = function () {
  12881. if (!this._contextWasLost) {
  12882. var shouldRender = true;
  12883. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12884. shouldRender = false;
  12885. }
  12886. if (shouldRender) {
  12887. // Start new frame
  12888. this.beginFrame();
  12889. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12890. var renderFunction = this._activeRenderLoops[index];
  12891. renderFunction();
  12892. }
  12893. // Present
  12894. this.endFrame();
  12895. }
  12896. }
  12897. if (this._activeRenderLoops.length > 0) {
  12898. // Register new frame
  12899. var requester = null;
  12900. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12901. requester = this._vrDisplay;
  12902. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12903. }
  12904. else {
  12905. this._renderingQueueLaunched = false;
  12906. }
  12907. };
  12908. /**
  12909. * Register and execute a render loop. The engine can have more than one render function
  12910. * @param renderFunction defines the function to continuously execute
  12911. */
  12912. Engine.prototype.runRenderLoop = function (renderFunction) {
  12913. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12914. return;
  12915. }
  12916. this._activeRenderLoops.push(renderFunction);
  12917. if (!this._renderingQueueLaunched) {
  12918. this._renderingQueueLaunched = true;
  12919. this._bindedRenderFunction = this._renderLoop.bind(this);
  12920. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12921. }
  12922. };
  12923. /**
  12924. * Toggle full screen mode
  12925. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12926. * @param options defines an option object to be sent to the requestFullscreen function
  12927. */
  12928. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12929. if (this.isFullscreen) {
  12930. BABYLON.Tools.ExitFullscreen();
  12931. }
  12932. else {
  12933. this._pointerLockRequested = requestPointerLock;
  12934. if (this._renderingCanvas) {
  12935. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12936. }
  12937. }
  12938. };
  12939. /**
  12940. * Clear the current render buffer or the current render target (if any is set up)
  12941. * @param color defines the color to use
  12942. * @param backBuffer defines if the back buffer must be cleared
  12943. * @param depth defines if the depth buffer must be cleared
  12944. * @param stencil defines if the stencil buffer must be cleared
  12945. */
  12946. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12947. if (stencil === void 0) { stencil = false; }
  12948. this.applyStates();
  12949. var mode = 0;
  12950. if (backBuffer && color) {
  12951. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12952. mode |= this._gl.COLOR_BUFFER_BIT;
  12953. }
  12954. if (depth) {
  12955. this._gl.clearDepth(1.0);
  12956. mode |= this._gl.DEPTH_BUFFER_BIT;
  12957. }
  12958. if (stencil) {
  12959. this._gl.clearStencil(0);
  12960. mode |= this._gl.STENCIL_BUFFER_BIT;
  12961. }
  12962. this._gl.clear(mode);
  12963. };
  12964. /**
  12965. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12966. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12967. * @param y defines the y-coordinate of the corner of the clear rectangle
  12968. * @param width defines the width of the clear rectangle
  12969. * @param height defines the height of the clear rectangle
  12970. * @param clearColor defines the clear color
  12971. */
  12972. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12973. var gl = this._gl;
  12974. // Save state
  12975. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12976. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12977. // Change state
  12978. gl.enable(gl.SCISSOR_TEST);
  12979. gl.scissor(x, y, width, height);
  12980. // Clear
  12981. this.clear(clearColor, true, true, true);
  12982. // Restore state
  12983. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12984. if (curScissor === true) {
  12985. gl.enable(gl.SCISSOR_TEST);
  12986. }
  12987. else {
  12988. gl.disable(gl.SCISSOR_TEST);
  12989. }
  12990. };
  12991. /** @hidden */
  12992. Engine.prototype._viewport = function (x, y, width, height) {
  12993. if (x !== this._viewportCached.x ||
  12994. y !== this._viewportCached.y ||
  12995. width !== this._viewportCached.z ||
  12996. height !== this._viewportCached.w) {
  12997. this._viewportCached.x = x;
  12998. this._viewportCached.y = y;
  12999. this._viewportCached.z = width;
  13000. this._viewportCached.w = height;
  13001. this._gl.viewport(x, y, width, height);
  13002. }
  13003. };
  13004. /**
  13005. * Set the WebGL's viewport
  13006. * @param viewport defines the viewport element to be used
  13007. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13008. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13009. */
  13010. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13011. var width = requiredWidth || this.getRenderWidth();
  13012. var height = requiredHeight || this.getRenderHeight();
  13013. var x = viewport.x || 0;
  13014. var y = viewport.y || 0;
  13015. this._cachedViewport = viewport;
  13016. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13017. };
  13018. /**
  13019. * Directly set the WebGL Viewport
  13020. * @param x defines the x coordinate of the viewport (in screen space)
  13021. * @param y defines the y coordinate of the viewport (in screen space)
  13022. * @param width defines the width of the viewport (in screen space)
  13023. * @param height defines the height of the viewport (in screen space)
  13024. * @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
  13025. */
  13026. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13027. var currentViewport = this._cachedViewport;
  13028. this._cachedViewport = null;
  13029. this._viewport(x, y, width, height);
  13030. return currentViewport;
  13031. };
  13032. /**
  13033. * Begin a new frame
  13034. */
  13035. Engine.prototype.beginFrame = function () {
  13036. this.onBeginFrameObservable.notifyObservers(this);
  13037. this._measureFps();
  13038. };
  13039. /**
  13040. * Enf the current frame
  13041. */
  13042. Engine.prototype.endFrame = function () {
  13043. // Force a flush in case we are using a bad OS.
  13044. if (this._badOS) {
  13045. this.flushFramebuffer();
  13046. }
  13047. // Submit frame to the vr device, if enabled
  13048. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13049. // TODO: We should only submit the frame if we read frameData successfully.
  13050. this._vrDisplay.submitFrame();
  13051. }
  13052. this.onEndFrameObservable.notifyObservers(this);
  13053. };
  13054. /**
  13055. * Resize the view according to the canvas' size
  13056. */
  13057. Engine.prototype.resize = function () {
  13058. // We're not resizing the size of the canvas while in VR mode & presenting
  13059. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13060. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13061. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13062. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13063. }
  13064. };
  13065. /**
  13066. * Force a specific size of the canvas
  13067. * @param width defines the new canvas' width
  13068. * @param height defines the new canvas' height
  13069. */
  13070. Engine.prototype.setSize = function (width, height) {
  13071. if (!this._renderingCanvas) {
  13072. return;
  13073. }
  13074. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13075. return;
  13076. }
  13077. this._renderingCanvas.width = width;
  13078. this._renderingCanvas.height = height;
  13079. for (var index = 0; index < this.scenes.length; index++) {
  13080. var scene = this.scenes[index];
  13081. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13082. var cam = scene.cameras[camIndex];
  13083. cam._currentRenderId = 0;
  13084. }
  13085. }
  13086. if (this.onResizeObservable.hasObservers) {
  13087. this.onResizeObservable.notifyObservers(this);
  13088. }
  13089. };
  13090. // WebVR functions
  13091. /**
  13092. * Gets a boolean indicating if a webVR device was detected
  13093. * @returns true if a webVR device was detected
  13094. */
  13095. Engine.prototype.isVRDevicePresent = function () {
  13096. return !!this._vrDisplay;
  13097. };
  13098. /**
  13099. * Gets the current webVR device
  13100. * @returns the current webVR device (or null)
  13101. */
  13102. Engine.prototype.getVRDevice = function () {
  13103. return this._vrDisplay;
  13104. };
  13105. /**
  13106. * Initializes a webVR display and starts listening to display change events
  13107. * The onVRDisplayChangedObservable will be notified upon these changes
  13108. * @returns The onVRDisplayChangedObservable
  13109. */
  13110. Engine.prototype.initWebVR = function () {
  13111. this.initWebVRAsync();
  13112. return this.onVRDisplayChangedObservable;
  13113. };
  13114. /**
  13115. * Initializes a webVR display and starts listening to display change events
  13116. * The onVRDisplayChangedObservable will be notified upon these changes
  13117. * @returns A promise containing a VRDisplay and if vr is supported
  13118. */
  13119. Engine.prototype.initWebVRAsync = function () {
  13120. var _this = this;
  13121. var notifyObservers = function () {
  13122. var eventArgs = {
  13123. vrDisplay: _this._vrDisplay,
  13124. vrSupported: _this._vrSupported
  13125. };
  13126. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13127. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13128. };
  13129. if (!this._onVrDisplayConnect) {
  13130. this._onVrDisplayConnect = function (event) {
  13131. _this._vrDisplay = event.display;
  13132. notifyObservers();
  13133. };
  13134. this._onVrDisplayDisconnect = function () {
  13135. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13136. _this._vrDisplay = undefined;
  13137. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13138. notifyObservers();
  13139. };
  13140. this._onVrDisplayPresentChange = function () {
  13141. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13142. };
  13143. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13144. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13145. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13146. }
  13147. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13148. this._webVRInitPromise.then(notifyObservers);
  13149. return this._webVRInitPromise;
  13150. };
  13151. /**
  13152. * Call this function to switch to webVR mode
  13153. * Will do nothing if webVR is not supported or if there is no webVR device
  13154. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13155. */
  13156. Engine.prototype.enableVR = function () {
  13157. var _this = this;
  13158. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13159. var onResolved = function () {
  13160. _this.onVRRequestPresentComplete.notifyObservers(true);
  13161. _this._onVRFullScreenTriggered();
  13162. };
  13163. var onRejected = function () {
  13164. _this.onVRRequestPresentComplete.notifyObservers(false);
  13165. };
  13166. this.onVRRequestPresentStart.notifyObservers(this);
  13167. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13168. }
  13169. };
  13170. /**
  13171. * Call this function to leave webVR mode
  13172. * Will do nothing if webVR is not supported or if there is no webVR device
  13173. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13174. */
  13175. Engine.prototype.disableVR = function () {
  13176. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13177. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13178. }
  13179. };
  13180. Engine.prototype._getVRDisplaysAsync = function () {
  13181. var _this = this;
  13182. return new Promise(function (res, rej) {
  13183. if (navigator.getVRDisplays) {
  13184. navigator.getVRDisplays().then(function (devices) {
  13185. _this._vrSupported = true;
  13186. // note that devices may actually be an empty array. This is fine;
  13187. // we expect this._vrDisplay to be undefined in this case.
  13188. _this._vrDisplay = devices[0];
  13189. res({
  13190. vrDisplay: _this._vrDisplay,
  13191. vrSupported: _this._vrSupported
  13192. });
  13193. });
  13194. }
  13195. else {
  13196. _this._vrDisplay = undefined;
  13197. _this._vrSupported = false;
  13198. res({
  13199. vrDisplay: _this._vrDisplay,
  13200. vrSupported: _this._vrSupported
  13201. });
  13202. }
  13203. });
  13204. };
  13205. /**
  13206. * Binds the frame buffer to the specified texture.
  13207. * @param texture The texture to render to or null for the default canvas
  13208. * @param faceIndex The face of the texture to render to in case of cube texture
  13209. * @param requiredWidth The width of the target to render to
  13210. * @param requiredHeight The height of the target to render to
  13211. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13212. * @param depthStencilTexture The depth stencil texture to use to render
  13213. * @param lodLevel defines le lod level to bind to the frame buffer
  13214. */
  13215. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13216. if (lodLevel === void 0) { lodLevel = 0; }
  13217. if (this._currentRenderTarget) {
  13218. this.unBindFramebuffer(this._currentRenderTarget);
  13219. }
  13220. this._currentRenderTarget = texture;
  13221. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13222. var gl = this._gl;
  13223. if (texture.isCube) {
  13224. if (faceIndex === undefined) {
  13225. faceIndex = 0;
  13226. }
  13227. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13228. if (depthStencilTexture) {
  13229. if (depthStencilTexture._generateStencilBuffer) {
  13230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13231. }
  13232. else {
  13233. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13234. }
  13235. }
  13236. }
  13237. if (this._cachedViewport && !forceFullscreenViewport) {
  13238. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13239. }
  13240. else {
  13241. if (!requiredWidth) {
  13242. requiredWidth = texture.width;
  13243. if (lodLevel) {
  13244. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13245. }
  13246. }
  13247. if (!requiredHeight) {
  13248. requiredHeight = texture.height;
  13249. if (lodLevel) {
  13250. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13251. }
  13252. }
  13253. this._viewport(0, 0, requiredWidth, requiredHeight);
  13254. }
  13255. this.wipeCaches();
  13256. };
  13257. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13258. if (this._currentFramebuffer !== framebuffer) {
  13259. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13260. this._currentFramebuffer = framebuffer;
  13261. }
  13262. };
  13263. /**
  13264. * Unbind the current render target texture from the webGL context
  13265. * @param texture defines the render target texture to unbind
  13266. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13267. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13268. */
  13269. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13270. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13271. this._currentRenderTarget = null;
  13272. // If MSAA, we need to bitblt back to main texture
  13273. var gl = this._gl;
  13274. if (texture._MSAAFramebuffer) {
  13275. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13276. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13277. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13278. }
  13279. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13280. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13281. gl.generateMipmap(gl.TEXTURE_2D);
  13282. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13283. }
  13284. if (onBeforeUnbind) {
  13285. if (texture._MSAAFramebuffer) {
  13286. // Bind the correct framebuffer
  13287. this.bindUnboundFramebuffer(texture._framebuffer);
  13288. }
  13289. onBeforeUnbind();
  13290. }
  13291. this.bindUnboundFramebuffer(null);
  13292. };
  13293. /**
  13294. * Unbind a list of render target textures from the webGL context
  13295. * This is used only when drawBuffer extension or webGL2 are active
  13296. * @param textures defines the render target textures to unbind
  13297. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13298. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13299. */
  13300. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13301. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13302. this._currentRenderTarget = null;
  13303. // If MSAA, we need to bitblt back to main texture
  13304. var gl = this._gl;
  13305. if (textures[0]._MSAAFramebuffer) {
  13306. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13307. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13308. var attachments = textures[0]._attachments;
  13309. if (!attachments) {
  13310. attachments = new Array(textures.length);
  13311. textures[0]._attachments = attachments;
  13312. }
  13313. for (var i = 0; i < textures.length; i++) {
  13314. var texture = textures[i];
  13315. for (var j = 0; j < attachments.length; j++) {
  13316. attachments[j] = gl.NONE;
  13317. }
  13318. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13319. gl.readBuffer(attachments[i]);
  13320. gl.drawBuffers(attachments);
  13321. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13322. }
  13323. for (var i = 0; i < attachments.length; i++) {
  13324. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13325. }
  13326. gl.drawBuffers(attachments);
  13327. }
  13328. for (var i = 0; i < textures.length; i++) {
  13329. var texture = textures[i];
  13330. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13331. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13332. gl.generateMipmap(gl.TEXTURE_2D);
  13333. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13334. }
  13335. }
  13336. if (onBeforeUnbind) {
  13337. if (textures[0]._MSAAFramebuffer) {
  13338. // Bind the correct framebuffer
  13339. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13340. }
  13341. onBeforeUnbind();
  13342. }
  13343. this.bindUnboundFramebuffer(null);
  13344. };
  13345. /**
  13346. * Force the mipmap generation for the given render target texture
  13347. * @param texture defines the render target texture to use
  13348. */
  13349. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13350. if (texture.generateMipMaps) {
  13351. var gl = this._gl;
  13352. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13353. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13354. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13355. }
  13356. };
  13357. /**
  13358. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13359. */
  13360. Engine.prototype.flushFramebuffer = function () {
  13361. this._gl.flush();
  13362. };
  13363. /**
  13364. * Unbind the current render target and bind the default framebuffer
  13365. */
  13366. Engine.prototype.restoreDefaultFramebuffer = function () {
  13367. if (this._currentRenderTarget) {
  13368. this.unBindFramebuffer(this._currentRenderTarget);
  13369. }
  13370. else {
  13371. this.bindUnboundFramebuffer(null);
  13372. }
  13373. if (this._cachedViewport) {
  13374. this.setViewport(this._cachedViewport);
  13375. }
  13376. this.wipeCaches();
  13377. };
  13378. // UBOs
  13379. /**
  13380. * Create an uniform buffer
  13381. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13382. * @param elements defines the content of the uniform buffer
  13383. * @returns the webGL uniform buffer
  13384. */
  13385. Engine.prototype.createUniformBuffer = function (elements) {
  13386. var ubo = this._gl.createBuffer();
  13387. if (!ubo) {
  13388. throw new Error("Unable to create uniform buffer");
  13389. }
  13390. this.bindUniformBuffer(ubo);
  13391. if (elements instanceof Float32Array) {
  13392. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13393. }
  13394. else {
  13395. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13396. }
  13397. this.bindUniformBuffer(null);
  13398. ubo.references = 1;
  13399. return ubo;
  13400. };
  13401. /**
  13402. * Create a dynamic uniform buffer
  13403. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13404. * @param elements defines the content of the uniform buffer
  13405. * @returns the webGL uniform buffer
  13406. */
  13407. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13408. var ubo = this._gl.createBuffer();
  13409. if (!ubo) {
  13410. throw new Error("Unable to create dynamic uniform buffer");
  13411. }
  13412. this.bindUniformBuffer(ubo);
  13413. if (elements instanceof Float32Array) {
  13414. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13415. }
  13416. else {
  13417. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13418. }
  13419. this.bindUniformBuffer(null);
  13420. ubo.references = 1;
  13421. return ubo;
  13422. };
  13423. /**
  13424. * Update an existing uniform buffer
  13425. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13426. * @param uniformBuffer defines the target uniform buffer
  13427. * @param elements defines the content to update
  13428. * @param offset defines the offset in the uniform buffer where update should start
  13429. * @param count defines the size of the data to update
  13430. */
  13431. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13432. this.bindUniformBuffer(uniformBuffer);
  13433. if (offset === undefined) {
  13434. offset = 0;
  13435. }
  13436. if (count === undefined) {
  13437. if (elements instanceof Float32Array) {
  13438. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13439. }
  13440. else {
  13441. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13442. }
  13443. }
  13444. else {
  13445. if (elements instanceof Float32Array) {
  13446. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13447. }
  13448. else {
  13449. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13450. }
  13451. }
  13452. this.bindUniformBuffer(null);
  13453. };
  13454. // VBOs
  13455. Engine.prototype._resetVertexBufferBinding = function () {
  13456. this.bindArrayBuffer(null);
  13457. this._cachedVertexBuffers = null;
  13458. };
  13459. /**
  13460. * Creates a vertex buffer
  13461. * @param data the data for the vertex buffer
  13462. * @returns the new WebGL static buffer
  13463. */
  13464. Engine.prototype.createVertexBuffer = function (data) {
  13465. var vbo = this._gl.createBuffer();
  13466. if (!vbo) {
  13467. throw new Error("Unable to create vertex buffer");
  13468. }
  13469. this.bindArrayBuffer(vbo);
  13470. if (data instanceof Array) {
  13471. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13472. }
  13473. else {
  13474. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13475. }
  13476. this._resetVertexBufferBinding();
  13477. vbo.references = 1;
  13478. return vbo;
  13479. };
  13480. /**
  13481. * Creates a dynamic vertex buffer
  13482. * @param data the data for the dynamic vertex buffer
  13483. * @returns the new WebGL dynamic buffer
  13484. */
  13485. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13486. var vbo = this._gl.createBuffer();
  13487. if (!vbo) {
  13488. throw new Error("Unable to create dynamic vertex buffer");
  13489. }
  13490. this.bindArrayBuffer(vbo);
  13491. if (data instanceof Array) {
  13492. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13493. }
  13494. else {
  13495. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13496. }
  13497. this._resetVertexBufferBinding();
  13498. vbo.references = 1;
  13499. return vbo;
  13500. };
  13501. /**
  13502. * Update a dynamic index buffer
  13503. * @param indexBuffer defines the target index buffer
  13504. * @param indices defines the data to update
  13505. * @param offset defines the offset in the target index buffer where update should start
  13506. */
  13507. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13508. if (offset === void 0) { offset = 0; }
  13509. // Force cache update
  13510. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13511. this.bindIndexBuffer(indexBuffer);
  13512. var arrayBuffer;
  13513. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13514. arrayBuffer = indices;
  13515. }
  13516. else {
  13517. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13518. }
  13519. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13520. this._resetIndexBufferBinding();
  13521. };
  13522. /**
  13523. * Updates a dynamic vertex buffer.
  13524. * @param vertexBuffer the vertex buffer to update
  13525. * @param data the data used to update the vertex buffer
  13526. * @param byteOffset the byte offset of the data
  13527. * @param byteLength the byte length of the data
  13528. */
  13529. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13530. this.bindArrayBuffer(vertexBuffer);
  13531. if (byteOffset === undefined) {
  13532. byteOffset = 0;
  13533. }
  13534. if (byteLength === undefined) {
  13535. if (data instanceof Array) {
  13536. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13537. }
  13538. else {
  13539. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13540. }
  13541. }
  13542. else {
  13543. if (data instanceof Array) {
  13544. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13545. }
  13546. else {
  13547. if (data instanceof ArrayBuffer) {
  13548. data = new Uint8Array(data, byteOffset, byteLength);
  13549. }
  13550. else {
  13551. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13552. }
  13553. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13554. }
  13555. }
  13556. this._resetVertexBufferBinding();
  13557. };
  13558. Engine.prototype._resetIndexBufferBinding = function () {
  13559. this.bindIndexBuffer(null);
  13560. this._cachedIndexBuffer = null;
  13561. };
  13562. /**
  13563. * Creates a new index buffer
  13564. * @param indices defines the content of the index buffer
  13565. * @param updatable defines if the index buffer must be updatable
  13566. * @returns a new webGL buffer
  13567. */
  13568. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13569. var vbo = this._gl.createBuffer();
  13570. if (!vbo) {
  13571. throw new Error("Unable to create index buffer");
  13572. }
  13573. this.bindIndexBuffer(vbo);
  13574. // Check for 32 bits indices
  13575. var arrayBuffer;
  13576. var need32Bits = false;
  13577. if (indices instanceof Uint16Array) {
  13578. arrayBuffer = indices;
  13579. }
  13580. else {
  13581. //check 32 bit support
  13582. if (this._caps.uintIndices) {
  13583. if (indices instanceof Uint32Array) {
  13584. arrayBuffer = indices;
  13585. need32Bits = true;
  13586. }
  13587. else {
  13588. //number[] or Int32Array, check if 32 bit is necessary
  13589. for (var index = 0; index < indices.length; index++) {
  13590. if (indices[index] > 65535) {
  13591. need32Bits = true;
  13592. break;
  13593. }
  13594. }
  13595. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13596. }
  13597. }
  13598. else {
  13599. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13600. arrayBuffer = new Uint16Array(indices);
  13601. }
  13602. }
  13603. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13604. this._resetIndexBufferBinding();
  13605. vbo.references = 1;
  13606. vbo.is32Bits = need32Bits;
  13607. return vbo;
  13608. };
  13609. /**
  13610. * Bind a webGL buffer to the webGL context
  13611. * @param buffer defines the buffer to bind
  13612. */
  13613. Engine.prototype.bindArrayBuffer = function (buffer) {
  13614. if (!this._vaoRecordInProgress) {
  13615. this._unbindVertexArrayObject();
  13616. }
  13617. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13618. };
  13619. /**
  13620. * Bind an uniform buffer to the current webGL context
  13621. * @param buffer defines the buffer to bind
  13622. */
  13623. Engine.prototype.bindUniformBuffer = function (buffer) {
  13624. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13625. };
  13626. /**
  13627. * Bind a buffer to the current webGL context at a given location
  13628. * @param buffer defines the buffer to bind
  13629. * @param location defines the index where to bind the buffer
  13630. */
  13631. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13632. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13633. };
  13634. /**
  13635. * Bind a specific block at a given index in a specific shader program
  13636. * @param shaderProgram defines the shader program
  13637. * @param blockName defines the block name
  13638. * @param index defines the index where to bind the block
  13639. */
  13640. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13641. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13642. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13643. };
  13644. ;
  13645. Engine.prototype.bindIndexBuffer = function (buffer) {
  13646. if (!this._vaoRecordInProgress) {
  13647. this._unbindVertexArrayObject();
  13648. }
  13649. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13650. };
  13651. Engine.prototype.bindBuffer = function (buffer, target) {
  13652. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13653. this._gl.bindBuffer(target, buffer);
  13654. this._currentBoundBuffer[target] = buffer;
  13655. }
  13656. };
  13657. /**
  13658. * update the bound buffer with the given data
  13659. * @param data defines the data to update
  13660. */
  13661. Engine.prototype.updateArrayBuffer = function (data) {
  13662. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13663. };
  13664. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13665. var pointer = this._currentBufferPointers[indx];
  13666. var changed = false;
  13667. if (!pointer.active) {
  13668. changed = true;
  13669. pointer.active = true;
  13670. pointer.index = indx;
  13671. pointer.size = size;
  13672. pointer.type = type;
  13673. pointer.normalized = normalized;
  13674. pointer.stride = stride;
  13675. pointer.offset = offset;
  13676. pointer.buffer = buffer;
  13677. }
  13678. else {
  13679. if (pointer.buffer !== buffer) {
  13680. pointer.buffer = buffer;
  13681. changed = true;
  13682. }
  13683. if (pointer.size !== size) {
  13684. pointer.size = size;
  13685. changed = true;
  13686. }
  13687. if (pointer.type !== type) {
  13688. pointer.type = type;
  13689. changed = true;
  13690. }
  13691. if (pointer.normalized !== normalized) {
  13692. pointer.normalized = normalized;
  13693. changed = true;
  13694. }
  13695. if (pointer.stride !== stride) {
  13696. pointer.stride = stride;
  13697. changed = true;
  13698. }
  13699. if (pointer.offset !== offset) {
  13700. pointer.offset = offset;
  13701. changed = true;
  13702. }
  13703. }
  13704. if (changed || this._vaoRecordInProgress) {
  13705. this.bindArrayBuffer(buffer);
  13706. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13707. }
  13708. };
  13709. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13710. if (indexBuffer == null) {
  13711. return;
  13712. }
  13713. if (this._cachedIndexBuffer !== indexBuffer) {
  13714. this._cachedIndexBuffer = indexBuffer;
  13715. this.bindIndexBuffer(indexBuffer);
  13716. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13717. }
  13718. };
  13719. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13720. var attributes = effect.getAttributesNames();
  13721. if (!this._vaoRecordInProgress) {
  13722. this._unbindVertexArrayObject();
  13723. }
  13724. this.unbindAllAttributes();
  13725. for (var index = 0; index < attributes.length; index++) {
  13726. var order = effect.getAttributeLocation(index);
  13727. if (order >= 0) {
  13728. var vertexBuffer = vertexBuffers[attributes[index]];
  13729. if (!vertexBuffer) {
  13730. continue;
  13731. }
  13732. this._gl.enableVertexAttribArray(order);
  13733. if (!this._vaoRecordInProgress) {
  13734. this._vertexAttribArraysEnabled[order] = true;
  13735. }
  13736. var buffer = vertexBuffer.getBuffer();
  13737. if (buffer) {
  13738. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13739. if (vertexBuffer.getIsInstanced()) {
  13740. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13741. if (!this._vaoRecordInProgress) {
  13742. this._currentInstanceLocations.push(order);
  13743. this._currentInstanceBuffers.push(buffer);
  13744. }
  13745. }
  13746. }
  13747. }
  13748. }
  13749. };
  13750. /**
  13751. * Records a vertex array object
  13752. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13753. * @param vertexBuffers defines the list of vertex buffers to store
  13754. * @param indexBuffer defines the index buffer to store
  13755. * @param effect defines the effect to store
  13756. * @returns the new vertex array object
  13757. */
  13758. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13759. var vao = this._gl.createVertexArray();
  13760. this._vaoRecordInProgress = true;
  13761. this._gl.bindVertexArray(vao);
  13762. this._mustWipeVertexAttributes = true;
  13763. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13764. this.bindIndexBuffer(indexBuffer);
  13765. this._vaoRecordInProgress = false;
  13766. this._gl.bindVertexArray(null);
  13767. return vao;
  13768. };
  13769. /**
  13770. * Bind a specific vertex array object
  13771. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13772. * @param vertexArrayObject defines the vertex array object to bind
  13773. * @param indexBuffer defines the index buffer to bind
  13774. */
  13775. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13776. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13777. this._cachedVertexArrayObject = vertexArrayObject;
  13778. this._gl.bindVertexArray(vertexArrayObject);
  13779. this._cachedVertexBuffers = null;
  13780. this._cachedIndexBuffer = null;
  13781. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13782. this._mustWipeVertexAttributes = true;
  13783. }
  13784. };
  13785. /**
  13786. * Bind webGl buffers directly to the webGL context
  13787. * @param vertexBuffer defines the vertex buffer to bind
  13788. * @param indexBuffer defines the index buffer to bind
  13789. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13790. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13791. * @param effect defines the effect associated with the vertex buffer
  13792. */
  13793. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13794. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13795. this._cachedVertexBuffers = vertexBuffer;
  13796. this._cachedEffectForVertexBuffers = effect;
  13797. var attributesCount = effect.getAttributesCount();
  13798. this._unbindVertexArrayObject();
  13799. this.unbindAllAttributes();
  13800. var offset = 0;
  13801. for (var index = 0; index < attributesCount; index++) {
  13802. if (index < vertexDeclaration.length) {
  13803. var order = effect.getAttributeLocation(index);
  13804. if (order >= 0) {
  13805. this._gl.enableVertexAttribArray(order);
  13806. this._vertexAttribArraysEnabled[order] = true;
  13807. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13808. }
  13809. offset += vertexDeclaration[index] * 4;
  13810. }
  13811. }
  13812. }
  13813. this._bindIndexBufferWithCache(indexBuffer);
  13814. };
  13815. Engine.prototype._unbindVertexArrayObject = function () {
  13816. if (!this._cachedVertexArrayObject) {
  13817. return;
  13818. }
  13819. this._cachedVertexArrayObject = null;
  13820. this._gl.bindVertexArray(null);
  13821. };
  13822. /**
  13823. * Bind a list of vertex buffers to the webGL context
  13824. * @param vertexBuffers defines the list of vertex buffers to bind
  13825. * @param indexBuffer defines the index buffer to bind
  13826. * @param effect defines the effect associated with the vertex buffers
  13827. */
  13828. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13829. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13830. this._cachedVertexBuffers = vertexBuffers;
  13831. this._cachedEffectForVertexBuffers = effect;
  13832. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13833. }
  13834. this._bindIndexBufferWithCache(indexBuffer);
  13835. };
  13836. /**
  13837. * Unbind all instance attributes
  13838. */
  13839. Engine.prototype.unbindInstanceAttributes = function () {
  13840. var boundBuffer;
  13841. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13842. var instancesBuffer = this._currentInstanceBuffers[i];
  13843. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13844. boundBuffer = instancesBuffer;
  13845. this.bindArrayBuffer(instancesBuffer);
  13846. }
  13847. var offsetLocation = this._currentInstanceLocations[i];
  13848. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13849. }
  13850. this._currentInstanceBuffers.length = 0;
  13851. this._currentInstanceLocations.length = 0;
  13852. };
  13853. /**
  13854. * Release and free the memory of a vertex array object
  13855. * @param vao defines the vertex array object to delete
  13856. */
  13857. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13858. this._gl.deleteVertexArray(vao);
  13859. };
  13860. /** @hidden */
  13861. Engine.prototype._releaseBuffer = function (buffer) {
  13862. buffer.references--;
  13863. if (buffer.references === 0) {
  13864. this._gl.deleteBuffer(buffer);
  13865. return true;
  13866. }
  13867. return false;
  13868. };
  13869. /**
  13870. * Creates a webGL buffer to use with instanciation
  13871. * @param capacity defines the size of the buffer
  13872. * @returns the webGL buffer
  13873. */
  13874. Engine.prototype.createInstancesBuffer = function (capacity) {
  13875. var buffer = this._gl.createBuffer();
  13876. if (!buffer) {
  13877. throw new Error("Unable to create instance buffer");
  13878. }
  13879. buffer.capacity = capacity;
  13880. this.bindArrayBuffer(buffer);
  13881. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13882. return buffer;
  13883. };
  13884. /**
  13885. * Delete a webGL buffer used with instanciation
  13886. * @param buffer defines the webGL buffer to delete
  13887. */
  13888. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13889. this._gl.deleteBuffer(buffer);
  13890. };
  13891. /**
  13892. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13893. * @param instancesBuffer defines the webGL buffer to update and bind
  13894. * @param data defines the data to store in the buffer
  13895. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13896. */
  13897. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13898. this.bindArrayBuffer(instancesBuffer);
  13899. if (data) {
  13900. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13901. }
  13902. if (offsetLocations[0].index !== undefined) {
  13903. var stride = 0;
  13904. for (var i = 0; i < offsetLocations.length; i++) {
  13905. var ai = offsetLocations[i];
  13906. stride += ai.attributeSize * 4;
  13907. }
  13908. for (var i = 0; i < offsetLocations.length; i++) {
  13909. var ai = offsetLocations[i];
  13910. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13911. this._gl.enableVertexAttribArray(ai.index);
  13912. this._vertexAttribArraysEnabled[ai.index] = true;
  13913. }
  13914. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13915. this._gl.vertexAttribDivisor(ai.index, 1);
  13916. this._currentInstanceLocations.push(ai.index);
  13917. this._currentInstanceBuffers.push(instancesBuffer);
  13918. }
  13919. }
  13920. else {
  13921. for (var index = 0; index < 4; index++) {
  13922. var offsetLocation = offsetLocations[index];
  13923. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13924. this._gl.enableVertexAttribArray(offsetLocation);
  13925. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13926. }
  13927. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13928. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13929. this._currentInstanceLocations.push(offsetLocation);
  13930. this._currentInstanceBuffers.push(instancesBuffer);
  13931. }
  13932. }
  13933. };
  13934. /**
  13935. * Apply all cached states (depth, culling, stencil and alpha)
  13936. */
  13937. Engine.prototype.applyStates = function () {
  13938. this._depthCullingState.apply(this._gl);
  13939. this._stencilState.apply(this._gl);
  13940. this._alphaState.apply(this._gl);
  13941. };
  13942. /**
  13943. * Send a draw order
  13944. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13945. * @param indexStart defines the starting index
  13946. * @param indexCount defines the number of index to draw
  13947. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13948. */
  13949. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13950. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13951. };
  13952. /**
  13953. * Draw a list of points
  13954. * @param verticesStart defines the index of first vertex to draw
  13955. * @param verticesCount defines the count of vertices to draw
  13956. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13957. */
  13958. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13959. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13960. };
  13961. /**
  13962. * Draw a list of unindexed primitives
  13963. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13964. * @param verticesStart defines the index of first vertex to draw
  13965. * @param verticesCount defines the count of vertices to draw
  13966. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13967. */
  13968. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13969. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13970. };
  13971. /**
  13972. * Draw a list of indexed primitives
  13973. * @param fillMode defines the primitive to use
  13974. * @param indexStart defines the starting index
  13975. * @param indexCount defines the number of index to draw
  13976. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13977. */
  13978. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13979. // Apply states
  13980. this.applyStates();
  13981. this._drawCalls.addCount(1, false);
  13982. // Render
  13983. var drawMode = this._drawMode(fillMode);
  13984. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13985. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13986. if (instancesCount) {
  13987. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13988. }
  13989. else {
  13990. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13991. }
  13992. };
  13993. /**
  13994. * Draw a list of unindexed primitives
  13995. * @param fillMode defines the primitive to use
  13996. * @param verticesStart defines the index of first vertex to draw
  13997. * @param verticesCount defines the count of vertices to draw
  13998. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13999. */
  14000. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14001. // Apply states
  14002. this.applyStates();
  14003. this._drawCalls.addCount(1, false);
  14004. var drawMode = this._drawMode(fillMode);
  14005. if (instancesCount) {
  14006. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14007. }
  14008. else {
  14009. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14010. }
  14011. };
  14012. Engine.prototype._drawMode = function (fillMode) {
  14013. switch (fillMode) {
  14014. // Triangle views
  14015. case BABYLON.Material.TriangleFillMode:
  14016. return this._gl.TRIANGLES;
  14017. case BABYLON.Material.PointFillMode:
  14018. return this._gl.POINTS;
  14019. case BABYLON.Material.WireFrameFillMode:
  14020. return this._gl.LINES;
  14021. // Draw modes
  14022. case BABYLON.Material.PointListDrawMode:
  14023. return this._gl.POINTS;
  14024. case BABYLON.Material.LineListDrawMode:
  14025. return this._gl.LINES;
  14026. case BABYLON.Material.LineLoopDrawMode:
  14027. return this._gl.LINE_LOOP;
  14028. case BABYLON.Material.LineStripDrawMode:
  14029. return this._gl.LINE_STRIP;
  14030. case BABYLON.Material.TriangleStripDrawMode:
  14031. return this._gl.TRIANGLE_STRIP;
  14032. case BABYLON.Material.TriangleFanDrawMode:
  14033. return this._gl.TRIANGLE_FAN;
  14034. default:
  14035. return this._gl.TRIANGLES;
  14036. }
  14037. };
  14038. // Shaders
  14039. /** @hidden */
  14040. Engine.prototype._releaseEffect = function (effect) {
  14041. if (this._compiledEffects[effect._key]) {
  14042. delete this._compiledEffects[effect._key];
  14043. this._deleteProgram(effect.getProgram());
  14044. }
  14045. };
  14046. /** @hidden */
  14047. Engine.prototype._deleteProgram = function (program) {
  14048. if (program) {
  14049. program.__SPECTOR_rebuildProgram = null;
  14050. if (program.transformFeedback) {
  14051. this.deleteTransformFeedback(program.transformFeedback);
  14052. program.transformFeedback = null;
  14053. }
  14054. this._gl.deleteProgram(program);
  14055. }
  14056. };
  14057. /**
  14058. * Create a new effect (used to store vertex/fragment shaders)
  14059. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14060. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14061. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14062. * @param samplers defines an array of string used to represent textures
  14063. * @param defines defines the string containing the defines to use to compile the shaders
  14064. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14065. * @param onCompiled defines a function to call when the effect creation is successful
  14066. * @param onError defines a function to call when the effect creation has failed
  14067. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14068. * @returns the new Effect
  14069. */
  14070. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14071. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14072. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14073. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14074. if (this._compiledEffects[name]) {
  14075. var compiledEffect = this._compiledEffects[name];
  14076. if (onCompiled && compiledEffect.isReady()) {
  14077. onCompiled(compiledEffect);
  14078. }
  14079. return compiledEffect;
  14080. }
  14081. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14082. effect._key = name;
  14083. this._compiledEffects[name] = effect;
  14084. return effect;
  14085. };
  14086. /**
  14087. * Create an effect to use with particle systems.
  14088. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14089. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14090. * @param uniformsNames defines a list of attribute names
  14091. * @param samplers defines an array of string used to represent textures
  14092. * @param defines defines the string containing the defines to use to compile the shaders
  14093. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14094. * @param onCompiled defines a function to call when the effect creation is successful
  14095. * @param onError defines a function to call when the effect creation has failed
  14096. * @returns the new Effect
  14097. */
  14098. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14099. if (uniformsNames === void 0) { uniformsNames = []; }
  14100. if (samplers === void 0) { samplers = []; }
  14101. if (defines === void 0) { defines = ""; }
  14102. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14103. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14104. if (defines.indexOf(" BILLBOARD") === -1) {
  14105. defines += "\n#define BILLBOARD\n";
  14106. }
  14107. if (samplers.indexOf("diffuseSampler") === -1) {
  14108. samplers.push("diffuseSampler");
  14109. }
  14110. return this.createEffect({
  14111. vertex: "particles",
  14112. fragmentElement: fragmentName
  14113. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14114. };
  14115. /**
  14116. * Directly creates a webGL program
  14117. * @param vertexCode defines the vertex shader code to use
  14118. * @param fragmentCode defines the fragment shader code to use
  14119. * @param context defines the webGL context to use (if not set, the current one will be used)
  14120. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14121. * @returns the new webGL program
  14122. */
  14123. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14124. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14125. context = context || this._gl;
  14126. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14127. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14128. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14129. };
  14130. /**
  14131. * Creates a webGL program
  14132. * @param vertexCode defines the vertex shader code to use
  14133. * @param fragmentCode defines the fragment shader code to use
  14134. * @param defines defines the string containing the defines to use to compile the shaders
  14135. * @param context defines the webGL context to use (if not set, the current one will be used)
  14136. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14137. * @returns the new webGL program
  14138. */
  14139. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14140. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14141. context = context || this._gl;
  14142. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14143. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14144. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14145. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14146. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14147. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14148. return program;
  14149. };
  14150. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14151. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14152. var shaderProgram = context.createProgram();
  14153. if (!shaderProgram) {
  14154. throw new Error("Unable to create program");
  14155. }
  14156. context.attachShader(shaderProgram, vertexShader);
  14157. context.attachShader(shaderProgram, fragmentShader);
  14158. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14159. var transformFeedback = this.createTransformFeedback();
  14160. this.bindTransformFeedback(transformFeedback);
  14161. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14162. shaderProgram.transformFeedback = transformFeedback;
  14163. }
  14164. context.linkProgram(shaderProgram);
  14165. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14166. this.bindTransformFeedback(null);
  14167. }
  14168. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14169. if (!linked) {
  14170. context.validateProgram(shaderProgram);
  14171. var error = context.getProgramInfoLog(shaderProgram);
  14172. if (error) {
  14173. throw new Error(error);
  14174. }
  14175. }
  14176. context.deleteShader(vertexShader);
  14177. context.deleteShader(fragmentShader);
  14178. return shaderProgram;
  14179. };
  14180. /**
  14181. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14182. * @param shaderProgram defines the webGL program to use
  14183. * @param uniformsNames defines the list of uniform names
  14184. * @returns an array of webGL uniform locations
  14185. */
  14186. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14187. var results = new Array();
  14188. for (var index = 0; index < uniformsNames.length; index++) {
  14189. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14190. }
  14191. return results;
  14192. };
  14193. /**
  14194. * Gets the lsit of active attributes for a given webGL program
  14195. * @param shaderProgram defines the webGL program to use
  14196. * @param attributesNames defines the list of attribute names to get
  14197. * @returns an array of indices indicating the offset of each attribute
  14198. */
  14199. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14200. var results = [];
  14201. for (var index = 0; index < attributesNames.length; index++) {
  14202. try {
  14203. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14204. }
  14205. catch (e) {
  14206. results.push(-1);
  14207. }
  14208. }
  14209. return results;
  14210. };
  14211. /**
  14212. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14213. * @param effect defines the effect to activate
  14214. */
  14215. Engine.prototype.enableEffect = function (effect) {
  14216. if (!effect) {
  14217. return;
  14218. }
  14219. // Use program
  14220. this.bindSamplers(effect);
  14221. this._currentEffect = effect;
  14222. if (effect.onBind) {
  14223. effect.onBind(effect);
  14224. }
  14225. effect.onBindObservable.notifyObservers(effect);
  14226. };
  14227. /**
  14228. * Set the value of an uniform to an array of int32
  14229. * @param uniform defines the webGL uniform location where to store the value
  14230. * @param array defines the array of int32 to store
  14231. */
  14232. Engine.prototype.setIntArray = function (uniform, array) {
  14233. if (!uniform)
  14234. return;
  14235. this._gl.uniform1iv(uniform, array);
  14236. };
  14237. /**
  14238. * Set the value of an uniform to an array of int32 (stored as vec2)
  14239. * @param uniform defines the webGL uniform location where to store the value
  14240. * @param array defines the array of int32 to store
  14241. */
  14242. Engine.prototype.setIntArray2 = function (uniform, array) {
  14243. if (!uniform || array.length % 2 !== 0)
  14244. return;
  14245. this._gl.uniform2iv(uniform, array);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to an array of int32 (stored as vec3)
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param array defines the array of int32 to store
  14251. */
  14252. Engine.prototype.setIntArray3 = function (uniform, array) {
  14253. if (!uniform || array.length % 3 !== 0)
  14254. return;
  14255. this._gl.uniform3iv(uniform, array);
  14256. };
  14257. /**
  14258. * Set the value of an uniform to an array of int32 (stored as vec4)
  14259. * @param uniform defines the webGL uniform location where to store the value
  14260. * @param array defines the array of int32 to store
  14261. */
  14262. Engine.prototype.setIntArray4 = function (uniform, array) {
  14263. if (!uniform || array.length % 4 !== 0)
  14264. return;
  14265. this._gl.uniform4iv(uniform, array);
  14266. };
  14267. /**
  14268. * Set the value of an uniform to an array of float32
  14269. * @param uniform defines the webGL uniform location where to store the value
  14270. * @param array defines the array of float32 to store
  14271. */
  14272. Engine.prototype.setFloatArray = function (uniform, array) {
  14273. if (!uniform)
  14274. return;
  14275. this._gl.uniform1fv(uniform, array);
  14276. };
  14277. /**
  14278. * Set the value of an uniform to an array of float32 (stored as vec2)
  14279. * @param uniform defines the webGL uniform location where to store the value
  14280. * @param array defines the array of float32 to store
  14281. */
  14282. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14283. if (!uniform || array.length % 2 !== 0)
  14284. return;
  14285. this._gl.uniform2fv(uniform, array);
  14286. };
  14287. /**
  14288. * Set the value of an uniform to an array of float32 (stored as vec3)
  14289. * @param uniform defines the webGL uniform location where to store the value
  14290. * @param array defines the array of float32 to store
  14291. */
  14292. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14293. if (!uniform || array.length % 3 !== 0)
  14294. return;
  14295. this._gl.uniform3fv(uniform, array);
  14296. };
  14297. /**
  14298. * Set the value of an uniform to an array of float32 (stored as vec4)
  14299. * @param uniform defines the webGL uniform location where to store the value
  14300. * @param array defines the array of float32 to store
  14301. */
  14302. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14303. if (!uniform || array.length % 4 !== 0)
  14304. return;
  14305. this._gl.uniform4fv(uniform, array);
  14306. };
  14307. /**
  14308. * Set the value of an uniform to an array of number
  14309. * @param uniform defines the webGL uniform location where to store the value
  14310. * @param array defines the array of number to store
  14311. */
  14312. Engine.prototype.setArray = function (uniform, array) {
  14313. if (!uniform)
  14314. return;
  14315. this._gl.uniform1fv(uniform, array);
  14316. };
  14317. /**
  14318. * Set the value of an uniform to an array of number (stored as vec2)
  14319. * @param uniform defines the webGL uniform location where to store the value
  14320. * @param array defines the array of number to store
  14321. */
  14322. Engine.prototype.setArray2 = function (uniform, array) {
  14323. if (!uniform || array.length % 2 !== 0)
  14324. return;
  14325. this._gl.uniform2fv(uniform, array);
  14326. };
  14327. /**
  14328. * Set the value of an uniform to an array of number (stored as vec3)
  14329. * @param uniform defines the webGL uniform location where to store the value
  14330. * @param array defines the array of number to store
  14331. */
  14332. Engine.prototype.setArray3 = function (uniform, array) {
  14333. if (!uniform || array.length % 3 !== 0)
  14334. return;
  14335. this._gl.uniform3fv(uniform, array);
  14336. };
  14337. /**
  14338. * Set the value of an uniform to an array of number (stored as vec4)
  14339. * @param uniform defines the webGL uniform location where to store the value
  14340. * @param array defines the array of number to store
  14341. */
  14342. Engine.prototype.setArray4 = function (uniform, array) {
  14343. if (!uniform || array.length % 4 !== 0)
  14344. return;
  14345. this._gl.uniform4fv(uniform, array);
  14346. };
  14347. /**
  14348. * Set the value of an uniform to an array of float32 (stored as matrices)
  14349. * @param uniform defines the webGL uniform location where to store the value
  14350. * @param matrices defines the array of float32 to store
  14351. */
  14352. Engine.prototype.setMatrices = function (uniform, matrices) {
  14353. if (!uniform)
  14354. return;
  14355. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14356. };
  14357. /**
  14358. * Set the value of an uniform to a matrix
  14359. * @param uniform defines the webGL uniform location where to store the value
  14360. * @param matrix defines the matrix to store
  14361. */
  14362. Engine.prototype.setMatrix = function (uniform, matrix) {
  14363. if (!uniform)
  14364. return;
  14365. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14366. };
  14367. /**
  14368. * Set the value of an uniform to a matrix (3x3)
  14369. * @param uniform defines the webGL uniform location where to store the value
  14370. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14371. */
  14372. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14373. if (!uniform)
  14374. return;
  14375. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14376. };
  14377. /**
  14378. * Set the value of an uniform to a matrix (2x2)
  14379. * @param uniform defines the webGL uniform location where to store the value
  14380. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14381. */
  14382. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14383. if (!uniform)
  14384. return;
  14385. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14386. };
  14387. /**
  14388. * Set the value of an uniform to a number (int)
  14389. * @param uniform defines the webGL uniform location where to store the value
  14390. * @param value defines the int number to store
  14391. */
  14392. Engine.prototype.setInt = function (uniform, value) {
  14393. if (!uniform)
  14394. return;
  14395. this._gl.uniform1i(uniform, value);
  14396. };
  14397. /**
  14398. * Set the value of an uniform to a number (float)
  14399. * @param uniform defines the webGL uniform location where to store the value
  14400. * @param value defines the float number to store
  14401. */
  14402. Engine.prototype.setFloat = function (uniform, value) {
  14403. if (!uniform)
  14404. return;
  14405. this._gl.uniform1f(uniform, value);
  14406. };
  14407. /**
  14408. * Set the value of an uniform to a vec2
  14409. * @param uniform defines the webGL uniform location where to store the value
  14410. * @param x defines the 1st component of the value
  14411. * @param y defines the 2nd component of the value
  14412. */
  14413. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14414. if (!uniform)
  14415. return;
  14416. this._gl.uniform2f(uniform, x, y);
  14417. };
  14418. /**
  14419. * Set the value of an uniform to a vec3
  14420. * @param uniform defines the webGL uniform location where to store the value
  14421. * @param x defines the 1st component of the value
  14422. * @param y defines the 2nd component of the value
  14423. * @param z defines the 3rd component of the value
  14424. */
  14425. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14426. if (!uniform)
  14427. return;
  14428. this._gl.uniform3f(uniform, x, y, z);
  14429. };
  14430. /**
  14431. * Set the value of an uniform to a boolean
  14432. * @param uniform defines the webGL uniform location where to store the value
  14433. * @param bool defines the boolean to store
  14434. */
  14435. Engine.prototype.setBool = function (uniform, bool) {
  14436. if (!uniform)
  14437. return;
  14438. this._gl.uniform1i(uniform, bool);
  14439. };
  14440. /**
  14441. * Set the value of an uniform to a vec4
  14442. * @param uniform defines the webGL uniform location where to store the value
  14443. * @param x defines the 1st component of the value
  14444. * @param y defines the 2nd component of the value
  14445. * @param z defines the 3rd component of the value
  14446. * @param w defines the 4th component of the value
  14447. */
  14448. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14449. if (!uniform)
  14450. return;
  14451. this._gl.uniform4f(uniform, x, y, z, w);
  14452. };
  14453. /**
  14454. * Set the value of an uniform to a Color3
  14455. * @param uniform defines the webGL uniform location where to store the value
  14456. * @param color3 defines the color to store
  14457. */
  14458. Engine.prototype.setColor3 = function (uniform, color3) {
  14459. if (!uniform)
  14460. return;
  14461. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14462. };
  14463. /**
  14464. * Set the value of an uniform to a Color3 and an alpha value
  14465. * @param uniform defines the webGL uniform location where to store the value
  14466. * @param color3 defines the color to store
  14467. * @param alpha defines the alpha component to store
  14468. */
  14469. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14470. if (!uniform)
  14471. return;
  14472. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14473. };
  14474. /**
  14475. * Sets a Color4 on a uniform variable
  14476. * @param uniform defines the uniform location
  14477. * @param color4 defines the value to be set
  14478. */
  14479. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14480. if (!uniform)
  14481. return;
  14482. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14483. };
  14484. // States
  14485. /**
  14486. * Set various states to the webGL context
  14487. * @param culling defines backface culling state
  14488. * @param zOffset defines the value to apply to zOffset (0 by default)
  14489. * @param force defines if states must be applied even if cache is up to date
  14490. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14491. */
  14492. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14493. if (zOffset === void 0) { zOffset = 0; }
  14494. if (reverseSide === void 0) { reverseSide = false; }
  14495. // Culling
  14496. if (this._depthCullingState.cull !== culling || force) {
  14497. this._depthCullingState.cull = culling;
  14498. }
  14499. // Cull face
  14500. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14501. if (this._depthCullingState.cullFace !== cullFace || force) {
  14502. this._depthCullingState.cullFace = cullFace;
  14503. }
  14504. // Z offset
  14505. this.setZOffset(zOffset);
  14506. // Front face
  14507. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14508. if (this._depthCullingState.frontFace !== frontFace || force) {
  14509. this._depthCullingState.frontFace = frontFace;
  14510. }
  14511. };
  14512. /**
  14513. * Set the z offset to apply to current rendering
  14514. * @param value defines the offset to apply
  14515. */
  14516. Engine.prototype.setZOffset = function (value) {
  14517. this._depthCullingState.zOffset = value;
  14518. };
  14519. /**
  14520. * Gets the current value of the zOffset
  14521. * @returns the current zOffset state
  14522. */
  14523. Engine.prototype.getZOffset = function () {
  14524. return this._depthCullingState.zOffset;
  14525. };
  14526. /**
  14527. * Enable or disable depth buffering
  14528. * @param enable defines the state to set
  14529. */
  14530. Engine.prototype.setDepthBuffer = function (enable) {
  14531. this._depthCullingState.depthTest = enable;
  14532. };
  14533. /**
  14534. * Gets a boolean indicating if depth writing is enabled
  14535. * @returns the current depth writing state
  14536. */
  14537. Engine.prototype.getDepthWrite = function () {
  14538. return this._depthCullingState.depthMask;
  14539. };
  14540. /**
  14541. * Enable or disable depth writing
  14542. * @param enable defines the state to set
  14543. */
  14544. Engine.prototype.setDepthWrite = function (enable) {
  14545. this._depthCullingState.depthMask = enable;
  14546. };
  14547. /**
  14548. * Enable or disable color writing
  14549. * @param enable defines the state to set
  14550. */
  14551. Engine.prototype.setColorWrite = function (enable) {
  14552. this._gl.colorMask(enable, enable, enable, enable);
  14553. this._colorWrite = enable;
  14554. };
  14555. /**
  14556. * Gets a boolean indicating if color writing is enabled
  14557. * @returns the current color writing state
  14558. */
  14559. Engine.prototype.getColorWrite = function () {
  14560. return this._colorWrite;
  14561. };
  14562. /**
  14563. * Sets alpha constants used by some alpha blending modes
  14564. * @param r defines the red component
  14565. * @param g defines the green component
  14566. * @param b defines the blue component
  14567. * @param a defines the alpha component
  14568. */
  14569. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14570. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14571. };
  14572. /**
  14573. * Sets the current alpha mode
  14574. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14575. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14576. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14577. */
  14578. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14579. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14580. if (this._alphaMode === mode) {
  14581. return;
  14582. }
  14583. switch (mode) {
  14584. case Engine.ALPHA_DISABLE:
  14585. this._alphaState.alphaBlend = false;
  14586. break;
  14587. case Engine.ALPHA_PREMULTIPLIED:
  14588. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14589. this._alphaState.alphaBlend = true;
  14590. break;
  14591. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14592. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14593. this._alphaState.alphaBlend = true;
  14594. break;
  14595. case Engine.ALPHA_COMBINE:
  14596. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14597. this._alphaState.alphaBlend = true;
  14598. break;
  14599. case Engine.ALPHA_ONEONE:
  14600. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14601. this._alphaState.alphaBlend = true;
  14602. break;
  14603. case Engine.ALPHA_ADD:
  14604. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14605. this._alphaState.alphaBlend = true;
  14606. break;
  14607. case Engine.ALPHA_SUBTRACT:
  14608. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14609. this._alphaState.alphaBlend = true;
  14610. break;
  14611. case Engine.ALPHA_MULTIPLY:
  14612. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14613. this._alphaState.alphaBlend = true;
  14614. break;
  14615. case Engine.ALPHA_MAXIMIZED:
  14616. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14617. this._alphaState.alphaBlend = true;
  14618. break;
  14619. case Engine.ALPHA_INTERPOLATE:
  14620. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14621. this._alphaState.alphaBlend = true;
  14622. break;
  14623. case Engine.ALPHA_SCREENMODE:
  14624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14625. this._alphaState.alphaBlend = true;
  14626. break;
  14627. }
  14628. if (!noDepthWriteChange) {
  14629. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14630. }
  14631. this._alphaMode = mode;
  14632. };
  14633. /**
  14634. * Gets the current alpha mode
  14635. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14636. * @returns the current alpha mode
  14637. */
  14638. Engine.prototype.getAlphaMode = function () {
  14639. return this._alphaMode;
  14640. };
  14641. // Textures
  14642. /**
  14643. * Clears the list of texture accessible through engine.
  14644. * This can help preventing texture load conflict due to name collision.
  14645. */
  14646. Engine.prototype.clearInternalTexturesCache = function () {
  14647. this._internalTexturesCache = [];
  14648. };
  14649. /**
  14650. * Force the entire cache to be cleared
  14651. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14652. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14653. */
  14654. Engine.prototype.wipeCaches = function (bruteForce) {
  14655. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14656. return;
  14657. }
  14658. this._currentEffect = null;
  14659. this._unpackFlipYCached = null;
  14660. this._viewportCached.x = 0;
  14661. this._viewportCached.y = 0;
  14662. this._viewportCached.z = 0;
  14663. this._viewportCached.w = 0;
  14664. if (bruteForce) {
  14665. this.resetTextureCache();
  14666. this._currentProgram = null;
  14667. this._stencilState.reset();
  14668. this._depthCullingState.reset();
  14669. this.setDepthFunctionToLessOrEqual();
  14670. this._alphaState.reset();
  14671. }
  14672. this._resetVertexBufferBinding();
  14673. this._cachedIndexBuffer = null;
  14674. this._cachedEffectForVertexBuffers = null;
  14675. this._unbindVertexArrayObject();
  14676. this.bindIndexBuffer(null);
  14677. };
  14678. /**
  14679. * Set the compressed texture format to use, based on the formats you have, and the formats
  14680. * supported by the hardware / browser.
  14681. *
  14682. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14683. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14684. * to API arguments needed to compressed textures. This puts the burden on the container
  14685. * generator to house the arcane code for determining these for current & future formats.
  14686. *
  14687. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14688. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14689. *
  14690. * Note: The result of this call is not taken into account when a texture is base64.
  14691. *
  14692. * @param formatsAvailable defines the list of those format families you have created
  14693. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14694. *
  14695. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14696. * @returns The extension selected.
  14697. */
  14698. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14699. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14700. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14701. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14702. return this._textureFormatInUse = this._texturesSupported[i];
  14703. }
  14704. }
  14705. }
  14706. // actively set format to nothing, to allow this to be called more than once
  14707. // and possibly fail the 2nd time
  14708. this._textureFormatInUse = null;
  14709. return null;
  14710. };
  14711. /** @hidden */
  14712. Engine.prototype._createTexture = function () {
  14713. var texture = this._gl.createTexture();
  14714. if (!texture) {
  14715. throw new Error("Unable to create texture");
  14716. }
  14717. return texture;
  14718. };
  14719. /**
  14720. * Usually called from BABYLON.Texture.ts.
  14721. * Passed information to create a WebGLTexture
  14722. * @param urlArg defines a value which contains one of the following:
  14723. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14724. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14725. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14726. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14727. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14728. * @param scene needed for loading to the correct scene
  14729. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14730. * @param onLoad optional callback to be called upon successful completion
  14731. * @param onError optional callback to be called upon failure
  14732. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14733. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14734. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14735. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14736. */
  14737. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14738. var _this = this;
  14739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14740. if (onLoad === void 0) { onLoad = null; }
  14741. if (onError === void 0) { onError = null; }
  14742. if (buffer === void 0) { buffer = null; }
  14743. if (fallback === void 0) { fallback = null; }
  14744. if (format === void 0) { format = null; }
  14745. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14746. var fromData = url.substr(0, 5) === "data:";
  14747. var fromBlob = url.substr(0, 5) === "blob:";
  14748. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14749. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14750. // establish the file extension, if possible
  14751. var lastDot = url.lastIndexOf('.');
  14752. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14753. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14754. var isTGA = (extension.indexOf(".tga") === 0);
  14755. // determine if a ktx file should be substituted
  14756. var isKTX = false;
  14757. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14758. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14759. isKTX = true;
  14760. }
  14761. if (scene) {
  14762. scene._addPendingData(texture);
  14763. }
  14764. texture.url = url;
  14765. texture.generateMipMaps = !noMipmap;
  14766. texture.samplingMode = samplingMode;
  14767. texture.invertY = invertY;
  14768. if (!this._doNotHandleContextLost) {
  14769. // Keep a link to the buffer only if we plan to handle context lost
  14770. texture._buffer = buffer;
  14771. }
  14772. var onLoadObserver = null;
  14773. if (onLoad && !fallback) {
  14774. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14775. }
  14776. if (!fallback)
  14777. this._internalTexturesCache.push(texture);
  14778. var onerror = function (message, exception) {
  14779. if (scene) {
  14780. scene._removePendingData(texture);
  14781. }
  14782. if (onLoadObserver && !isKTX) {
  14783. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14784. texture.onLoadedObservable.remove(onLoadObserver);
  14785. }
  14786. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14787. if (isKTX) {
  14788. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14789. }
  14790. else if (BABYLON.Tools.UseFallbackTexture) {
  14791. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14792. }
  14793. if (onError) {
  14794. onError(message || "Unknown error", exception);
  14795. }
  14796. };
  14797. var callback = null;
  14798. // processing for non-image formats
  14799. if (isKTX || isTGA || isDDS) {
  14800. if (isKTX) {
  14801. callback = function (data) {
  14802. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14803. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14804. ktx.uploadLevels(_this._gl, !noMipmap);
  14805. return false;
  14806. }, samplingMode);
  14807. };
  14808. }
  14809. else if (isTGA) {
  14810. callback = function (arrayBuffer) {
  14811. var data = new Uint8Array(arrayBuffer);
  14812. var header = BABYLON.TGATools.GetTGAHeader(data);
  14813. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14814. BABYLON.TGATools.UploadContent(_this._gl, data);
  14815. return false;
  14816. }, samplingMode);
  14817. };
  14818. }
  14819. else if (isDDS) {
  14820. callback = function (data) {
  14821. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14822. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14823. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14824. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14825. return false;
  14826. }, samplingMode);
  14827. };
  14828. }
  14829. if (!buffer) {
  14830. this._loadFile(url, function (data) {
  14831. if (callback) {
  14832. callback(data);
  14833. }
  14834. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14835. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14836. });
  14837. }
  14838. else {
  14839. if (callback) {
  14840. callback(buffer);
  14841. }
  14842. }
  14843. // image format processing
  14844. }
  14845. else {
  14846. var onload = function (img) {
  14847. if (fromBlob && !_this._doNotHandleContextLost) {
  14848. // We need to store the image if we need to rebuild the texture
  14849. // in case of a webgl context lost
  14850. texture._buffer = img;
  14851. }
  14852. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14853. var gl = _this._gl;
  14854. var isPot = (img.width === potWidth && img.height === potHeight);
  14855. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14856. if (isPot) {
  14857. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14858. return false;
  14859. }
  14860. var maxTextureSize = _this._caps.maxTextureSize;
  14861. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14862. _this._prepareWorkingCanvas();
  14863. if (!_this._workingCanvas || !_this._workingContext) {
  14864. return false;
  14865. }
  14866. _this._workingCanvas.width = potWidth;
  14867. _this._workingCanvas.height = potHeight;
  14868. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14869. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14870. texture.width = potWidth;
  14871. texture.height = potHeight;
  14872. return false;
  14873. }
  14874. else {
  14875. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14876. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14877. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14878. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14883. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14884. _this._releaseTexture(source_1);
  14885. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14886. continuationCallback();
  14887. });
  14888. }
  14889. return true;
  14890. }, samplingMode);
  14891. };
  14892. if (!fromData || isBase64) {
  14893. if (buffer instanceof HTMLImageElement) {
  14894. onload(buffer);
  14895. }
  14896. else {
  14897. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14898. }
  14899. }
  14900. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14901. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14902. }
  14903. else {
  14904. onload(buffer);
  14905. }
  14906. }
  14907. return texture;
  14908. };
  14909. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14910. var _this = this;
  14911. var rtt = this.createRenderTargetTexture({
  14912. width: destination.width,
  14913. height: destination.height,
  14914. }, {
  14915. generateMipMaps: false,
  14916. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14917. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14918. generateDepthBuffer: false,
  14919. generateStencilBuffer: false
  14920. });
  14921. if (!this._rescalePostProcess) {
  14922. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14923. }
  14924. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14925. _this._rescalePostProcess.onApply = function (effect) {
  14926. effect._bindTexture("textureSampler", source);
  14927. };
  14928. var hostingScene = scene;
  14929. if (!hostingScene) {
  14930. hostingScene = _this.scenes[_this.scenes.length - 1];
  14931. }
  14932. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14933. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14934. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14935. _this.unBindFramebuffer(rtt);
  14936. _this._releaseTexture(rtt);
  14937. if (onComplete) {
  14938. onComplete();
  14939. }
  14940. });
  14941. };
  14942. /**
  14943. * Update a raw texture
  14944. * @param texture defines the texture to update
  14945. * @param data defines the data to store in the texture
  14946. * @param format defines the format of the data
  14947. * @param invertY defines if data must be stored with Y axis inverted
  14948. * @param compression defines the compression used (null by default)
  14949. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14950. */
  14951. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14952. if (compression === void 0) { compression = null; }
  14953. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14954. if (!texture) {
  14955. return;
  14956. }
  14957. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14958. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14959. // babylon's internalFormat but gl's texImage2D format
  14960. var internalFormat = this._getInternalFormat(format);
  14961. var textureType = this._getWebGLTextureType(type);
  14962. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14963. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14964. if (!this._doNotHandleContextLost) {
  14965. texture._bufferView = data;
  14966. texture.format = format;
  14967. texture.type = type;
  14968. texture.invertY = invertY;
  14969. texture._compression = compression;
  14970. }
  14971. if (texture.width % 4 !== 0) {
  14972. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14973. }
  14974. if (compression && data) {
  14975. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14976. }
  14977. else {
  14978. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14979. }
  14980. if (texture.generateMipMaps) {
  14981. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14982. }
  14983. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14984. // this.resetTextureCache();
  14985. texture.isReady = true;
  14986. };
  14987. /**
  14988. * Creates a raw texture
  14989. * @param data defines the data to store in the texture
  14990. * @param width defines the width of the texture
  14991. * @param height defines the height of the texture
  14992. * @param format defines the format of the data
  14993. * @param generateMipMaps defines if the engine should generate the mip levels
  14994. * @param invertY defines if data must be stored with Y axis inverted
  14995. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14996. * @param compression defines the compression used (null by default)
  14997. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14998. * @returns the raw texture inside an InternalTexture
  14999. */
  15000. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15001. if (compression === void 0) { compression = null; }
  15002. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15003. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15004. texture.baseWidth = width;
  15005. texture.baseHeight = height;
  15006. texture.width = width;
  15007. texture.height = height;
  15008. texture.format = format;
  15009. texture.generateMipMaps = generateMipMaps;
  15010. texture.samplingMode = samplingMode;
  15011. texture.invertY = invertY;
  15012. texture._compression = compression;
  15013. texture.type = type;
  15014. if (!this._doNotHandleContextLost) {
  15015. texture._bufferView = data;
  15016. }
  15017. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15019. // Filters
  15020. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15021. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15023. if (generateMipMaps) {
  15024. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15025. }
  15026. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15027. this._internalTexturesCache.push(texture);
  15028. return texture;
  15029. };
  15030. /** @hidden */
  15031. Engine.prototype._unpackFlipY = function (value) {
  15032. if (this._unpackFlipYCached !== value) {
  15033. this._unpackFlipYCached = value;
  15034. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15035. }
  15036. };
  15037. /**
  15038. * Creates a dynamic texture
  15039. * @param width defines the width of the texture
  15040. * @param height defines the height of the texture
  15041. * @param generateMipMaps defines if the engine should generate the mip levels
  15042. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15043. * @returns the dynamic texture inside an InternalTexture
  15044. */
  15045. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15046. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15047. texture.baseWidth = width;
  15048. texture.baseHeight = height;
  15049. if (generateMipMaps) {
  15050. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15051. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15052. }
  15053. // this.resetTextureCache();
  15054. texture.width = width;
  15055. texture.height = height;
  15056. texture.isReady = false;
  15057. texture.generateMipMaps = generateMipMaps;
  15058. texture.samplingMode = samplingMode;
  15059. this.updateTextureSamplingMode(samplingMode, texture);
  15060. this._internalTexturesCache.push(texture);
  15061. return texture;
  15062. };
  15063. /**
  15064. * Update the sampling mode of a given texture
  15065. * @param samplingMode defines the required sampling mode
  15066. * @param texture defines the texture to update
  15067. */
  15068. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15069. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15070. if (texture.isCube) {
  15071. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15072. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15073. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15074. }
  15075. else if (texture.is3D) {
  15076. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15077. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15078. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15079. }
  15080. else {
  15081. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15082. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15083. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15084. }
  15085. texture.samplingMode = samplingMode;
  15086. };
  15087. /**
  15088. * Update the content of a dynamic texture
  15089. * @param texture defines the texture to update
  15090. * @param canvas defines the canvas containing the source
  15091. * @param invertY defines if data must be stored with Y axis inverted
  15092. * @param premulAlpha defines if alpha is stored as premultiplied
  15093. * @param format defines the format of the data
  15094. */
  15095. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15096. if (premulAlpha === void 0) { premulAlpha = false; }
  15097. if (!texture) {
  15098. return;
  15099. }
  15100. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15101. this._unpackFlipY(invertY);
  15102. if (premulAlpha) {
  15103. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15104. }
  15105. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15106. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15107. if (texture.generateMipMaps) {
  15108. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15109. }
  15110. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15111. if (premulAlpha) {
  15112. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15113. }
  15114. texture.isReady = true;
  15115. };
  15116. /**
  15117. * Update a video texture
  15118. * @param texture defines the texture to update
  15119. * @param video defines the video element to use
  15120. * @param invertY defines if data must be stored with Y axis inverted
  15121. */
  15122. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15123. if (!texture || texture._isDisabled) {
  15124. return;
  15125. }
  15126. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15127. this._unpackFlipY(!invertY); // Video are upside down by default
  15128. try {
  15129. // Testing video texture support
  15130. if (this._videoTextureSupported === undefined) {
  15131. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15132. if (this._gl.getError() !== 0) {
  15133. this._videoTextureSupported = false;
  15134. }
  15135. else {
  15136. this._videoTextureSupported = true;
  15137. }
  15138. }
  15139. // Copy video through the current working canvas if video texture is not supported
  15140. if (!this._videoTextureSupported) {
  15141. if (!texture._workingCanvas) {
  15142. texture._workingCanvas = document.createElement("canvas");
  15143. var context = texture._workingCanvas.getContext("2d");
  15144. if (!context) {
  15145. throw new Error("Unable to get 2d context");
  15146. }
  15147. texture._workingContext = context;
  15148. texture._workingCanvas.width = texture.width;
  15149. texture._workingCanvas.height = texture.height;
  15150. }
  15151. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15152. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15153. }
  15154. else {
  15155. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15156. }
  15157. if (texture.generateMipMaps) {
  15158. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15159. }
  15160. if (!wasPreviouslyBound) {
  15161. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15162. }
  15163. // this.resetTextureCache();
  15164. texture.isReady = true;
  15165. }
  15166. catch (ex) {
  15167. // Something unexpected
  15168. // Let's disable the texture
  15169. texture._isDisabled = true;
  15170. }
  15171. };
  15172. /**
  15173. * Updates a depth texture Comparison Mode and Function.
  15174. * If the comparison Function is equal to 0, the mode will be set to none.
  15175. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15176. * @param texture The texture to set the comparison function for
  15177. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15178. */
  15179. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15180. if (this.webGLVersion === 1) {
  15181. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15182. return;
  15183. }
  15184. var gl = this._gl;
  15185. if (texture.isCube) {
  15186. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15187. if (comparisonFunction === 0) {
  15188. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15190. }
  15191. else {
  15192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15194. }
  15195. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15196. }
  15197. else {
  15198. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15199. if (comparisonFunction === 0) {
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15202. }
  15203. else {
  15204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15206. }
  15207. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15208. }
  15209. texture._comparisonFunction = comparisonFunction;
  15210. };
  15211. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15212. var width = size.width || size;
  15213. var height = size.height || size;
  15214. internalTexture.baseWidth = width;
  15215. internalTexture.baseHeight = height;
  15216. internalTexture.width = width;
  15217. internalTexture.height = height;
  15218. internalTexture.isReady = true;
  15219. internalTexture.samples = 1;
  15220. internalTexture.generateMipMaps = false;
  15221. internalTexture._generateDepthBuffer = true;
  15222. internalTexture._generateStencilBuffer = generateStencil;
  15223. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15224. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15225. internalTexture._comparisonFunction = comparisonFunction;
  15226. var gl = this._gl;
  15227. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15228. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15229. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15230. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15231. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15232. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15233. if (comparisonFunction === 0) {
  15234. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15235. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15236. }
  15237. else {
  15238. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15239. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15240. }
  15241. };
  15242. /**
  15243. * Creates a depth stencil texture.
  15244. * This is only available in WebGL 2 or with the depth texture extension available.
  15245. * @param size The size of face edge in the texture.
  15246. * @param options The options defining the texture.
  15247. * @returns The texture
  15248. */
  15249. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15250. if (options.isCube) {
  15251. var width = size.width || size;
  15252. return this._createDepthStencilCubeTexture(width, options);
  15253. }
  15254. else {
  15255. return this._createDepthStencilTexture(size, options);
  15256. }
  15257. };
  15258. /**
  15259. * Creates a depth stencil texture.
  15260. * This is only available in WebGL 2 or with the depth texture extension available.
  15261. * @param size The size of face edge in the texture.
  15262. * @param options The options defining the texture.
  15263. * @returns The texture
  15264. */
  15265. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15266. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15267. if (!this._caps.depthTextureExtension) {
  15268. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15269. return internalTexture;
  15270. }
  15271. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15272. var gl = this._gl;
  15273. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15274. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15275. if (this.webGLVersion > 1) {
  15276. if (internalOptions.generateStencil) {
  15277. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15278. }
  15279. else {
  15280. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15281. }
  15282. }
  15283. else {
  15284. if (internalOptions.generateStencil) {
  15285. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15286. }
  15287. else {
  15288. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15289. }
  15290. }
  15291. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15292. return internalTexture;
  15293. };
  15294. /**
  15295. * Creates a depth stencil cube texture.
  15296. * This is only available in WebGL 2.
  15297. * @param size The size of face edge in the cube texture.
  15298. * @param options The options defining the cube texture.
  15299. * @returns The cube texture
  15300. */
  15301. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15302. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15303. internalTexture.isCube = true;
  15304. if (this.webGLVersion === 1) {
  15305. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15306. return internalTexture;
  15307. }
  15308. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15309. var gl = this._gl;
  15310. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15311. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15312. // Create the depth/stencil buffer
  15313. for (var face = 0; face < 6; face++) {
  15314. if (internalOptions.generateStencil) {
  15315. 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);
  15316. }
  15317. else {
  15318. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15319. }
  15320. }
  15321. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15322. return internalTexture;
  15323. };
  15324. /**
  15325. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15326. * @param renderTarget The render target to set the frame buffer for
  15327. */
  15328. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15329. // Create the framebuffer
  15330. var internalTexture = renderTarget.getInternalTexture();
  15331. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15332. return;
  15333. }
  15334. var gl = this._gl;
  15335. var depthStencilTexture = renderTarget.depthStencilTexture;
  15336. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15337. if (depthStencilTexture.isCube) {
  15338. if (depthStencilTexture._generateStencilBuffer) {
  15339. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15340. }
  15341. else {
  15342. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15343. }
  15344. }
  15345. else {
  15346. if (depthStencilTexture._generateStencilBuffer) {
  15347. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15348. }
  15349. else {
  15350. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15351. }
  15352. }
  15353. this.bindUnboundFramebuffer(null);
  15354. };
  15355. /**
  15356. * Creates a new render target texture
  15357. * @param size defines the size of the texture
  15358. * @param options defines the options used to create the texture
  15359. * @returns a new render target texture stored in an InternalTexture
  15360. */
  15361. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15362. var fullOptions = new RenderTargetCreationOptions();
  15363. if (options !== undefined && typeof options === "object") {
  15364. fullOptions.generateMipMaps = options.generateMipMaps;
  15365. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15366. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15367. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15368. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15369. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15370. }
  15371. else {
  15372. fullOptions.generateMipMaps = options;
  15373. fullOptions.generateDepthBuffer = true;
  15374. fullOptions.generateStencilBuffer = false;
  15375. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15376. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15377. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15378. }
  15379. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15380. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15381. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15382. }
  15383. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15384. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15385. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15386. }
  15387. var gl = this._gl;
  15388. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15389. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15390. var width = size.width || size;
  15391. var height = size.height || size;
  15392. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15393. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15394. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15395. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15396. }
  15397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15399. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15401. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15402. // Create the framebuffer
  15403. var currentFrameBuffer = this._currentFramebuffer;
  15404. var framebuffer = gl.createFramebuffer();
  15405. this.bindUnboundFramebuffer(framebuffer);
  15406. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15407. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15408. if (fullOptions.generateMipMaps) {
  15409. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15410. }
  15411. // Unbind
  15412. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15413. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15414. this.bindUnboundFramebuffer(currentFrameBuffer);
  15415. texture._framebuffer = framebuffer;
  15416. texture.baseWidth = width;
  15417. texture.baseHeight = height;
  15418. texture.width = width;
  15419. texture.height = height;
  15420. texture.isReady = true;
  15421. texture.samples = 1;
  15422. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15423. texture.samplingMode = fullOptions.samplingMode;
  15424. texture.type = fullOptions.type;
  15425. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15426. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15427. // this.resetTextureCache();
  15428. this._internalTexturesCache.push(texture);
  15429. return texture;
  15430. };
  15431. /**
  15432. * Create a multi render target texture
  15433. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15434. * @param size defines the size of the texture
  15435. * @param options defines the creation options
  15436. * @returns the cube texture as an InternalTexture
  15437. */
  15438. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15439. var generateMipMaps = false;
  15440. var generateDepthBuffer = true;
  15441. var generateStencilBuffer = false;
  15442. var generateDepthTexture = false;
  15443. var textureCount = 1;
  15444. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15445. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15446. var types = new Array();
  15447. var samplingModes = new Array();
  15448. if (options !== undefined) {
  15449. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15450. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15451. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15452. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15453. textureCount = options.textureCount || 1;
  15454. if (options.types) {
  15455. types = options.types;
  15456. }
  15457. if (options.samplingModes) {
  15458. samplingModes = options.samplingModes;
  15459. }
  15460. }
  15461. var gl = this._gl;
  15462. // Create the framebuffer
  15463. var framebuffer = gl.createFramebuffer();
  15464. this.bindUnboundFramebuffer(framebuffer);
  15465. var width = size.width || size;
  15466. var height = size.height || size;
  15467. var textures = [];
  15468. var attachments = [];
  15469. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15470. for (var i = 0; i < textureCount; i++) {
  15471. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15472. var type = types[i] || defaultType;
  15473. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15474. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15475. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15476. }
  15477. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15478. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15479. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15480. }
  15481. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15482. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15483. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15484. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15485. }
  15486. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15487. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15488. textures.push(texture);
  15489. attachments.push(attachment);
  15490. gl.activeTexture(gl["TEXTURE" + i]);
  15491. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15496. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15497. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15498. if (generateMipMaps) {
  15499. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15500. }
  15501. // Unbind
  15502. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15503. texture._framebuffer = framebuffer;
  15504. texture._depthStencilBuffer = depthStencilBuffer;
  15505. texture.baseWidth = width;
  15506. texture.baseHeight = height;
  15507. texture.width = width;
  15508. texture.height = height;
  15509. texture.isReady = true;
  15510. texture.samples = 1;
  15511. texture.generateMipMaps = generateMipMaps;
  15512. texture.samplingMode = samplingMode;
  15513. texture.type = type;
  15514. texture._generateDepthBuffer = generateDepthBuffer;
  15515. texture._generateStencilBuffer = generateStencilBuffer;
  15516. texture._attachments = attachments;
  15517. this._internalTexturesCache.push(texture);
  15518. }
  15519. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15520. // Depth texture
  15521. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15522. gl.activeTexture(gl.TEXTURE0);
  15523. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15528. 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);
  15529. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15530. depthTexture._framebuffer = framebuffer;
  15531. depthTexture.baseWidth = width;
  15532. depthTexture.baseHeight = height;
  15533. depthTexture.width = width;
  15534. depthTexture.height = height;
  15535. depthTexture.isReady = true;
  15536. depthTexture.samples = 1;
  15537. depthTexture.generateMipMaps = generateMipMaps;
  15538. depthTexture.samplingMode = gl.NEAREST;
  15539. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15540. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15541. textures.push(depthTexture);
  15542. this._internalTexturesCache.push(depthTexture);
  15543. }
  15544. gl.drawBuffers(attachments);
  15545. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15546. this.bindUnboundFramebuffer(null);
  15547. this.resetTextureCache();
  15548. return textures;
  15549. };
  15550. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15551. if (samples === void 0) { samples = 1; }
  15552. var depthStencilBuffer = null;
  15553. var gl = this._gl;
  15554. // Create the depth/stencil buffer
  15555. if (generateStencilBuffer) {
  15556. depthStencilBuffer = gl.createRenderbuffer();
  15557. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15558. if (samples > 1) {
  15559. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15560. }
  15561. else {
  15562. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15563. }
  15564. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15565. }
  15566. else if (generateDepthBuffer) {
  15567. depthStencilBuffer = gl.createRenderbuffer();
  15568. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15569. if (samples > 1) {
  15570. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15571. }
  15572. else {
  15573. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15574. }
  15575. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15576. }
  15577. return depthStencilBuffer;
  15578. };
  15579. /**
  15580. * Updates the sample count of a render target texture
  15581. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15582. * @param texture defines the texture to update
  15583. * @param samples defines the sample count to set
  15584. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15585. */
  15586. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15587. if (this.webGLVersion < 2 || !texture) {
  15588. return 1;
  15589. }
  15590. if (texture.samples === samples) {
  15591. return samples;
  15592. }
  15593. var gl = this._gl;
  15594. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15595. // Dispose previous render buffers
  15596. if (texture._depthStencilBuffer) {
  15597. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15598. texture._depthStencilBuffer = null;
  15599. }
  15600. if (texture._MSAAFramebuffer) {
  15601. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15602. texture._MSAAFramebuffer = null;
  15603. }
  15604. if (texture._MSAARenderBuffer) {
  15605. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15606. texture._MSAARenderBuffer = null;
  15607. }
  15608. if (samples > 1) {
  15609. var framebuffer = gl.createFramebuffer();
  15610. if (!framebuffer) {
  15611. throw new Error("Unable to create multi sampled framebuffer");
  15612. }
  15613. texture._MSAAFramebuffer = framebuffer;
  15614. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15615. var colorRenderbuffer = gl.createRenderbuffer();
  15616. if (!colorRenderbuffer) {
  15617. throw new Error("Unable to create multi sampled framebuffer");
  15618. }
  15619. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15620. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15621. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15622. texture._MSAARenderBuffer = colorRenderbuffer;
  15623. }
  15624. else {
  15625. this.bindUnboundFramebuffer(texture._framebuffer);
  15626. }
  15627. texture.samples = samples;
  15628. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15629. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15630. this.bindUnboundFramebuffer(null);
  15631. return samples;
  15632. };
  15633. /**
  15634. * Update the sample count for a given multiple render target texture
  15635. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15636. * @param textures defines the textures to update
  15637. * @param samples defines the sample count to set
  15638. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15639. */
  15640. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15641. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15642. return 1;
  15643. }
  15644. if (textures[0].samples === samples) {
  15645. return samples;
  15646. }
  15647. var gl = this._gl;
  15648. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15649. // Dispose previous render buffers
  15650. if (textures[0]._depthStencilBuffer) {
  15651. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15652. textures[0]._depthStencilBuffer = null;
  15653. }
  15654. if (textures[0]._MSAAFramebuffer) {
  15655. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15656. textures[0]._MSAAFramebuffer = null;
  15657. }
  15658. for (var i = 0; i < textures.length; i++) {
  15659. if (textures[i]._MSAARenderBuffer) {
  15660. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15661. textures[i]._MSAARenderBuffer = null;
  15662. }
  15663. }
  15664. if (samples > 1) {
  15665. var framebuffer = gl.createFramebuffer();
  15666. if (!framebuffer) {
  15667. throw new Error("Unable to create multi sampled framebuffer");
  15668. }
  15669. this.bindUnboundFramebuffer(framebuffer);
  15670. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15671. var attachments = [];
  15672. for (var i = 0; i < textures.length; i++) {
  15673. var texture = textures[i];
  15674. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15675. var colorRenderbuffer = gl.createRenderbuffer();
  15676. if (!colorRenderbuffer) {
  15677. throw new Error("Unable to create multi sampled framebuffer");
  15678. }
  15679. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15680. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15682. texture._MSAAFramebuffer = framebuffer;
  15683. texture._MSAARenderBuffer = colorRenderbuffer;
  15684. texture.samples = samples;
  15685. texture._depthStencilBuffer = depthStencilBuffer;
  15686. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15687. attachments.push(attachment);
  15688. }
  15689. gl.drawBuffers(attachments);
  15690. }
  15691. else {
  15692. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15693. }
  15694. this.bindUnboundFramebuffer(null);
  15695. return samples;
  15696. };
  15697. /** @hidden */
  15698. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15699. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15700. };
  15701. /** @hidden */
  15702. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15703. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15704. };
  15705. /** @hidden */
  15706. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15707. var gl = this._gl;
  15708. var textureType = this._getWebGLTextureType(texture.type);
  15709. var format = this._getInternalFormat(texture.format);
  15710. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15711. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15712. this._bindTextureDirectly(bindTarget, texture, true);
  15713. this._unpackFlipY(texture.invertY);
  15714. var target = gl.TEXTURE_2D;
  15715. if (texture.isCube) {
  15716. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15717. }
  15718. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15719. this._bindTextureDirectly(bindTarget, null, true);
  15720. };
  15721. /**
  15722. * Creates a new render target cube texture
  15723. * @param size defines the size of the texture
  15724. * @param options defines the options used to create the texture
  15725. * @returns a new render target cube texture stored in an InternalTexture
  15726. */
  15727. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15728. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15729. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15730. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15731. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15732. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15733. }
  15734. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15735. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15736. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15737. }
  15738. var gl = this._gl;
  15739. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15740. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15741. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15742. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15743. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15744. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15745. }
  15746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15750. for (var face = 0; face < 6; face++) {
  15751. 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);
  15752. }
  15753. // Create the framebuffer
  15754. var framebuffer = gl.createFramebuffer();
  15755. this.bindUnboundFramebuffer(framebuffer);
  15756. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15757. // MipMaps
  15758. if (fullOptions.generateMipMaps) {
  15759. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15760. }
  15761. // Unbind
  15762. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15763. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15764. this.bindUnboundFramebuffer(null);
  15765. texture._framebuffer = framebuffer;
  15766. texture.width = size;
  15767. texture.height = size;
  15768. texture.isReady = true;
  15769. texture.isCube = true;
  15770. texture.samples = 1;
  15771. texture.generateMipMaps = fullOptions.generateMipMaps;
  15772. texture.samplingMode = fullOptions.samplingMode;
  15773. texture.type = fullOptions.type;
  15774. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15775. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15776. this._internalTexturesCache.push(texture);
  15777. return texture;
  15778. };
  15779. /**
  15780. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15781. * @param rootUrl defines the url where the file to load is located
  15782. * @param scene defines the current scene
  15783. * @param lodScale defines scale to apply to the mip map selection
  15784. * @param lodOffset defines offset to apply to the mip map selection
  15785. * @param onLoad defines an optional callback raised when the texture is loaded
  15786. * @param onError defines an optional callback raised if there is an issue to load the texture
  15787. * @param format defines the format of the data
  15788. * @param forcedExtension defines the extension to use to pick the right loader
  15789. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15790. * @returns the cube texture as an InternalTexture
  15791. */
  15792. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15793. var _this = this;
  15794. if (onLoad === void 0) { onLoad = null; }
  15795. if (onError === void 0) { onError = null; }
  15796. if (forcedExtension === void 0) { forcedExtension = null; }
  15797. if (createPolynomials === void 0) { createPolynomials = true; }
  15798. var callback = function (loadData) {
  15799. if (!loadData) {
  15800. if (onLoad) {
  15801. onLoad(null);
  15802. }
  15803. return;
  15804. }
  15805. var texture = loadData.texture;
  15806. if (!createPolynomials) {
  15807. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15808. }
  15809. else if (loadData.info.sphericalPolynomial) {
  15810. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15811. }
  15812. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15813. if (_this._caps.textureLOD) {
  15814. // Do not add extra process if texture lod is supported.
  15815. if (onLoad) {
  15816. onLoad(texture);
  15817. }
  15818. return;
  15819. }
  15820. var mipSlices = 3;
  15821. var gl = _this._gl;
  15822. var width = loadData.width;
  15823. if (!width) {
  15824. return;
  15825. }
  15826. var textures = [];
  15827. for (var i = 0; i < mipSlices; i++) {
  15828. //compute LOD from even spacing in smoothness (matching shader calculation)
  15829. var smoothness = i / (mipSlices - 1);
  15830. var roughness = 1 - smoothness;
  15831. var minLODIndex = lodOffset; // roughness = 0
  15832. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15833. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15834. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15835. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15836. glTextureFromLod.isCube = true;
  15837. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15842. if (loadData.isDDS) {
  15843. var info = loadData.info;
  15844. var data = loadData.data;
  15845. _this._unpackFlipY(info.isCompressed);
  15846. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15847. }
  15848. else {
  15849. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15850. }
  15851. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15852. // Wrap in a base texture for easy binding.
  15853. var lodTexture = new BABYLON.BaseTexture(scene);
  15854. lodTexture.isCube = true;
  15855. lodTexture._texture = glTextureFromLod;
  15856. glTextureFromLod.isReady = true;
  15857. textures.push(lodTexture);
  15858. }
  15859. texture._lodTextureHigh = textures[2];
  15860. texture._lodTextureMid = textures[1];
  15861. texture._lodTextureLow = textures[0];
  15862. if (onLoad) {
  15863. onLoad(texture);
  15864. }
  15865. };
  15866. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15867. };
  15868. /**
  15869. * Creates a cube texture
  15870. * @param rootUrl defines the url where the files to load is located
  15871. * @param scene defines the current scene
  15872. * @param files defines the list of files to load (1 per face)
  15873. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15874. * @param onLoad defines an optional callback raised when the texture is loaded
  15875. * @param onError defines an optional callback raised if there is an issue to load the texture
  15876. * @param format defines the format of the data
  15877. * @param forcedExtension defines the extension to use to pick the right loader
  15878. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15879. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15880. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15881. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15882. * @returns the cube texture as an InternalTexture
  15883. */
  15884. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15885. var _this = this;
  15886. if (onLoad === void 0) { onLoad = null; }
  15887. if (onError === void 0) { onError = null; }
  15888. if (forcedExtension === void 0) { forcedExtension = null; }
  15889. if (createPolynomials === void 0) { createPolynomials = false; }
  15890. if (lodScale === void 0) { lodScale = 0; }
  15891. if (lodOffset === void 0) { lodOffset = 0; }
  15892. if (fallback === void 0) { fallback = null; }
  15893. var gl = this._gl;
  15894. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15895. texture.isCube = true;
  15896. texture.url = rootUrl;
  15897. texture.generateMipMaps = !noMipmap;
  15898. texture._lodGenerationScale = lodScale;
  15899. texture._lodGenerationOffset = lodOffset;
  15900. if (!this._doNotHandleContextLost) {
  15901. texture._extension = forcedExtension;
  15902. texture._files = files;
  15903. }
  15904. var isKTX = false;
  15905. var isDDS = false;
  15906. var isEnv = false;
  15907. var lastDot = rootUrl.lastIndexOf('.');
  15908. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15909. if (this._textureFormatInUse && !fallback) {
  15910. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15911. isKTX = true;
  15912. }
  15913. else {
  15914. isDDS = (extension === ".dds");
  15915. isEnv = (extension === ".env");
  15916. }
  15917. var onerror = function (request, exception) {
  15918. if (isKTX) {
  15919. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15920. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15921. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15922. }
  15923. if (onError && request) {
  15924. onError(request.status + " " + request.statusText, exception);
  15925. }
  15926. };
  15927. if (isKTX) {
  15928. this._loadFile(rootUrl, function (data) {
  15929. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15930. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15931. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15932. _this._unpackFlipY(true);
  15933. ktx.uploadLevels(_this._gl, !noMipmap);
  15934. _this.setCubeMapTextureParams(gl, loadMipmap);
  15935. texture.width = ktx.pixelWidth;
  15936. texture.height = ktx.pixelHeight;
  15937. texture.isReady = true;
  15938. }, undefined, undefined, true, onerror);
  15939. }
  15940. else if (isEnv) {
  15941. this._loadFile(rootUrl, function (data) {
  15942. data = data;
  15943. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15944. if (info) {
  15945. texture.width = info.width;
  15946. texture.height = info.width;
  15947. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15948. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15949. texture.isReady = true;
  15950. if (onLoad) {
  15951. onLoad();
  15952. }
  15953. });
  15954. }
  15955. else if (onError) {
  15956. onError("Can not parse the environment file", null);
  15957. }
  15958. }, undefined, undefined, true, onerror);
  15959. }
  15960. else if (isDDS) {
  15961. if (files && files.length === 6) {
  15962. this._cascadeLoadFiles(scene, function (imgs) {
  15963. var info;
  15964. var loadMipmap = false;
  15965. var width = 0;
  15966. for (var index = 0; index < imgs.length; index++) {
  15967. var data = imgs[index];
  15968. info = BABYLON.DDSTools.GetDDSInfo(data);
  15969. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15970. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15971. _this._unpackFlipY(info.isCompressed);
  15972. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15973. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15974. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15975. }
  15976. texture.width = info.width;
  15977. texture.height = info.height;
  15978. texture.type = info.textureType;
  15979. width = info.width;
  15980. }
  15981. _this.setCubeMapTextureParams(gl, loadMipmap);
  15982. texture.isReady = true;
  15983. if (onLoad) {
  15984. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15985. }
  15986. }, files, onError);
  15987. }
  15988. else {
  15989. this._loadFile(rootUrl, function (data) {
  15990. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15991. if (createPolynomials) {
  15992. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15993. }
  15994. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15995. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15996. _this._unpackFlipY(info.isCompressed);
  15997. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15998. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15999. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16000. }
  16001. _this.setCubeMapTextureParams(gl, loadMipmap);
  16002. texture.width = info.width;
  16003. texture.height = info.height;
  16004. texture.isReady = true;
  16005. texture.type = info.textureType;
  16006. if (onLoad) {
  16007. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  16008. }
  16009. }, undefined, undefined, true, onerror);
  16010. }
  16011. }
  16012. else {
  16013. if (!files) {
  16014. throw new Error("Cannot load cubemap because files were not defined");
  16015. }
  16016. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16017. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16018. var height = width;
  16019. _this._prepareWorkingCanvas();
  16020. if (!_this._workingCanvas || !_this._workingContext) {
  16021. return;
  16022. }
  16023. _this._workingCanvas.width = width;
  16024. _this._workingCanvas.height = height;
  16025. var faces = [
  16026. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16027. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16028. ];
  16029. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16030. _this._unpackFlipY(false);
  16031. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16032. for (var index = 0; index < faces.length; index++) {
  16033. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16034. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16035. }
  16036. if (!noMipmap) {
  16037. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16038. }
  16039. _this.setCubeMapTextureParams(gl, !noMipmap);
  16040. texture.width = width;
  16041. texture.height = height;
  16042. texture.isReady = true;
  16043. if (format) {
  16044. texture.format = format;
  16045. }
  16046. texture.onLoadedObservable.notifyObservers(texture);
  16047. texture.onLoadedObservable.clear();
  16048. if (onLoad) {
  16049. onLoad();
  16050. }
  16051. }, files, onError);
  16052. }
  16053. this._internalTexturesCache.push(texture);
  16054. return texture;
  16055. };
  16056. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16061. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16062. // this.resetTextureCache();
  16063. };
  16064. /**
  16065. * Update a raw cube texture
  16066. * @param texture defines the texture to udpdate
  16067. * @param data defines the data to store
  16068. * @param format defines the data format
  16069. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16070. * @param invertY defines if data must be stored with Y axis inverted
  16071. * @param compression defines the compression used (null by default)
  16072. * @param level defines which level of the texture to update
  16073. */
  16074. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16075. if (compression === void 0) { compression = null; }
  16076. if (level === void 0) { level = 0; }
  16077. texture._bufferViewArray = data;
  16078. texture.format = format;
  16079. texture.type = type;
  16080. texture.invertY = invertY;
  16081. texture._compression = compression;
  16082. var gl = this._gl;
  16083. var textureType = this._getWebGLTextureType(type);
  16084. var internalFormat = this._getInternalFormat(format);
  16085. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16086. var needConversion = false;
  16087. if (internalFormat === gl.RGB) {
  16088. internalFormat = gl.RGBA;
  16089. needConversion = true;
  16090. }
  16091. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16092. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16093. if (texture.width % 4 !== 0) {
  16094. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16095. }
  16096. // Data are known to be in +X +Y +Z -X -Y -Z
  16097. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16098. var faceData = data[faceIndex];
  16099. if (compression) {
  16100. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16101. }
  16102. else {
  16103. if (needConversion) {
  16104. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16105. }
  16106. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16107. }
  16108. }
  16109. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16110. if (isPot && texture.generateMipMaps && level === 0) {
  16111. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16112. }
  16113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16114. // this.resetTextureCache();
  16115. texture.isReady = true;
  16116. };
  16117. /**
  16118. * Creates a new raw cube texture
  16119. * @param data defines the array of data to use to create each face
  16120. * @param size defines the size of the textures
  16121. * @param format defines the format of the data
  16122. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16123. * @param generateMipMaps defines if the engine should generate the mip levels
  16124. * @param invertY defines if data must be stored with Y axis inverted
  16125. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16126. * @param compression defines the compression used (null by default)
  16127. * @returns the cube texture as an InternalTexture
  16128. */
  16129. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16130. if (compression === void 0) { compression = null; }
  16131. var gl = this._gl;
  16132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16133. texture.isCube = true;
  16134. texture.generateMipMaps = generateMipMaps;
  16135. texture.format = format;
  16136. texture.type = type;
  16137. if (!this._doNotHandleContextLost) {
  16138. texture._bufferViewArray = data;
  16139. }
  16140. var textureType = this._getWebGLTextureType(type);
  16141. var internalFormat = this._getInternalFormat(format);
  16142. if (internalFormat === gl.RGB) {
  16143. internalFormat = gl.RGBA;
  16144. }
  16145. var width = size;
  16146. var height = width;
  16147. texture.width = width;
  16148. texture.height = height;
  16149. // Double check on POT to generate Mips.
  16150. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16151. if (!isPot) {
  16152. generateMipMaps = false;
  16153. }
  16154. // Upload data if needed. The texture won't be ready until then.
  16155. if (data) {
  16156. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16157. }
  16158. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16159. // Filters
  16160. if (data && generateMipMaps) {
  16161. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16162. }
  16163. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16166. }
  16167. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16170. }
  16171. else {
  16172. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16173. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16174. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16175. }
  16176. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16177. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16178. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16179. return texture;
  16180. };
  16181. /**
  16182. * Creates a new raw cube texture from a specified url
  16183. * @param url defines the url where the data is located
  16184. * @param scene defines the current scene
  16185. * @param size defines the size of the textures
  16186. * @param format defines the format of the data
  16187. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16188. * @param noMipmap defines if the engine should avoid generating the mip levels
  16189. * @param callback defines a callback used to extract texture data from loaded data
  16190. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16191. * @param onLoad defines a callback called when texture is loaded
  16192. * @param onError defines a callback called if there is an error
  16193. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16194. * @param invertY defines if data must be stored with Y axis inverted
  16195. * @returns the cube texture as an InternalTexture
  16196. */
  16197. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16198. var _this = this;
  16199. if (onLoad === void 0) { onLoad = null; }
  16200. if (onError === void 0) { onError = null; }
  16201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16202. if (invertY === void 0) { invertY = false; }
  16203. var gl = this._gl;
  16204. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16205. scene._addPendingData(texture);
  16206. texture.url = url;
  16207. this._internalTexturesCache.push(texture);
  16208. var onerror = function (request, exception) {
  16209. scene._removePendingData(texture);
  16210. if (onError && request) {
  16211. onError(request.status + " " + request.statusText, exception);
  16212. }
  16213. };
  16214. var internalCallback = function (data) {
  16215. var width = texture.width;
  16216. var faceDataArrays = callback(data);
  16217. if (!faceDataArrays) {
  16218. return;
  16219. }
  16220. if (mipmapGenerator) {
  16221. var textureType = _this._getWebGLTextureType(type);
  16222. var internalFormat = _this._getInternalFormat(format);
  16223. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16224. var needConversion = false;
  16225. if (internalFormat === gl.RGB) {
  16226. internalFormat = gl.RGBA;
  16227. needConversion = true;
  16228. }
  16229. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16230. _this._unpackFlipY(false);
  16231. var mipData = mipmapGenerator(faceDataArrays);
  16232. for (var level = 0; level < mipData.length; level++) {
  16233. var mipSize = width >> level;
  16234. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16235. var mipFaceData = mipData[level][faceIndex];
  16236. if (needConversion) {
  16237. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16238. }
  16239. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16240. }
  16241. }
  16242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16243. }
  16244. else {
  16245. texture.generateMipMaps = !noMipmap;
  16246. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16247. }
  16248. texture.isReady = true;
  16249. // this.resetTextureCache();
  16250. scene._removePendingData(texture);
  16251. if (onLoad) {
  16252. onLoad();
  16253. }
  16254. };
  16255. this._loadFile(url, function (data) {
  16256. internalCallback(data);
  16257. }, undefined, scene.database, true, onerror);
  16258. return texture;
  16259. };
  16260. ;
  16261. /**
  16262. * Update a raw 3D texture
  16263. * @param texture defines the texture to update
  16264. * @param data defines the data to store
  16265. * @param format defines the data format
  16266. * @param invertY defines if data must be stored with Y axis inverted
  16267. * @param compression defines the used compression (can be null)
  16268. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16269. */
  16270. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16271. if (compression === void 0) { compression = null; }
  16272. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16273. var internalType = this._getWebGLTextureType(textureType);
  16274. var internalFormat = this._getInternalFormat(format);
  16275. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16276. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16277. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16278. if (!this._doNotHandleContextLost) {
  16279. texture._bufferView = data;
  16280. texture.format = format;
  16281. texture.invertY = invertY;
  16282. texture._compression = compression;
  16283. }
  16284. if (texture.width % 4 !== 0) {
  16285. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16286. }
  16287. if (compression && data) {
  16288. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16289. }
  16290. else {
  16291. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16292. }
  16293. if (texture.generateMipMaps) {
  16294. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16295. }
  16296. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16297. // this.resetTextureCache();
  16298. texture.isReady = true;
  16299. };
  16300. /**
  16301. * Creates a new raw 3D texture
  16302. * @param data defines the data used to create the texture
  16303. * @param width defines the width of the texture
  16304. * @param height defines the height of the texture
  16305. * @param depth defines the depth of the texture
  16306. * @param format defines the format of the texture
  16307. * @param generateMipMaps defines if the engine must generate mip levels
  16308. * @param invertY defines if data must be stored with Y axis inverted
  16309. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16310. * @param compression defines the compressed used (can be null)
  16311. * @param textureType defines the compressed used (can be null)
  16312. * @returns a new raw 3D texture (stored in an InternalTexture)
  16313. */
  16314. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16315. if (compression === void 0) { compression = null; }
  16316. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16317. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16318. texture.baseWidth = width;
  16319. texture.baseHeight = height;
  16320. texture.baseDepth = depth;
  16321. texture.width = width;
  16322. texture.height = height;
  16323. texture.depth = depth;
  16324. texture.format = format;
  16325. texture.type = textureType;
  16326. texture.generateMipMaps = generateMipMaps;
  16327. texture.samplingMode = samplingMode;
  16328. texture.is3D = true;
  16329. if (!this._doNotHandleContextLost) {
  16330. texture._bufferView = data;
  16331. }
  16332. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16333. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16334. // Filters
  16335. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16336. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16337. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16338. if (generateMipMaps) {
  16339. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16340. }
  16341. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16342. this._internalTexturesCache.push(texture);
  16343. return texture;
  16344. };
  16345. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16346. var gl = this._gl;
  16347. if (!gl) {
  16348. return;
  16349. }
  16350. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16353. if (!noMipmap && !isCompressed) {
  16354. gl.generateMipmap(gl.TEXTURE_2D);
  16355. }
  16356. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16357. // this.resetTextureCache();
  16358. if (scene) {
  16359. scene._removePendingData(texture);
  16360. }
  16361. texture.onLoadedObservable.notifyObservers(texture);
  16362. texture.onLoadedObservable.clear();
  16363. };
  16364. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16365. var _this = this;
  16366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16367. var maxTextureSize = this.getCaps().maxTextureSize;
  16368. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16369. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16370. var gl = this._gl;
  16371. if (!gl) {
  16372. return;
  16373. }
  16374. if (!texture._webGLTexture) {
  16375. // this.resetTextureCache();
  16376. if (scene) {
  16377. scene._removePendingData(texture);
  16378. }
  16379. return;
  16380. }
  16381. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16382. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16383. texture.baseWidth = width;
  16384. texture.baseHeight = height;
  16385. texture.width = potWidth;
  16386. texture.height = potHeight;
  16387. texture.isReady = true;
  16388. if (processFunction(potWidth, potHeight, function () {
  16389. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16390. })) {
  16391. // Returning as texture needs extra async steps
  16392. return;
  16393. }
  16394. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16395. };
  16396. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16397. // Create new RGBA data container.
  16398. var rgbaData;
  16399. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16400. rgbaData = new Float32Array(width * height * 4);
  16401. }
  16402. else {
  16403. rgbaData = new Uint32Array(width * height * 4);
  16404. }
  16405. // Convert each pixel.
  16406. for (var x = 0; x < width; x++) {
  16407. for (var y = 0; y < height; y++) {
  16408. var index = (y * width + x) * 3;
  16409. var newIndex = (y * width + x) * 4;
  16410. // Map Old Value to new value.
  16411. rgbaData[newIndex + 0] = rgbData[index + 0];
  16412. rgbaData[newIndex + 1] = rgbData[index + 1];
  16413. rgbaData[newIndex + 2] = rgbData[index + 2];
  16414. // Add fully opaque alpha channel.
  16415. rgbaData[newIndex + 3] = 1;
  16416. }
  16417. }
  16418. return rgbaData;
  16419. };
  16420. /** @hidden */
  16421. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16422. var gl = this._gl;
  16423. if (texture._framebuffer) {
  16424. gl.deleteFramebuffer(texture._framebuffer);
  16425. texture._framebuffer = null;
  16426. }
  16427. if (texture._depthStencilBuffer) {
  16428. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16429. texture._depthStencilBuffer = null;
  16430. }
  16431. if (texture._MSAAFramebuffer) {
  16432. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16433. texture._MSAAFramebuffer = null;
  16434. }
  16435. if (texture._MSAARenderBuffer) {
  16436. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16437. texture._MSAARenderBuffer = null;
  16438. }
  16439. };
  16440. /** @hidden */
  16441. Engine.prototype._releaseTexture = function (texture) {
  16442. var gl = this._gl;
  16443. this._releaseFramebufferObjects(texture);
  16444. gl.deleteTexture(texture._webGLTexture);
  16445. // Unbind channels
  16446. this.unbindAllTextures();
  16447. var index = this._internalTexturesCache.indexOf(texture);
  16448. if (index !== -1) {
  16449. this._internalTexturesCache.splice(index, 1);
  16450. }
  16451. // Integrated fixed lod samplers.
  16452. if (texture._lodTextureHigh) {
  16453. texture._lodTextureHigh.dispose();
  16454. }
  16455. if (texture._lodTextureMid) {
  16456. texture._lodTextureMid.dispose();
  16457. }
  16458. if (texture._lodTextureLow) {
  16459. texture._lodTextureLow.dispose();
  16460. }
  16461. // Set output texture of post process to null if the texture has been released/disposed
  16462. this.scenes.forEach(function (scene) {
  16463. scene.postProcesses.forEach(function (postProcess) {
  16464. if (postProcess._outputTexture == texture) {
  16465. postProcess._outputTexture = null;
  16466. }
  16467. });
  16468. scene.cameras.forEach(function (camera) {
  16469. camera._postProcesses.forEach(function (postProcess) {
  16470. if (postProcess) {
  16471. if (postProcess._outputTexture == texture) {
  16472. postProcess._outputTexture = null;
  16473. }
  16474. }
  16475. });
  16476. });
  16477. });
  16478. };
  16479. Engine.prototype.setProgram = function (program) {
  16480. if (this._currentProgram !== program) {
  16481. this._gl.useProgram(program);
  16482. this._currentProgram = program;
  16483. }
  16484. };
  16485. /**
  16486. * Binds an effect to the webGL context
  16487. * @param effect defines the effect to bind
  16488. */
  16489. Engine.prototype.bindSamplers = function (effect) {
  16490. this.setProgram(effect.getProgram());
  16491. var samplers = effect.getSamplers();
  16492. for (var index = 0; index < samplers.length; index++) {
  16493. var uniform = effect.getUniform(samplers[index]);
  16494. if (uniform) {
  16495. this._boundUniforms[index] = uniform;
  16496. }
  16497. }
  16498. this._currentEffect = null;
  16499. };
  16500. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16501. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16502. return;
  16503. }
  16504. // Remove
  16505. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16506. // Bind last to it
  16507. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16508. // Bind to dummy
  16509. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16510. };
  16511. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16512. if (!internalTexture) {
  16513. return -1;
  16514. }
  16515. internalTexture._initialSlot = channel;
  16516. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16517. if (channel !== internalTexture._designatedSlot) {
  16518. this._textureCollisions.addCount(1, false);
  16519. }
  16520. }
  16521. else {
  16522. if (channel !== internalTexture._designatedSlot) {
  16523. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16524. return internalTexture._designatedSlot;
  16525. }
  16526. else {
  16527. // No slot for this texture, let's pick a new one (if we find a free slot)
  16528. if (this._nextFreeTextureSlots.length) {
  16529. return this._nextFreeTextureSlots[0];
  16530. }
  16531. // We need to recycle the oldest bound texture, sorry.
  16532. this._textureCollisions.addCount(1, false);
  16533. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16534. }
  16535. }
  16536. }
  16537. return channel;
  16538. };
  16539. Engine.prototype._linkTrackers = function (previous, next) {
  16540. previous.next = next;
  16541. next.previous = previous;
  16542. };
  16543. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16544. var currentSlot = internalTexture._designatedSlot;
  16545. if (currentSlot === -1) {
  16546. return -1;
  16547. }
  16548. internalTexture._designatedSlot = -1;
  16549. if (this.disableTextureBindingOptimization) {
  16550. return -1;
  16551. }
  16552. // Remove from bound list
  16553. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16554. // Free the slot
  16555. this._boundTexturesCache[currentSlot] = null;
  16556. this._nextFreeTextureSlots.push(currentSlot);
  16557. return currentSlot;
  16558. };
  16559. Engine.prototype._activateCurrentTexture = function () {
  16560. if (this._currentTextureChannel !== this._activeChannel) {
  16561. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16562. this._currentTextureChannel = this._activeChannel;
  16563. }
  16564. };
  16565. /** @hidden */
  16566. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16567. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16568. if (force === void 0) { force = false; }
  16569. var wasPreviouslyBound = false;
  16570. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16571. this._activeChannel = texture._designatedSlot;
  16572. }
  16573. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16574. var isTextureForRendering = texture && texture._initialSlot > -1;
  16575. if (currentTextureBound !== texture || force) {
  16576. if (currentTextureBound) {
  16577. this._removeDesignatedSlot(currentTextureBound);
  16578. }
  16579. this._activateCurrentTexture();
  16580. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16581. this._boundTexturesCache[this._activeChannel] = texture;
  16582. if (texture) {
  16583. if (!this.disableTextureBindingOptimization) {
  16584. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16585. if (slotIndex > -1) {
  16586. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16587. }
  16588. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16589. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16590. }
  16591. texture._designatedSlot = this._activeChannel;
  16592. }
  16593. }
  16594. else if (forTextureDataUpdate) {
  16595. wasPreviouslyBound = true;
  16596. this._activateCurrentTexture();
  16597. }
  16598. if (isTextureForRendering && !forTextureDataUpdate) {
  16599. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16600. }
  16601. return wasPreviouslyBound;
  16602. };
  16603. /** @hidden */
  16604. Engine.prototype._bindTexture = function (channel, texture) {
  16605. if (channel < 0) {
  16606. return;
  16607. }
  16608. if (texture) {
  16609. channel = this._getCorrectTextureChannel(channel, texture);
  16610. }
  16611. this._activeChannel = channel;
  16612. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16613. };
  16614. /**
  16615. * Sets a texture to the webGL context from a postprocess
  16616. * @param channel defines the channel to use
  16617. * @param postProcess defines the source postprocess
  16618. */
  16619. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16620. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16621. };
  16622. /**
  16623. * Binds the output of the passed in post process to the texture channel specified
  16624. * @param channel The channel the texture should be bound to
  16625. * @param postProcess The post process which's output should be bound
  16626. */
  16627. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16628. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16629. };
  16630. /**
  16631. * Unbind all textures from the webGL context
  16632. */
  16633. Engine.prototype.unbindAllTextures = function () {
  16634. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16635. this._activeChannel = channel;
  16636. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16637. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16638. if (this.webGLVersion > 1) {
  16639. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16640. }
  16641. }
  16642. };
  16643. /**
  16644. * Sets a texture to the according uniform.
  16645. * @param channel The texture channel
  16646. * @param uniform The uniform to set
  16647. * @param texture The texture to apply
  16648. */
  16649. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16650. if (channel < 0) {
  16651. return;
  16652. }
  16653. if (uniform) {
  16654. this._boundUniforms[channel] = uniform;
  16655. }
  16656. this._setTexture(channel, texture);
  16657. };
  16658. /**
  16659. * Sets a depth stencil texture from a render target to the according uniform.
  16660. * @param channel The texture channel
  16661. * @param uniform The uniform to set
  16662. * @param texture The render target texture containing the depth stencil texture to apply
  16663. */
  16664. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16665. if (channel < 0) {
  16666. return;
  16667. }
  16668. if (uniform) {
  16669. this._boundUniforms[channel] = uniform;
  16670. }
  16671. if (!texture || !texture.depthStencilTexture) {
  16672. this._setTexture(channel, null);
  16673. }
  16674. else {
  16675. this._setTexture(channel, texture, false, true);
  16676. }
  16677. };
  16678. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16679. var uniform = this._boundUniforms[sourceSlot];
  16680. if (uniform._currentState === destination) {
  16681. return;
  16682. }
  16683. this._gl.uniform1i(uniform, destination);
  16684. uniform._currentState = destination;
  16685. };
  16686. Engine.prototype._getTextureWrapMode = function (mode) {
  16687. switch (mode) {
  16688. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16689. return this._gl.REPEAT;
  16690. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16691. return this._gl.CLAMP_TO_EDGE;
  16692. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16693. return this._gl.MIRRORED_REPEAT;
  16694. }
  16695. return this._gl.REPEAT;
  16696. };
  16697. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16698. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16699. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16700. // Not ready?
  16701. if (!texture) {
  16702. if (this._boundTexturesCache[channel] != null) {
  16703. this._activeChannel = channel;
  16704. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16705. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16706. if (this.webGLVersion > 1) {
  16707. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16708. }
  16709. }
  16710. return false;
  16711. }
  16712. // Video
  16713. if (texture.video) {
  16714. this._activeChannel = channel;
  16715. texture.update();
  16716. }
  16717. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16718. texture.delayLoad();
  16719. return false;
  16720. }
  16721. var internalTexture;
  16722. if (depthStencilTexture) {
  16723. internalTexture = texture.depthStencilTexture;
  16724. }
  16725. else if (texture.isReady()) {
  16726. internalTexture = texture.getInternalTexture();
  16727. }
  16728. else if (texture.isCube) {
  16729. internalTexture = this.emptyCubeTexture;
  16730. }
  16731. else if (texture.is3D) {
  16732. internalTexture = this.emptyTexture3D;
  16733. }
  16734. else {
  16735. internalTexture = this.emptyTexture;
  16736. }
  16737. if (!isPartOfTextureArray) {
  16738. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16739. }
  16740. var needToBind = true;
  16741. if (this._boundTexturesCache[channel] === internalTexture) {
  16742. this._moveBoundTextureOnTop(internalTexture);
  16743. if (!isPartOfTextureArray) {
  16744. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16745. }
  16746. needToBind = false;
  16747. }
  16748. this._activeChannel = channel;
  16749. if (internalTexture && internalTexture.is3D) {
  16750. if (needToBind) {
  16751. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16752. }
  16753. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16754. internalTexture._cachedWrapU = texture.wrapU;
  16755. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16756. }
  16757. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16758. internalTexture._cachedWrapV = texture.wrapV;
  16759. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16760. }
  16761. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16762. internalTexture._cachedWrapR = texture.wrapR;
  16763. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16764. }
  16765. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16766. }
  16767. else if (internalTexture && internalTexture.isCube) {
  16768. if (needToBind) {
  16769. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16770. }
  16771. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16772. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16773. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16774. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16775. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16776. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16777. }
  16778. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16779. }
  16780. else {
  16781. if (needToBind) {
  16782. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16783. }
  16784. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16785. internalTexture._cachedWrapU = texture.wrapU;
  16786. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16787. }
  16788. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16789. internalTexture._cachedWrapV = texture.wrapV;
  16790. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16791. }
  16792. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16793. }
  16794. return true;
  16795. };
  16796. /**
  16797. * Sets an array of texture to the webGL context
  16798. * @param channel defines the channel where the texture array must be set
  16799. * @param uniform defines the associated uniform location
  16800. * @param textures defines the array of textures to bind
  16801. */
  16802. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16803. if (channel < 0 || !uniform) {
  16804. return;
  16805. }
  16806. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16807. this._textureUnits = new Int32Array(textures.length);
  16808. }
  16809. for (var i = 0; i < textures.length; i++) {
  16810. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16811. }
  16812. this._gl.uniform1iv(uniform, this._textureUnits);
  16813. for (var index = 0; index < textures.length; index++) {
  16814. this._setTexture(this._textureUnits[index], textures[index], true);
  16815. }
  16816. };
  16817. /** @hidden */
  16818. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16819. var internalTexture = texture.getInternalTexture();
  16820. if (!internalTexture) {
  16821. return;
  16822. }
  16823. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16824. var value = texture.anisotropicFilteringLevel;
  16825. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16826. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16827. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16828. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16829. }
  16830. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16831. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16832. internalTexture._cachedAnisotropicFilteringLevel = value;
  16833. }
  16834. };
  16835. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16836. this._bindTextureDirectly(target, texture, true, true);
  16837. this._gl.texParameterf(target, parameter, value);
  16838. };
  16839. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16840. if (texture) {
  16841. this._bindTextureDirectly(target, texture, true, true);
  16842. }
  16843. this._gl.texParameteri(target, parameter, value);
  16844. };
  16845. /**
  16846. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16847. * @param x defines the x coordinate of the rectangle where pixels must be read
  16848. * @param y defines the y coordinate of the rectangle where pixels must be read
  16849. * @param width defines the width of the rectangle where pixels must be read
  16850. * @param height defines the height of the rectangle where pixels must be read
  16851. * @returns a Uint8Array containing RGBA colors
  16852. */
  16853. Engine.prototype.readPixels = function (x, y, width, height) {
  16854. var data = new Uint8Array(height * width * 4);
  16855. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16856. return data;
  16857. };
  16858. /**
  16859. * Add an externaly attached data from its key.
  16860. * This method call will fail and return false, if such key already exists.
  16861. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16862. * @param key the unique key that identifies the data
  16863. * @param data the data object to associate to the key for this Engine instance
  16864. * @return true if no such key were already present and the data was added successfully, false otherwise
  16865. */
  16866. Engine.prototype.addExternalData = function (key, data) {
  16867. if (!this._externalData) {
  16868. this._externalData = new BABYLON.StringDictionary();
  16869. }
  16870. return this._externalData.add(key, data);
  16871. };
  16872. /**
  16873. * Get an externaly attached data from its key
  16874. * @param key the unique key that identifies the data
  16875. * @return the associated data, if present (can be null), or undefined if not present
  16876. */
  16877. Engine.prototype.getExternalData = function (key) {
  16878. if (!this._externalData) {
  16879. this._externalData = new BABYLON.StringDictionary();
  16880. }
  16881. return this._externalData.get(key);
  16882. };
  16883. /**
  16884. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16885. * @param key the unique key that identifies the data
  16886. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16887. * @return the associated data, can be null if the factory returned null.
  16888. */
  16889. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16890. if (!this._externalData) {
  16891. this._externalData = new BABYLON.StringDictionary();
  16892. }
  16893. return this._externalData.getOrAddWithFactory(key, factory);
  16894. };
  16895. /**
  16896. * Remove an externaly attached data from the Engine instance
  16897. * @param key the unique key that identifies the data
  16898. * @return true if the data was successfully removed, false if it doesn't exist
  16899. */
  16900. Engine.prototype.removeExternalData = function (key) {
  16901. if (!this._externalData) {
  16902. this._externalData = new BABYLON.StringDictionary();
  16903. }
  16904. return this._externalData.remove(key);
  16905. };
  16906. /**
  16907. * Unbind all vertex attributes from the webGL context
  16908. */
  16909. Engine.prototype.unbindAllAttributes = function () {
  16910. if (this._mustWipeVertexAttributes) {
  16911. this._mustWipeVertexAttributes = false;
  16912. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16913. this._gl.disableVertexAttribArray(i);
  16914. this._vertexAttribArraysEnabled[i] = false;
  16915. this._currentBufferPointers[i].active = false;
  16916. }
  16917. return;
  16918. }
  16919. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16920. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16921. continue;
  16922. }
  16923. this._gl.disableVertexAttribArray(i);
  16924. this._vertexAttribArraysEnabled[i] = false;
  16925. this._currentBufferPointers[i].active = false;
  16926. }
  16927. };
  16928. /**
  16929. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16930. */
  16931. Engine.prototype.releaseEffects = function () {
  16932. for (var name in this._compiledEffects) {
  16933. this._deleteProgram(this._compiledEffects[name]._program);
  16934. }
  16935. this._compiledEffects = {};
  16936. };
  16937. /**
  16938. * Dispose and release all associated resources
  16939. */
  16940. Engine.prototype.dispose = function () {
  16941. this.hideLoadingUI();
  16942. this.stopRenderLoop();
  16943. // Release postProcesses
  16944. while (this.postProcesses.length) {
  16945. this.postProcesses[0].dispose();
  16946. }
  16947. // Empty texture
  16948. if (this._emptyTexture) {
  16949. this._releaseTexture(this._emptyTexture);
  16950. this._emptyTexture = null;
  16951. }
  16952. if (this._emptyCubeTexture) {
  16953. this._releaseTexture(this._emptyCubeTexture);
  16954. this._emptyCubeTexture = null;
  16955. }
  16956. // Rescale PP
  16957. if (this._rescalePostProcess) {
  16958. this._rescalePostProcess.dispose();
  16959. }
  16960. // Release scenes
  16961. while (this.scenes.length) {
  16962. this.scenes[0].dispose();
  16963. }
  16964. // Release audio engine
  16965. if (Engine.audioEngine) {
  16966. Engine.audioEngine.dispose();
  16967. }
  16968. // Release effects
  16969. this.releaseEffects();
  16970. // Unbind
  16971. this.unbindAllAttributes();
  16972. this._boundUniforms = [];
  16973. if (this._dummyFramebuffer) {
  16974. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16975. }
  16976. //WebVR
  16977. this.disableVR();
  16978. // Events
  16979. if (BABYLON.Tools.IsWindowObjectExist()) {
  16980. window.removeEventListener("blur", this._onBlur);
  16981. window.removeEventListener("focus", this._onFocus);
  16982. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16983. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16984. if (this._renderingCanvas) {
  16985. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16986. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16987. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16988. if (!this._doNotHandleContextLost) {
  16989. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16990. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16991. }
  16992. }
  16993. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16994. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16995. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16996. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16997. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16998. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16999. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17000. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17001. if (this._onVrDisplayConnect) {
  17002. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17003. if (this._onVrDisplayDisconnect) {
  17004. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17005. }
  17006. if (this._onVrDisplayPresentChange) {
  17007. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17008. }
  17009. this._onVrDisplayConnect = null;
  17010. this._onVrDisplayDisconnect = null;
  17011. }
  17012. }
  17013. // Remove from Instances
  17014. var index = Engine.Instances.indexOf(this);
  17015. if (index >= 0) {
  17016. Engine.Instances.splice(index, 1);
  17017. }
  17018. this._workingCanvas = null;
  17019. this._workingContext = null;
  17020. this._currentBufferPointers = [];
  17021. this._renderingCanvas = null;
  17022. this._currentProgram = null;
  17023. this._bindedRenderFunction = null;
  17024. this.onResizeObservable.clear();
  17025. this.onCanvasBlurObservable.clear();
  17026. this.onCanvasFocusObservable.clear();
  17027. this.onCanvasPointerOutObservable.clear();
  17028. this.onBeginFrameObservable.clear();
  17029. this.onEndFrameObservable.clear();
  17030. BABYLON.Effect.ResetCache();
  17031. // Abort active requests
  17032. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17033. var request = _a[_i];
  17034. request.abort();
  17035. }
  17036. };
  17037. // Loading screen
  17038. /**
  17039. * Display the loading screen
  17040. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17041. */
  17042. Engine.prototype.displayLoadingUI = function () {
  17043. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17044. return;
  17045. }
  17046. var loadingScreen = this.loadingScreen;
  17047. if (loadingScreen) {
  17048. loadingScreen.displayLoadingUI();
  17049. }
  17050. };
  17051. /**
  17052. * Hide the loading screen
  17053. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17054. */
  17055. Engine.prototype.hideLoadingUI = function () {
  17056. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17057. return;
  17058. }
  17059. var loadingScreen = this.loadingScreen;
  17060. if (loadingScreen) {
  17061. loadingScreen.hideLoadingUI();
  17062. }
  17063. };
  17064. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17065. /**
  17066. * Gets the current loading screen object
  17067. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17068. */
  17069. get: function () {
  17070. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17071. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17072. return this._loadingScreen;
  17073. },
  17074. /**
  17075. * Sets the current loading screen object
  17076. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17077. */
  17078. set: function (loadingScreen) {
  17079. this._loadingScreen = loadingScreen;
  17080. },
  17081. enumerable: true,
  17082. configurable: true
  17083. });
  17084. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17085. /**
  17086. * Sets the current loading screen text
  17087. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17088. */
  17089. set: function (text) {
  17090. this.loadingScreen.loadingUIText = text;
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17096. /**
  17097. * Sets the current loading screen background color
  17098. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17099. */
  17100. set: function (color) {
  17101. this.loadingScreen.loadingUIBackgroundColor = color;
  17102. },
  17103. enumerable: true,
  17104. configurable: true
  17105. });
  17106. /**
  17107. * Attach a new callback raised when context lost event is fired
  17108. * @param callback defines the callback to call
  17109. */
  17110. Engine.prototype.attachContextLostEvent = function (callback) {
  17111. if (this._renderingCanvas) {
  17112. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17113. }
  17114. };
  17115. /**
  17116. * Attach a new callback raised when context restored event is fired
  17117. * @param callback defines the callback to call
  17118. */
  17119. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17120. if (this._renderingCanvas) {
  17121. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17122. }
  17123. };
  17124. /**
  17125. * Gets the source code of the vertex shader associated with a specific webGL program
  17126. * @param program defines the program to use
  17127. * @returns a string containing the source code of the vertex shader associated with the program
  17128. */
  17129. Engine.prototype.getVertexShaderSource = function (program) {
  17130. var shaders = this._gl.getAttachedShaders(program);
  17131. if (!shaders) {
  17132. return null;
  17133. }
  17134. return this._gl.getShaderSource(shaders[0]);
  17135. };
  17136. /**
  17137. * Gets the source code of the fragment shader associated with a specific webGL program
  17138. * @param program defines the program to use
  17139. * @returns a string containing the source code of the fragment shader associated with the program
  17140. */
  17141. Engine.prototype.getFragmentShaderSource = function (program) {
  17142. var shaders = this._gl.getAttachedShaders(program);
  17143. if (!shaders) {
  17144. return null;
  17145. }
  17146. return this._gl.getShaderSource(shaders[1]);
  17147. };
  17148. /**
  17149. * Get the current error code of the webGL context
  17150. * @returns the error code
  17151. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17152. */
  17153. Engine.prototype.getError = function () {
  17154. return this._gl.getError();
  17155. };
  17156. // FPS
  17157. /**
  17158. * Gets the current framerate
  17159. * @returns a number representing the framerate
  17160. */
  17161. Engine.prototype.getFps = function () {
  17162. return this._fps;
  17163. };
  17164. /**
  17165. * Gets the time spent between current and previous frame
  17166. * @returns a number representing the delta time in ms
  17167. */
  17168. Engine.prototype.getDeltaTime = function () {
  17169. return this._deltaTime;
  17170. };
  17171. Engine.prototype._measureFps = function () {
  17172. this._performanceMonitor.sampleFrame();
  17173. this._fps = this._performanceMonitor.averageFPS;
  17174. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17175. };
  17176. /** @hidden */
  17177. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17178. if (faceIndex === void 0) { faceIndex = -1; }
  17179. if (level === void 0) { level = 0; }
  17180. var gl = this._gl;
  17181. if (!this._dummyFramebuffer) {
  17182. var dummy = gl.createFramebuffer();
  17183. if (!dummy) {
  17184. throw new Error("Unable to create dummy framebuffer");
  17185. }
  17186. this._dummyFramebuffer = dummy;
  17187. }
  17188. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17189. if (faceIndex > -1) {
  17190. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17191. }
  17192. else {
  17193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17194. }
  17195. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17196. var buffer;
  17197. switch (readType) {
  17198. case gl.UNSIGNED_BYTE:
  17199. buffer = new Uint8Array(4 * width * height);
  17200. readType = gl.UNSIGNED_BYTE;
  17201. break;
  17202. default:
  17203. buffer = new Float32Array(4 * width * height);
  17204. readType = gl.FLOAT;
  17205. break;
  17206. }
  17207. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17208. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17209. return buffer;
  17210. };
  17211. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17212. if (this._webGLVersion > 1) {
  17213. return this._caps.colorBufferFloat;
  17214. }
  17215. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17216. };
  17217. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17218. if (this._webGLVersion > 1) {
  17219. return this._caps.colorBufferFloat;
  17220. }
  17221. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17222. };
  17223. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17224. Engine.prototype._canRenderToFramebuffer = function (type) {
  17225. var gl = this._gl;
  17226. //clear existing errors
  17227. while (gl.getError() !== gl.NO_ERROR) { }
  17228. var successful = true;
  17229. var texture = gl.createTexture();
  17230. gl.bindTexture(gl.TEXTURE_2D, texture);
  17231. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17234. var fb = gl.createFramebuffer();
  17235. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17236. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17237. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17238. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17239. successful = successful && (gl.getError() === gl.NO_ERROR);
  17240. //try render by clearing frame buffer's color buffer
  17241. if (successful) {
  17242. gl.clear(gl.COLOR_BUFFER_BIT);
  17243. successful = successful && (gl.getError() === gl.NO_ERROR);
  17244. }
  17245. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17246. if (successful) {
  17247. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17248. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17249. var readFormat = gl.RGBA;
  17250. var readType = gl.UNSIGNED_BYTE;
  17251. var buffer = new Uint8Array(4);
  17252. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17253. successful = successful && (gl.getError() === gl.NO_ERROR);
  17254. }
  17255. //clean up
  17256. gl.deleteTexture(texture);
  17257. gl.deleteFramebuffer(fb);
  17258. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17259. //clear accumulated errors
  17260. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17261. return successful;
  17262. };
  17263. /** @hidden */
  17264. Engine.prototype._getWebGLTextureType = function (type) {
  17265. if (type === Engine.TEXTURETYPE_FLOAT) {
  17266. return this._gl.FLOAT;
  17267. }
  17268. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17269. // Add Half Float Constant.
  17270. return this._gl.HALF_FLOAT_OES;
  17271. }
  17272. return this._gl.UNSIGNED_BYTE;
  17273. };
  17274. ;
  17275. Engine.prototype._getInternalFormat = function (format) {
  17276. var internalFormat = this._gl.RGBA;
  17277. switch (format) {
  17278. case Engine.TEXTUREFORMAT_ALPHA:
  17279. internalFormat = this._gl.ALPHA;
  17280. break;
  17281. case Engine.TEXTUREFORMAT_LUMINANCE:
  17282. internalFormat = this._gl.LUMINANCE;
  17283. break;
  17284. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17285. internalFormat = this._gl.LUMINANCE_ALPHA;
  17286. break;
  17287. case Engine.TEXTUREFORMAT_RGB:
  17288. internalFormat = this._gl.RGB;
  17289. break;
  17290. case Engine.TEXTUREFORMAT_RGBA:
  17291. internalFormat = this._gl.RGBA;
  17292. break;
  17293. case Engine.TEXTUREFORMAT_R:
  17294. internalFormat = this._gl.RED;
  17295. break;
  17296. case Engine.TEXTUREFORMAT_RG:
  17297. internalFormat = this._gl.RG;
  17298. break;
  17299. }
  17300. return internalFormat;
  17301. };
  17302. /** @hidden */
  17303. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17304. if (this._webGLVersion === 1) {
  17305. if (format !== undefined) {
  17306. switch (format) {
  17307. case Engine.TEXTUREFORMAT_LUMINANCE:
  17308. return this._gl.LUMINANCE;
  17309. case Engine.TEXTUREFORMAT_ALPHA:
  17310. return this._gl.ALPHA;
  17311. }
  17312. }
  17313. return this._gl.RGBA;
  17314. }
  17315. if (type === Engine.TEXTURETYPE_FLOAT) {
  17316. if (format !== undefined) {
  17317. switch (format) {
  17318. case Engine.TEXTUREFORMAT_R:
  17319. return this._gl.R32F;
  17320. case Engine.TEXTUREFORMAT_RG:
  17321. return this._gl.RG32F;
  17322. case Engine.TEXTUREFORMAT_RGB:
  17323. return this._gl.RGB32F;
  17324. }
  17325. }
  17326. return this._gl.RGBA32F;
  17327. }
  17328. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17329. if (format) {
  17330. switch (format) {
  17331. case Engine.TEXTUREFORMAT_R:
  17332. return this._gl.R16F;
  17333. case Engine.TEXTUREFORMAT_RG:
  17334. return this._gl.RG16F;
  17335. case Engine.TEXTUREFORMAT_RGB:
  17336. return this._gl.RGB16F;
  17337. }
  17338. }
  17339. return this._gl.RGBA16F;
  17340. }
  17341. if (format !== undefined) {
  17342. switch (format) {
  17343. case Engine.TEXTUREFORMAT_LUMINANCE:
  17344. return this._gl.LUMINANCE;
  17345. case Engine.TEXTUREFORMAT_RGB:
  17346. return this._gl.RGB;
  17347. case Engine.TEXTUREFORMAT_R:
  17348. return this._gl.R8;
  17349. case Engine.TEXTUREFORMAT_RG:
  17350. return this._gl.RG8;
  17351. case Engine.TEXTUREFORMAT_ALPHA:
  17352. return this._gl.ALPHA;
  17353. }
  17354. }
  17355. return this._gl.RGBA;
  17356. };
  17357. ;
  17358. /** @hidden */
  17359. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17360. if (type === Engine.TEXTURETYPE_FLOAT) {
  17361. return this._gl.RGBA32F;
  17362. }
  17363. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17364. return this._gl.RGBA16F;
  17365. }
  17366. return this._gl.RGBA8;
  17367. };
  17368. ;
  17369. /**
  17370. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17371. * @return the new query
  17372. */
  17373. Engine.prototype.createQuery = function () {
  17374. return this._gl.createQuery();
  17375. };
  17376. /**
  17377. * Delete and release a webGL query
  17378. * @param query defines the query to delete
  17379. * @return the current engine
  17380. */
  17381. Engine.prototype.deleteQuery = function (query) {
  17382. this._gl.deleteQuery(query);
  17383. return this;
  17384. };
  17385. /**
  17386. * Check if a given query has resolved and got its value
  17387. * @param query defines the query to check
  17388. * @returns true if the query got its value
  17389. */
  17390. Engine.prototype.isQueryResultAvailable = function (query) {
  17391. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17392. };
  17393. /**
  17394. * Gets the value of a given query
  17395. * @param query defines the query to check
  17396. * @returns the value of the query
  17397. */
  17398. Engine.prototype.getQueryResult = function (query) {
  17399. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17400. };
  17401. /**
  17402. * Initiates an occlusion query
  17403. * @param algorithmType defines the algorithm to use
  17404. * @param query defines the query to use
  17405. * @returns the current engine
  17406. * @see http://doc.babylonjs.com/features/occlusionquery
  17407. */
  17408. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17409. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17410. this._gl.beginQuery(glAlgorithm, query);
  17411. return this;
  17412. };
  17413. /**
  17414. * Ends an occlusion query
  17415. * @see http://doc.babylonjs.com/features/occlusionquery
  17416. * @param algorithmType defines the algorithm to use
  17417. * @returns the current engine
  17418. */
  17419. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17420. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17421. this._gl.endQuery(glAlgorithm);
  17422. return this;
  17423. };
  17424. /* Time queries */
  17425. Engine.prototype._createTimeQuery = function () {
  17426. var timerQuery = this._caps.timerQuery;
  17427. if (timerQuery.createQueryEXT) {
  17428. return timerQuery.createQueryEXT();
  17429. }
  17430. return this.createQuery();
  17431. };
  17432. Engine.prototype._deleteTimeQuery = function (query) {
  17433. var timerQuery = this._caps.timerQuery;
  17434. if (timerQuery.deleteQueryEXT) {
  17435. timerQuery.deleteQueryEXT(query);
  17436. return;
  17437. }
  17438. this.deleteQuery(query);
  17439. };
  17440. Engine.prototype._getTimeQueryResult = function (query) {
  17441. var timerQuery = this._caps.timerQuery;
  17442. if (timerQuery.getQueryObjectEXT) {
  17443. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17444. }
  17445. return this.getQueryResult(query);
  17446. };
  17447. Engine.prototype._getTimeQueryAvailability = function (query) {
  17448. var timerQuery = this._caps.timerQuery;
  17449. if (timerQuery.getQueryObjectEXT) {
  17450. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17451. }
  17452. return this.isQueryResultAvailable(query);
  17453. };
  17454. /**
  17455. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17456. * Please note that only one query can be issued at a time
  17457. * @returns a time token used to track the time span
  17458. */
  17459. Engine.prototype.startTimeQuery = function () {
  17460. var timerQuery = this._caps.timerQuery;
  17461. if (!timerQuery) {
  17462. return null;
  17463. }
  17464. var token = new BABYLON._TimeToken();
  17465. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17466. if (this._caps.canUseTimestampForTimerQuery) {
  17467. token._startTimeQuery = this._createTimeQuery();
  17468. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17469. }
  17470. else {
  17471. if (this._currentNonTimestampToken) {
  17472. return this._currentNonTimestampToken;
  17473. }
  17474. token._timeElapsedQuery = this._createTimeQuery();
  17475. if (timerQuery.beginQueryEXT) {
  17476. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17477. }
  17478. else {
  17479. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17480. }
  17481. this._currentNonTimestampToken = token;
  17482. }
  17483. return token;
  17484. };
  17485. /**
  17486. * Ends a time query
  17487. * @param token defines the token used to measure the time span
  17488. * @returns the time spent (in ns)
  17489. */
  17490. Engine.prototype.endTimeQuery = function (token) {
  17491. var timerQuery = this._caps.timerQuery;
  17492. if (!timerQuery || !token) {
  17493. return -1;
  17494. }
  17495. if (this._caps.canUseTimestampForTimerQuery) {
  17496. if (!token._startTimeQuery) {
  17497. return -1;
  17498. }
  17499. if (!token._endTimeQuery) {
  17500. token._endTimeQuery = this._createTimeQuery();
  17501. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17502. }
  17503. }
  17504. else if (!token._timeElapsedQueryEnded) {
  17505. if (!token._timeElapsedQuery) {
  17506. return -1;
  17507. }
  17508. if (timerQuery.endQueryEXT) {
  17509. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17510. }
  17511. else {
  17512. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17513. }
  17514. token._timeElapsedQueryEnded = true;
  17515. }
  17516. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17517. var available = false;
  17518. if (token._endTimeQuery) {
  17519. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17520. }
  17521. else if (token._timeElapsedQuery) {
  17522. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17523. }
  17524. if (available && !disjoint) {
  17525. var result = 0;
  17526. if (this._caps.canUseTimestampForTimerQuery) {
  17527. if (!token._startTimeQuery || !token._endTimeQuery) {
  17528. return -1;
  17529. }
  17530. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17531. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17532. result = timeEnd - timeStart;
  17533. this._deleteTimeQuery(token._startTimeQuery);
  17534. this._deleteTimeQuery(token._endTimeQuery);
  17535. token._startTimeQuery = null;
  17536. token._endTimeQuery = null;
  17537. }
  17538. else {
  17539. if (!token._timeElapsedQuery) {
  17540. return -1;
  17541. }
  17542. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17543. this._deleteTimeQuery(token._timeElapsedQuery);
  17544. token._timeElapsedQuery = null;
  17545. token._timeElapsedQueryEnded = false;
  17546. this._currentNonTimestampToken = null;
  17547. }
  17548. return result;
  17549. }
  17550. return -1;
  17551. };
  17552. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17553. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17554. };
  17555. // Transform feedback
  17556. /**
  17557. * Creates a webGL transform feedback object
  17558. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17559. * @returns the webGL transform feedback object
  17560. */
  17561. Engine.prototype.createTransformFeedback = function () {
  17562. return this._gl.createTransformFeedback();
  17563. };
  17564. /**
  17565. * Delete a webGL transform feedback object
  17566. * @param value defines the webGL transform feedback object to delete
  17567. */
  17568. Engine.prototype.deleteTransformFeedback = function (value) {
  17569. this._gl.deleteTransformFeedback(value);
  17570. };
  17571. /**
  17572. * Bind a webGL transform feedback object to the webgl context
  17573. * @param value defines the webGL transform feedback object to bind
  17574. */
  17575. Engine.prototype.bindTransformFeedback = function (value) {
  17576. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17577. };
  17578. /**
  17579. * Begins a transform feedback operation
  17580. * @param usePoints defines if points or triangles must be used
  17581. */
  17582. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17583. if (usePoints === void 0) { usePoints = true; }
  17584. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17585. };
  17586. /**
  17587. * Ends a transform feedback operation
  17588. */
  17589. Engine.prototype.endTransformFeedback = function () {
  17590. this._gl.endTransformFeedback();
  17591. };
  17592. /**
  17593. * Specify the varyings to use with transform feedback
  17594. * @param program defines the associated webGL program
  17595. * @param value defines the list of strings representing the varying names
  17596. */
  17597. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17598. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17599. };
  17600. /**
  17601. * Bind a webGL buffer for a transform feedback operation
  17602. * @param value defines the webGL buffer to bind
  17603. */
  17604. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17605. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17606. };
  17607. /** @hidden */
  17608. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17609. var _this = this;
  17610. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17611. this._activeRequests.push(request);
  17612. request.onCompleteObservable.add(function (request) {
  17613. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17614. });
  17615. return request;
  17616. };
  17617. /** @hidden */
  17618. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17619. var _this = this;
  17620. return new Promise(function (resolve, reject) {
  17621. _this._loadFile(url, function (data) {
  17622. resolve(data);
  17623. }, undefined, database, useArrayBuffer, function (request, exception) {
  17624. reject(exception);
  17625. });
  17626. });
  17627. };
  17628. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17629. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17630. var onload = function (data) {
  17631. loadedFiles[index] = data;
  17632. loadedFiles._internalCount++;
  17633. if (loadedFiles._internalCount === 6) {
  17634. onfinish(loadedFiles);
  17635. }
  17636. };
  17637. var onerror = function (request, exception) {
  17638. if (onErrorCallBack && request) {
  17639. onErrorCallBack(request.status + " " + request.statusText, exception);
  17640. }
  17641. };
  17642. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17643. };
  17644. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17645. if (onError === void 0) { onError = null; }
  17646. var loadedFiles = [];
  17647. loadedFiles._internalCount = 0;
  17648. for (var index = 0; index < 6; index++) {
  17649. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17650. }
  17651. };
  17652. // Statics
  17653. /**
  17654. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17655. * @returns true if the engine can be created
  17656. * @ignorenaming
  17657. */
  17658. Engine.isSupported = function () {
  17659. try {
  17660. var tempcanvas = document.createElement("canvas");
  17661. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17662. return gl != null && !!window.WebGLRenderingContext;
  17663. }
  17664. catch (e) {
  17665. return false;
  17666. }
  17667. };
  17668. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17669. Engine.ExceptionList = [
  17670. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17671. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17672. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17673. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17674. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17675. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17676. ];
  17677. /** Gets the list of created engines */
  17678. Engine.Instances = new Array();
  17679. // Const statics
  17680. Engine._ALPHA_DISABLE = 0;
  17681. Engine._ALPHA_ADD = 1;
  17682. Engine._ALPHA_COMBINE = 2;
  17683. Engine._ALPHA_SUBTRACT = 3;
  17684. Engine._ALPHA_MULTIPLY = 4;
  17685. Engine._ALPHA_MAXIMIZED = 5;
  17686. Engine._ALPHA_ONEONE = 6;
  17687. Engine._ALPHA_PREMULTIPLIED = 7;
  17688. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17689. Engine._ALPHA_INTERPOLATE = 9;
  17690. Engine._ALPHA_SCREENMODE = 10;
  17691. Engine._DELAYLOADSTATE_NONE = 0;
  17692. Engine._DELAYLOADSTATE_LOADED = 1;
  17693. Engine._DELAYLOADSTATE_LOADING = 2;
  17694. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17695. Engine._TEXTUREFORMAT_ALPHA = 0;
  17696. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17697. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17698. Engine._TEXTUREFORMAT_RGB = 4;
  17699. Engine._TEXTUREFORMAT_RGBA = 5;
  17700. Engine._TEXTUREFORMAT_R = 6;
  17701. Engine._TEXTUREFORMAT_RG = 7;
  17702. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17703. Engine._TEXTURETYPE_FLOAT = 1;
  17704. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17705. // Depht or Stencil test Constants.
  17706. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17707. 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.
  17708. 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.
  17709. 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.
  17710. 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.
  17711. 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.
  17712. 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.
  17713. 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.
  17714. // Stencil Actions Constants.
  17715. Engine._KEEP = 0x1E00;
  17716. Engine._REPLACE = 0x1E01;
  17717. Engine._INCR = 0x1E02;
  17718. Engine._DECR = 0x1E03;
  17719. Engine._INVERT = 0x150A;
  17720. Engine._INCR_WRAP = 0x8507;
  17721. Engine._DECR_WRAP = 0x8508;
  17722. // Texture rescaling mode
  17723. Engine._SCALEMODE_FLOOR = 1;
  17724. Engine._SCALEMODE_NEAREST = 2;
  17725. Engine._SCALEMODE_CEILING = 3;
  17726. // Updatable statics so stick with vars here
  17727. /**
  17728. * Gets or sets the epsilon value used by collision engine
  17729. */
  17730. Engine.CollisionsEpsilon = 0.001;
  17731. /**
  17732. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17733. */
  17734. Engine.CodeRepository = "src/";
  17735. /**
  17736. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17737. */
  17738. Engine.ShadersRepository = "src/Shaders/";
  17739. return Engine;
  17740. }());
  17741. BABYLON.Engine = Engine;
  17742. })(BABYLON || (BABYLON = {}));
  17743. //# sourceMappingURL=babylon.engine.js.map
  17744. var BABYLON;
  17745. (function (BABYLON) {
  17746. /**
  17747. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17748. */
  17749. var Node = /** @class */ (function () {
  17750. /**
  17751. * Creates a new Node
  17752. * @param {string} name - the name and id to be given to this node
  17753. * @param {BABYLON.Scene} the scene this node will be added to
  17754. */
  17755. function Node(name, scene) {
  17756. if (scene === void 0) { scene = null; }
  17757. /**
  17758. * Gets or sets a string used to store user defined state for the node
  17759. */
  17760. this.state = "";
  17761. /**
  17762. * Gets or sets an object used to store user defined information for the node
  17763. */
  17764. this.metadata = null;
  17765. /**
  17766. * Gets or sets a boolean used to define if the node must be serialized
  17767. */
  17768. this.doNotSerialize = false;
  17769. /** @hidden */
  17770. this._isDisposed = false;
  17771. /**
  17772. * Gets a list of Animations associated with the node
  17773. */
  17774. this.animations = new Array();
  17775. this._ranges = {};
  17776. this._isEnabled = true;
  17777. this._isReady = true;
  17778. /** @hidden */
  17779. this._currentRenderId = -1;
  17780. this._parentRenderId = -1;
  17781. this._childRenderId = -1;
  17782. this._animationPropertiesOverride = null;
  17783. /**
  17784. * An event triggered when the mesh is disposed
  17785. */
  17786. this.onDisposeObservable = new BABYLON.Observable();
  17787. // Behaviors
  17788. this._behaviors = new Array();
  17789. this.name = name;
  17790. this.id = name;
  17791. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17792. this.uniqueId = this._scene.getUniqueId();
  17793. this._initCache();
  17794. }
  17795. /**
  17796. * Gets a boolean indicating if the node has been disposed
  17797. * @returns true if the node was disposed
  17798. */
  17799. Node.prototype.isDisposed = function () {
  17800. return this._isDisposed;
  17801. };
  17802. Object.defineProperty(Node.prototype, "parent", {
  17803. get: function () {
  17804. return this._parentNode;
  17805. },
  17806. /**
  17807. * Gets or sets the parent of the node
  17808. */
  17809. set: function (parent) {
  17810. if (this._parentNode === parent) {
  17811. return;
  17812. }
  17813. // Remove self from list of children of parent
  17814. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17815. var index = this._parentNode._children.indexOf(this);
  17816. if (index !== -1) {
  17817. this._parentNode._children.splice(index, 1);
  17818. }
  17819. }
  17820. // Store new parent
  17821. this._parentNode = parent;
  17822. // Add as child to new parent
  17823. if (this._parentNode) {
  17824. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17825. this._parentNode._children = new Array();
  17826. }
  17827. this._parentNode._children.push(this);
  17828. }
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17834. /**
  17835. * Gets or sets the animation properties override
  17836. */
  17837. get: function () {
  17838. if (!this._animationPropertiesOverride) {
  17839. return this._scene.animationPropertiesOverride;
  17840. }
  17841. return this._animationPropertiesOverride;
  17842. },
  17843. set: function (value) {
  17844. this._animationPropertiesOverride = value;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. /**
  17850. * Gets a string idenfifying the name of the class
  17851. * @returns "Node" string
  17852. */
  17853. Node.prototype.getClassName = function () {
  17854. return "Node";
  17855. };
  17856. Object.defineProperty(Node.prototype, "onDispose", {
  17857. /**
  17858. * Sets a callback that will be raised when the node will be disposed
  17859. */
  17860. set: function (callback) {
  17861. if (this._onDisposeObserver) {
  17862. this.onDisposeObservable.remove(this._onDisposeObserver);
  17863. }
  17864. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. /**
  17870. * Gets the scene of the node
  17871. * @returns a {BABYLON.Scene}
  17872. */
  17873. Node.prototype.getScene = function () {
  17874. return this._scene;
  17875. };
  17876. /**
  17877. * Gets the engine of the node
  17878. * @returns a {BABYLON.Engine}
  17879. */
  17880. Node.prototype.getEngine = function () {
  17881. return this._scene.getEngine();
  17882. };
  17883. /**
  17884. * Attach a behavior to the node
  17885. * @see http://doc.babylonjs.com/features/behaviour
  17886. * @param behavior defines the behavior to attach
  17887. * @returns the current Node
  17888. */
  17889. Node.prototype.addBehavior = function (behavior) {
  17890. var _this = this;
  17891. var index = this._behaviors.indexOf(behavior);
  17892. if (index !== -1) {
  17893. return this;
  17894. }
  17895. behavior.init();
  17896. if (this._scene.isLoading) {
  17897. // We defer the attach when the scene will be loaded
  17898. this._scene.onDataLoadedObservable.addOnce(function () {
  17899. behavior.attach(_this);
  17900. });
  17901. }
  17902. else {
  17903. behavior.attach(this);
  17904. }
  17905. this._behaviors.push(behavior);
  17906. return this;
  17907. };
  17908. /**
  17909. * Remove an attached behavior
  17910. * @see http://doc.babylonjs.com/features/behaviour
  17911. * @param behavior defines the behavior to attach
  17912. * @returns the current Node
  17913. */
  17914. Node.prototype.removeBehavior = function (behavior) {
  17915. var index = this._behaviors.indexOf(behavior);
  17916. if (index === -1) {
  17917. return this;
  17918. }
  17919. this._behaviors[index].detach();
  17920. this._behaviors.splice(index, 1);
  17921. return this;
  17922. };
  17923. Object.defineProperty(Node.prototype, "behaviors", {
  17924. /**
  17925. * Gets the list of attached behaviors
  17926. * @see http://doc.babylonjs.com/features/behaviour
  17927. */
  17928. get: function () {
  17929. return this._behaviors;
  17930. },
  17931. enumerable: true,
  17932. configurable: true
  17933. });
  17934. /**
  17935. * Gets an attached behavior by name
  17936. * @param name defines the name of the behavior to look for
  17937. * @see http://doc.babylonjs.com/features/behaviour
  17938. * @returns null if behavior was not found else the requested behavior
  17939. */
  17940. Node.prototype.getBehaviorByName = function (name) {
  17941. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17942. var behavior = _a[_i];
  17943. if (behavior.name === name) {
  17944. return behavior;
  17945. }
  17946. }
  17947. return null;
  17948. };
  17949. /**
  17950. * Returns the world matrix of the node
  17951. * @returns a matrix containing the node's world matrix
  17952. */
  17953. Node.prototype.getWorldMatrix = function () {
  17954. return BABYLON.Matrix.Identity();
  17955. };
  17956. /** @hidden */
  17957. Node.prototype._getWorldMatrixDeterminant = function () {
  17958. return 1;
  17959. };
  17960. // override it in derived class if you add new variables to the cache
  17961. // and call the parent class method
  17962. /** @hidden */
  17963. Node.prototype._initCache = function () {
  17964. this._cache = {};
  17965. this._cache.parent = undefined;
  17966. };
  17967. /** @hidden */
  17968. Node.prototype.updateCache = function (force) {
  17969. if (!force && this.isSynchronized())
  17970. return;
  17971. this._cache.parent = this.parent;
  17972. this._updateCache();
  17973. };
  17974. // override it in derived class if you add new variables to the cache
  17975. // and call the parent class method if !ignoreParentClass
  17976. /** @hidden */
  17977. Node.prototype._updateCache = function (ignoreParentClass) {
  17978. };
  17979. // override it in derived class if you add new variables to the cache
  17980. /** @hidden */
  17981. Node.prototype._isSynchronized = function () {
  17982. return true;
  17983. };
  17984. /** @hidden */
  17985. Node.prototype._markSyncedWithParent = function () {
  17986. if (this.parent) {
  17987. this._parentRenderId = this.parent._childRenderId;
  17988. }
  17989. };
  17990. /** @hidden */
  17991. Node.prototype.isSynchronizedWithParent = function () {
  17992. if (!this.parent) {
  17993. return true;
  17994. }
  17995. if (this._parentRenderId !== this.parent._childRenderId) {
  17996. return false;
  17997. }
  17998. return this.parent.isSynchronized();
  17999. };
  18000. /** @hidden */
  18001. Node.prototype.isSynchronized = function (updateCache) {
  18002. var check = this.hasNewParent();
  18003. check = check || !this.isSynchronizedWithParent();
  18004. check = check || !this._isSynchronized();
  18005. if (updateCache)
  18006. this.updateCache(true);
  18007. return !check;
  18008. };
  18009. /** @hidden */
  18010. Node.prototype.hasNewParent = function (update) {
  18011. if (this._cache.parent === this.parent)
  18012. return false;
  18013. if (update)
  18014. this._cache.parent = this.parent;
  18015. return true;
  18016. };
  18017. /**
  18018. * Is this node ready to be used/rendered
  18019. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18020. * @return true if the node is ready
  18021. */
  18022. Node.prototype.isReady = function (completeCheck) {
  18023. if (completeCheck === void 0) { completeCheck = false; }
  18024. return this._isReady;
  18025. };
  18026. /**
  18027. * Is this node enabled?
  18028. * 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
  18029. * @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
  18030. * @return whether this node (and its parent) is enabled
  18031. */
  18032. Node.prototype.isEnabled = function (checkAncestors) {
  18033. if (checkAncestors === void 0) { checkAncestors = true; }
  18034. if (checkAncestors === false) {
  18035. return this._isEnabled;
  18036. }
  18037. if (this._isEnabled === false) {
  18038. return false;
  18039. }
  18040. if (this.parent !== undefined && this.parent !== null) {
  18041. return this.parent.isEnabled(checkAncestors);
  18042. }
  18043. return true;
  18044. };
  18045. /**
  18046. * Set the enabled state of this node
  18047. * @param value defines the new enabled state
  18048. */
  18049. Node.prototype.setEnabled = function (value) {
  18050. this._isEnabled = value;
  18051. };
  18052. /**
  18053. * Is this node a descendant of the given node?
  18054. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18055. * @param ancestor defines the parent node to inspect
  18056. * @returns a boolean indicating if this node is a descendant of the given node
  18057. */
  18058. Node.prototype.isDescendantOf = function (ancestor) {
  18059. if (this.parent) {
  18060. if (this.parent === ancestor) {
  18061. return true;
  18062. }
  18063. return this.parent.isDescendantOf(ancestor);
  18064. }
  18065. return false;
  18066. };
  18067. /** @hidden */
  18068. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18069. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18070. if (!this._children) {
  18071. return;
  18072. }
  18073. for (var index = 0; index < this._children.length; index++) {
  18074. var item = this._children[index];
  18075. if (!predicate || predicate(item)) {
  18076. results.push(item);
  18077. }
  18078. if (!directDescendantsOnly) {
  18079. item._getDescendants(results, false, predicate);
  18080. }
  18081. }
  18082. };
  18083. /**
  18084. * Will return all nodes that have this node as ascendant
  18085. * @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
  18086. * @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
  18087. * @return all children nodes of all types
  18088. */
  18089. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18090. var results = new Array();
  18091. this._getDescendants(results, directDescendantsOnly, predicate);
  18092. return results;
  18093. };
  18094. /**
  18095. * Get all child-meshes of this node
  18096. * @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
  18097. * @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
  18098. * @returns an array of {BABYLON.AbstractMesh}
  18099. */
  18100. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18101. var results = [];
  18102. this._getDescendants(results, directDescendantsOnly, function (node) {
  18103. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18104. });
  18105. return results;
  18106. };
  18107. /**
  18108. * Get all child-transformNodes of this node
  18109. * @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
  18110. * @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
  18111. * @returns an array of {BABYLON.TransformNode}
  18112. */
  18113. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18114. var results = [];
  18115. this._getDescendants(results, directDescendantsOnly, function (node) {
  18116. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18117. });
  18118. return results;
  18119. };
  18120. /**
  18121. * Get all direct children of this node
  18122. * @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
  18123. * @returns an array of {BABYLON.Node}
  18124. */
  18125. Node.prototype.getChildren = function (predicate) {
  18126. return this.getDescendants(true, predicate);
  18127. };
  18128. /** @hidden */
  18129. Node.prototype._setReady = function (state) {
  18130. if (state === this._isReady) {
  18131. return;
  18132. }
  18133. if (!state) {
  18134. this._isReady = false;
  18135. return;
  18136. }
  18137. if (this.onReady) {
  18138. this.onReady(this);
  18139. }
  18140. this._isReady = true;
  18141. };
  18142. /**
  18143. * Get an animation by name
  18144. * @param name defines the name of the animation to look for
  18145. * @returns null if not found else the requested animation
  18146. */
  18147. Node.prototype.getAnimationByName = function (name) {
  18148. for (var i = 0; i < this.animations.length; i++) {
  18149. var animation = this.animations[i];
  18150. if (animation.name === name) {
  18151. return animation;
  18152. }
  18153. }
  18154. return null;
  18155. };
  18156. /**
  18157. * Creates an animation range for this node
  18158. * @param name defines the name of the range
  18159. * @param from defines the starting key
  18160. * @param to defines the end key
  18161. */
  18162. Node.prototype.createAnimationRange = function (name, from, to) {
  18163. // check name not already in use
  18164. if (!this._ranges[name]) {
  18165. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18166. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18167. if (this.animations[i]) {
  18168. this.animations[i].createRange(name, from, to);
  18169. }
  18170. }
  18171. }
  18172. };
  18173. /**
  18174. * Delete a specific animation range
  18175. * @param name defines the name of the range to delete
  18176. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18177. */
  18178. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18179. if (deleteFrames === void 0) { deleteFrames = true; }
  18180. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18181. if (this.animations[i]) {
  18182. this.animations[i].deleteRange(name, deleteFrames);
  18183. }
  18184. }
  18185. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18186. };
  18187. /**
  18188. * Get an animation range by name
  18189. * @param name defines the name of the animation range to look for
  18190. * @returns null if not found else the requested animation range
  18191. */
  18192. Node.prototype.getAnimationRange = function (name) {
  18193. return this._ranges[name];
  18194. };
  18195. /**
  18196. * Will start the animation sequence
  18197. * @param name defines the range frames for animation sequence
  18198. * @param loop defines if the animation should loop (false by default)
  18199. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18200. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18201. * @returns the object created for this animation. If range does not exist, it will return null
  18202. */
  18203. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18204. var range = this.getAnimationRange(name);
  18205. if (!range) {
  18206. return null;
  18207. }
  18208. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18209. };
  18210. /**
  18211. * Serialize animation ranges into a JSON compatible object
  18212. * @returns serialization object
  18213. */
  18214. Node.prototype.serializeAnimationRanges = function () {
  18215. var serializationRanges = [];
  18216. for (var name in this._ranges) {
  18217. var localRange = this._ranges[name];
  18218. if (!localRange) {
  18219. continue;
  18220. }
  18221. var range = {};
  18222. range.name = name;
  18223. range.from = localRange.from;
  18224. range.to = localRange.to;
  18225. serializationRanges.push(range);
  18226. }
  18227. return serializationRanges;
  18228. };
  18229. /**
  18230. * Computes the world matrix of the node
  18231. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18232. * @returns the world matrix
  18233. */
  18234. Node.prototype.computeWorldMatrix = function (force) {
  18235. return BABYLON.Matrix.Identity();
  18236. };
  18237. /**
  18238. * Releases resources associated with this node.
  18239. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18240. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18241. */
  18242. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18243. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18244. if (!doNotRecurse) {
  18245. var nodes = this.getDescendants(true);
  18246. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18247. var node = nodes_1[_i];
  18248. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18249. }
  18250. }
  18251. else {
  18252. var transformNodes = this.getChildTransformNodes(true);
  18253. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18254. var transformNode = transformNodes_1[_a];
  18255. transformNode.parent = null;
  18256. transformNode.computeWorldMatrix(true);
  18257. }
  18258. }
  18259. this.parent = null;
  18260. // Callback
  18261. this.onDisposeObservable.notifyObservers(this);
  18262. this.onDisposeObservable.clear();
  18263. // Behaviors
  18264. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18265. var behavior = _c[_b];
  18266. behavior.detach();
  18267. }
  18268. this._behaviors = [];
  18269. this._isDisposed = true;
  18270. };
  18271. /**
  18272. * Parse animation range data from a serialization object and store them into a given node
  18273. * @param node defines where to store the animation ranges
  18274. * @param parsedNode defines the serialization object to read data from
  18275. * @param scene defines the hosting scene
  18276. */
  18277. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18278. if (parsedNode.ranges) {
  18279. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18280. var data = parsedNode.ranges[index];
  18281. node.createAnimationRange(data.name, data.from, data.to);
  18282. }
  18283. }
  18284. };
  18285. __decorate([
  18286. BABYLON.serialize()
  18287. ], Node.prototype, "name", void 0);
  18288. __decorate([
  18289. BABYLON.serialize()
  18290. ], Node.prototype, "id", void 0);
  18291. __decorate([
  18292. BABYLON.serialize()
  18293. ], Node.prototype, "uniqueId", void 0);
  18294. __decorate([
  18295. BABYLON.serialize()
  18296. ], Node.prototype, "state", void 0);
  18297. __decorate([
  18298. BABYLON.serialize()
  18299. ], Node.prototype, "metadata", void 0);
  18300. return Node;
  18301. }());
  18302. BABYLON.Node = Node;
  18303. })(BABYLON || (BABYLON = {}));
  18304. //# sourceMappingURL=babylon.node.js.map
  18305. var BABYLON;
  18306. (function (BABYLON) {
  18307. var BoundingSphere = /** @class */ (function () {
  18308. /**
  18309. * Creates a new bounding sphere
  18310. * @param min defines the minimum vector (in local space)
  18311. * @param max defines the maximum vector (in local space)
  18312. */
  18313. function BoundingSphere(min, max) {
  18314. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18315. this.reConstruct(min, max);
  18316. }
  18317. /**
  18318. * Recreates the entire bounding sphere from scratch
  18319. * @param min defines the new minimum vector (in local space)
  18320. * @param max defines the new maximum vector (in local space)
  18321. */
  18322. BoundingSphere.prototype.reConstruct = function (min, max) {
  18323. this.minimum = min.clone();
  18324. this.maximum = max.clone();
  18325. var distance = BABYLON.Vector3.Distance(min, max);
  18326. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18327. this.radius = distance * 0.5;
  18328. this.centerWorld = BABYLON.Vector3.Zero();
  18329. this._update(BABYLON.Matrix.Identity());
  18330. };
  18331. // Methods
  18332. BoundingSphere.prototype._update = function (world) {
  18333. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18334. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18335. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18336. };
  18337. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18338. for (var i = 0; i < 6; i++) {
  18339. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18340. return false;
  18341. }
  18342. return true;
  18343. };
  18344. BoundingSphere.prototype.intersectsPoint = function (point) {
  18345. var x = this.centerWorld.x - point.x;
  18346. var y = this.centerWorld.y - point.y;
  18347. var z = this.centerWorld.z - point.z;
  18348. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18349. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18350. return false;
  18351. return true;
  18352. };
  18353. // Statics
  18354. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18355. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18356. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18357. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18358. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18359. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18360. return false;
  18361. return true;
  18362. };
  18363. return BoundingSphere;
  18364. }());
  18365. BABYLON.BoundingSphere = BoundingSphere;
  18366. })(BABYLON || (BABYLON = {}));
  18367. //# sourceMappingURL=babylon.boundingSphere.js.map
  18368. var BABYLON;
  18369. (function (BABYLON) {
  18370. var BoundingBox = /** @class */ (function () {
  18371. /**
  18372. * Creates a new bounding box
  18373. * @param min defines the minimum vector (in local space)
  18374. * @param max defines the maximum vector (in local space)
  18375. */
  18376. function BoundingBox(min, max) {
  18377. this.vectorsWorld = new Array();
  18378. this.reConstruct(min, max);
  18379. }
  18380. // Methods
  18381. /**
  18382. * Recreates the entire bounding box from scratch
  18383. * @param min defines the new minimum vector (in local space)
  18384. * @param max defines the new maximum vector (in local space)
  18385. */
  18386. BoundingBox.prototype.reConstruct = function (min, max) {
  18387. this.minimum = min.clone();
  18388. this.maximum = max.clone();
  18389. // Bounding vectors
  18390. this.vectors = new Array();
  18391. this.vectors.push(this.minimum.clone());
  18392. this.vectors.push(this.maximum.clone());
  18393. this.vectors.push(this.minimum.clone());
  18394. this.vectors[2].x = this.maximum.x;
  18395. this.vectors.push(this.minimum.clone());
  18396. this.vectors[3].y = this.maximum.y;
  18397. this.vectors.push(this.minimum.clone());
  18398. this.vectors[4].z = this.maximum.z;
  18399. this.vectors.push(this.maximum.clone());
  18400. this.vectors[5].z = this.minimum.z;
  18401. this.vectors.push(this.maximum.clone());
  18402. this.vectors[6].x = this.minimum.x;
  18403. this.vectors.push(this.maximum.clone());
  18404. this.vectors[7].y = this.minimum.y;
  18405. // OBB
  18406. this.center = this.maximum.add(this.minimum).scale(0.5);
  18407. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18408. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18409. // World
  18410. for (var index = 0; index < this.vectors.length; index++) {
  18411. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18412. }
  18413. this.minimumWorld = BABYLON.Vector3.Zero();
  18414. this.maximumWorld = BABYLON.Vector3.Zero();
  18415. this.centerWorld = BABYLON.Vector3.Zero();
  18416. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18417. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18418. };
  18419. BoundingBox.prototype.getWorldMatrix = function () {
  18420. return this._worldMatrix;
  18421. };
  18422. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18423. this._worldMatrix.copyFrom(matrix);
  18424. return this;
  18425. };
  18426. BoundingBox.prototype._update = function (world) {
  18427. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18428. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18429. for (var index = 0; index < this.vectors.length; index++) {
  18430. var v = this.vectorsWorld[index];
  18431. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18432. if (v.x < this.minimumWorld.x)
  18433. this.minimumWorld.x = v.x;
  18434. if (v.y < this.minimumWorld.y)
  18435. this.minimumWorld.y = v.y;
  18436. if (v.z < this.minimumWorld.z)
  18437. this.minimumWorld.z = v.z;
  18438. if (v.x > this.maximumWorld.x)
  18439. this.maximumWorld.x = v.x;
  18440. if (v.y > this.maximumWorld.y)
  18441. this.maximumWorld.y = v.y;
  18442. if (v.z > this.maximumWorld.z)
  18443. this.maximumWorld.z = v.z;
  18444. }
  18445. // Extend
  18446. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18447. this.extendSizeWorld.scaleInPlace(0.5);
  18448. // OBB
  18449. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18450. this.centerWorld.scaleInPlace(0.5);
  18451. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18452. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18453. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18454. this._worldMatrix = world;
  18455. };
  18456. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18457. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18458. };
  18459. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18460. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18461. };
  18462. BoundingBox.prototype.intersectsPoint = function (point) {
  18463. var delta = -BABYLON.Epsilon;
  18464. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18465. return false;
  18466. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18467. return false;
  18468. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18469. return false;
  18470. return true;
  18471. };
  18472. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18473. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18474. };
  18475. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18476. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18477. return false;
  18478. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18479. return false;
  18480. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18481. return false;
  18482. return true;
  18483. };
  18484. // Statics
  18485. BoundingBox.Intersects = function (box0, box1) {
  18486. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18487. return false;
  18488. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18489. return false;
  18490. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18491. return false;
  18492. return true;
  18493. };
  18494. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18495. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18496. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18497. return (num <= (sphereRadius * sphereRadius));
  18498. };
  18499. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18500. for (var p = 0; p < 6; p++) {
  18501. for (var i = 0; i < 8; i++) {
  18502. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18503. return false;
  18504. }
  18505. }
  18506. }
  18507. return true;
  18508. };
  18509. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18510. for (var p = 0; p < 6; p++) {
  18511. var inCount = 8;
  18512. for (var i = 0; i < 8; i++) {
  18513. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18514. --inCount;
  18515. }
  18516. else {
  18517. break;
  18518. }
  18519. }
  18520. if (inCount === 0)
  18521. return false;
  18522. }
  18523. return true;
  18524. };
  18525. return BoundingBox;
  18526. }());
  18527. BABYLON.BoundingBox = BoundingBox;
  18528. })(BABYLON || (BABYLON = {}));
  18529. //# sourceMappingURL=babylon.boundingBox.js.map
  18530. var BABYLON;
  18531. (function (BABYLON) {
  18532. var computeBoxExtents = function (axis, box) {
  18533. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18534. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18535. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18536. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18537. var r = r0 + r1 + r2;
  18538. return {
  18539. min: p - r,
  18540. max: p + r
  18541. };
  18542. };
  18543. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18544. var axisOverlap = function (axis, box0, box1) {
  18545. var result0 = computeBoxExtents(axis, box0);
  18546. var result1 = computeBoxExtents(axis, box1);
  18547. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18548. };
  18549. var BoundingInfo = /** @class */ (function () {
  18550. function BoundingInfo(minimum, maximum) {
  18551. this.minimum = minimum;
  18552. this.maximum = maximum;
  18553. this._isLocked = false;
  18554. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18555. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18556. }
  18557. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18558. get: function () {
  18559. return this._isLocked;
  18560. },
  18561. set: function (value) {
  18562. this._isLocked = value;
  18563. },
  18564. enumerable: true,
  18565. configurable: true
  18566. });
  18567. // Methods
  18568. BoundingInfo.prototype.update = function (world) {
  18569. if (this._isLocked) {
  18570. return;
  18571. }
  18572. this.boundingBox._update(world);
  18573. this.boundingSphere._update(world);
  18574. };
  18575. /**
  18576. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18577. * @param center New center of the bounding info
  18578. * @param extend New extend of the bounding info
  18579. */
  18580. BoundingInfo.prototype.centerOn = function (center, extend) {
  18581. this.minimum = center.subtract(extend);
  18582. this.maximum = center.add(extend);
  18583. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18584. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18585. return this;
  18586. };
  18587. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18588. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18589. return false;
  18590. return this.boundingBox.isInFrustum(frustumPlanes);
  18591. };
  18592. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18593. /**
  18594. * Gets the world distance between the min and max points of the bounding box
  18595. */
  18596. get: function () {
  18597. var boundingBox = this.boundingBox;
  18598. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18599. return size.length();
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18605. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18606. };
  18607. BoundingInfo.prototype._checkCollision = function (collider) {
  18608. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18609. };
  18610. BoundingInfo.prototype.intersectsPoint = function (point) {
  18611. if (!this.boundingSphere.centerWorld) {
  18612. return false;
  18613. }
  18614. if (!this.boundingSphere.intersectsPoint(point)) {
  18615. return false;
  18616. }
  18617. if (!this.boundingBox.intersectsPoint(point)) {
  18618. return false;
  18619. }
  18620. return true;
  18621. };
  18622. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18623. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18624. return false;
  18625. }
  18626. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18627. return false;
  18628. }
  18629. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18630. return false;
  18631. }
  18632. if (!precise) {
  18633. return true;
  18634. }
  18635. var box0 = this.boundingBox;
  18636. var box1 = boundingInfo.boundingBox;
  18637. if (!axisOverlap(box0.directions[0], box0, box1))
  18638. return false;
  18639. if (!axisOverlap(box0.directions[1], box0, box1))
  18640. return false;
  18641. if (!axisOverlap(box0.directions[2], box0, box1))
  18642. return false;
  18643. if (!axisOverlap(box1.directions[0], box0, box1))
  18644. return false;
  18645. if (!axisOverlap(box1.directions[1], box0, box1))
  18646. return false;
  18647. if (!axisOverlap(box1.directions[2], box0, box1))
  18648. return false;
  18649. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18650. return false;
  18651. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18652. return false;
  18653. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18654. return false;
  18655. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18656. return false;
  18657. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18658. return false;
  18659. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18660. return false;
  18661. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18662. return false;
  18663. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18664. return false;
  18665. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18666. return false;
  18667. return true;
  18668. };
  18669. return BoundingInfo;
  18670. }());
  18671. BABYLON.BoundingInfo = BoundingInfo;
  18672. })(BABYLON || (BABYLON = {}));
  18673. //# sourceMappingURL=babylon.boundingInfo.js.map
  18674. var BABYLON;
  18675. (function (BABYLON) {
  18676. var TransformNode = /** @class */ (function (_super) {
  18677. __extends(TransformNode, _super);
  18678. function TransformNode(name, scene, isPure) {
  18679. if (scene === void 0) { scene = null; }
  18680. if (isPure === void 0) { isPure = true; }
  18681. var _this = _super.call(this, name, scene) || this;
  18682. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18683. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18684. _this._up = new BABYLON.Vector3(0, 1, 0);
  18685. _this._right = new BABYLON.Vector3(1, 0, 0);
  18686. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18687. // Properties
  18688. _this._rotation = BABYLON.Vector3.Zero();
  18689. _this._scaling = BABYLON.Vector3.One();
  18690. _this._isDirty = false;
  18691. /**
  18692. * Set the billboard mode. Default is 0.
  18693. *
  18694. * | Value | Type | Description |
  18695. * | --- | --- | --- |
  18696. * | 0 | BILLBOARDMODE_NONE | |
  18697. * | 1 | BILLBOARDMODE_X | |
  18698. * | 2 | BILLBOARDMODE_Y | |
  18699. * | 4 | BILLBOARDMODE_Z | |
  18700. * | 7 | BILLBOARDMODE_ALL | |
  18701. *
  18702. */
  18703. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18704. _this.scalingDeterminant = 1;
  18705. _this.infiniteDistance = false;
  18706. /**
  18707. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18708. * By default the system will update normals to compensate
  18709. */
  18710. _this.ignoreNonUniformScaling = false;
  18711. _this.position = BABYLON.Vector3.Zero();
  18712. _this._localWorld = BABYLON.Matrix.Zero();
  18713. _this._worldMatrix = BABYLON.Matrix.Zero();
  18714. _this._worldMatrixDeterminant = 0;
  18715. _this._absolutePosition = BABYLON.Vector3.Zero();
  18716. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18717. _this._postMultiplyPivotMatrix = false;
  18718. _this._isWorldMatrixFrozen = false;
  18719. /**
  18720. * An event triggered after the world matrix is updated
  18721. */
  18722. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18723. _this._nonUniformScaling = false;
  18724. if (isPure) {
  18725. _this.getScene().addTransformNode(_this);
  18726. }
  18727. return _this;
  18728. }
  18729. /**
  18730. * Gets a string idenfifying the name of the class
  18731. * @returns "TransformNode" string
  18732. */
  18733. TransformNode.prototype.getClassName = function () {
  18734. return "TransformNode";
  18735. };
  18736. Object.defineProperty(TransformNode.prototype, "rotation", {
  18737. /**
  18738. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18739. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18740. * Default : (0.0, 0.0, 0.0)
  18741. */
  18742. get: function () {
  18743. return this._rotation;
  18744. },
  18745. set: function (newRotation) {
  18746. this._rotation = newRotation;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(TransformNode.prototype, "scaling", {
  18752. /**
  18753. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18754. * Default : (1.0, 1.0, 1.0)
  18755. */
  18756. get: function () {
  18757. return this._scaling;
  18758. },
  18759. /**
  18760. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18761. * Default : (1.0, 1.0, 1.0)
  18762. */
  18763. set: function (newScaling) {
  18764. this._scaling = newScaling;
  18765. },
  18766. enumerable: true,
  18767. configurable: true
  18768. });
  18769. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18770. /**
  18771. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18772. * It's null by default.
  18773. * 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)
  18774. */
  18775. get: function () {
  18776. return this._rotationQuaternion;
  18777. },
  18778. set: function (quaternion) {
  18779. this._rotationQuaternion = quaternion;
  18780. //reset the rotation vector.
  18781. if (quaternion && this.rotation.length()) {
  18782. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18783. }
  18784. },
  18785. enumerable: true,
  18786. configurable: true
  18787. });
  18788. Object.defineProperty(TransformNode.prototype, "forward", {
  18789. /**
  18790. * The forward direction of that transform in world space.
  18791. */
  18792. get: function () {
  18793. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. Object.defineProperty(TransformNode.prototype, "up", {
  18799. /**
  18800. * The up direction of that transform in world space.
  18801. */
  18802. get: function () {
  18803. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18804. },
  18805. enumerable: true,
  18806. configurable: true
  18807. });
  18808. Object.defineProperty(TransformNode.prototype, "right", {
  18809. /**
  18810. * The right direction of that transform in world space.
  18811. */
  18812. get: function () {
  18813. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. /**
  18819. * Returns the latest update of the World matrix
  18820. * Returns a Matrix.
  18821. */
  18822. TransformNode.prototype.getWorldMatrix = function () {
  18823. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18824. this.computeWorldMatrix();
  18825. }
  18826. return this._worldMatrix;
  18827. };
  18828. /** @hidden */
  18829. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18830. return this._worldMatrixDeterminant;
  18831. };
  18832. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18833. /**
  18834. * Returns directly the latest state of the mesh World matrix.
  18835. * A Matrix is returned.
  18836. */
  18837. get: function () {
  18838. return this._worldMatrix;
  18839. },
  18840. enumerable: true,
  18841. configurable: true
  18842. });
  18843. /**
  18844. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18845. * Returns the TransformNode.
  18846. */
  18847. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18848. this._poseMatrix.copyFrom(matrix);
  18849. return this;
  18850. };
  18851. /**
  18852. * Returns the mesh Pose matrix.
  18853. * Returned object : Matrix
  18854. */
  18855. TransformNode.prototype.getPoseMatrix = function () {
  18856. return this._poseMatrix;
  18857. };
  18858. TransformNode.prototype._isSynchronized = function () {
  18859. if (this._isDirty) {
  18860. return false;
  18861. }
  18862. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18863. return false;
  18864. if (this._cache.pivotMatrixUpdated) {
  18865. return false;
  18866. }
  18867. if (this.infiniteDistance) {
  18868. return false;
  18869. }
  18870. if (!this._cache.position.equals(this.position))
  18871. return false;
  18872. if (this.rotationQuaternion) {
  18873. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18874. return false;
  18875. }
  18876. if (!this._cache.rotation.equals(this.rotation))
  18877. return false;
  18878. if (!this._cache.scaling.equals(this.scaling))
  18879. return false;
  18880. return true;
  18881. };
  18882. TransformNode.prototype._initCache = function () {
  18883. _super.prototype._initCache.call(this);
  18884. this._cache.localMatrixUpdated = false;
  18885. this._cache.position = BABYLON.Vector3.Zero();
  18886. this._cache.scaling = BABYLON.Vector3.Zero();
  18887. this._cache.rotation = BABYLON.Vector3.Zero();
  18888. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18889. this._cache.billboardMode = -1;
  18890. };
  18891. TransformNode.prototype.markAsDirty = function (property) {
  18892. if (property === "rotation") {
  18893. this.rotationQuaternion = null;
  18894. }
  18895. this._currentRenderId = Number.MAX_VALUE;
  18896. this._isDirty = true;
  18897. return this;
  18898. };
  18899. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18900. /**
  18901. * Returns the current mesh absolute position.
  18902. * Retuns a Vector3.
  18903. */
  18904. get: function () {
  18905. return this._absolutePosition;
  18906. },
  18907. enumerable: true,
  18908. configurable: true
  18909. });
  18910. /**
  18911. * Sets a new matrix to apply before all other transformation
  18912. * @param matrix defines the transform matrix
  18913. * @returns the current TransformNode
  18914. */
  18915. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18916. return this.setPivotMatrix(matrix, false);
  18917. };
  18918. /**
  18919. * Sets a new pivot matrix to the current node
  18920. * @param matrix defines the new pivot matrix to use
  18921. * @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
  18922. * @returns the current TransformNode
  18923. */
  18924. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18925. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18926. this._pivotMatrix = matrix.clone();
  18927. this._cache.pivotMatrixUpdated = true;
  18928. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18929. if (this._postMultiplyPivotMatrix) {
  18930. if (!this._pivotMatrixInverse) {
  18931. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18932. }
  18933. else {
  18934. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18935. }
  18936. }
  18937. return this;
  18938. };
  18939. /**
  18940. * Returns the mesh pivot matrix.
  18941. * Default : Identity.
  18942. * A Matrix is returned.
  18943. */
  18944. TransformNode.prototype.getPivotMatrix = function () {
  18945. return this._pivotMatrix;
  18946. };
  18947. /**
  18948. * Prevents the World matrix to be computed any longer.
  18949. * Returns the TransformNode.
  18950. */
  18951. TransformNode.prototype.freezeWorldMatrix = function () {
  18952. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18953. this.computeWorldMatrix(true);
  18954. this._isWorldMatrixFrozen = true;
  18955. return this;
  18956. };
  18957. /**
  18958. * Allows back the World matrix computation.
  18959. * Returns the TransformNode.
  18960. */
  18961. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18962. this._isWorldMatrixFrozen = false;
  18963. this.computeWorldMatrix(true);
  18964. return this;
  18965. };
  18966. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18967. /**
  18968. * True if the World matrix has been frozen.
  18969. * Returns a boolean.
  18970. */
  18971. get: function () {
  18972. return this._isWorldMatrixFrozen;
  18973. },
  18974. enumerable: true,
  18975. configurable: true
  18976. });
  18977. /**
  18978. * Retuns the mesh absolute position in the World.
  18979. * Returns a Vector3.
  18980. */
  18981. TransformNode.prototype.getAbsolutePosition = function () {
  18982. this.computeWorldMatrix();
  18983. return this._absolutePosition;
  18984. };
  18985. /**
  18986. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18987. * Returns the TransformNode.
  18988. */
  18989. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18990. if (!absolutePosition) {
  18991. return this;
  18992. }
  18993. var absolutePositionX;
  18994. var absolutePositionY;
  18995. var absolutePositionZ;
  18996. if (absolutePosition.x === undefined) {
  18997. if (arguments.length < 3) {
  18998. return this;
  18999. }
  19000. absolutePositionX = arguments[0];
  19001. absolutePositionY = arguments[1];
  19002. absolutePositionZ = arguments[2];
  19003. }
  19004. else {
  19005. absolutePositionX = absolutePosition.x;
  19006. absolutePositionY = absolutePosition.y;
  19007. absolutePositionZ = absolutePosition.z;
  19008. }
  19009. if (this.parent) {
  19010. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19011. invertParentWorldMatrix.invert();
  19012. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19013. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19014. }
  19015. else {
  19016. this.position.x = absolutePositionX;
  19017. this.position.y = absolutePositionY;
  19018. this.position.z = absolutePositionZ;
  19019. }
  19020. return this;
  19021. };
  19022. /**
  19023. * Sets the mesh position in its local space.
  19024. * Returns the TransformNode.
  19025. */
  19026. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19027. this.computeWorldMatrix();
  19028. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19029. return this;
  19030. };
  19031. /**
  19032. * Returns the mesh position in the local space from the current World matrix values.
  19033. * Returns a new Vector3.
  19034. */
  19035. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19036. this.computeWorldMatrix();
  19037. var invLocalWorldMatrix = this._localWorld.clone();
  19038. invLocalWorldMatrix.invert();
  19039. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19040. };
  19041. /**
  19042. * Translates the mesh along the passed Vector3 in its local space.
  19043. * Returns the TransformNode.
  19044. */
  19045. TransformNode.prototype.locallyTranslate = function (vector3) {
  19046. this.computeWorldMatrix(true);
  19047. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19048. return this;
  19049. };
  19050. /**
  19051. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19052. * @param targetPoint the position (must be in same space as current mesh) to look at
  19053. * @param yawCor optional yaw (y-axis) correction in radians
  19054. * @param pitchCor optional pitch (x-axis) correction in radians
  19055. * @param rollCor optional roll (z-axis) correction in radians
  19056. * @param space the choosen space of the target
  19057. * @returns the TransformNode.
  19058. */
  19059. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19060. if (yawCor === void 0) { yawCor = 0; }
  19061. if (pitchCor === void 0) { pitchCor = 0; }
  19062. if (rollCor === void 0) { rollCor = 0; }
  19063. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19064. var dv = TransformNode._lookAtVectorCache;
  19065. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19066. targetPoint.subtractToRef(pos, dv);
  19067. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19068. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19069. var pitch = Math.atan2(dv.y, len);
  19070. if (this.rotationQuaternion) {
  19071. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19072. }
  19073. else {
  19074. this.rotation.x = pitch + pitchCor;
  19075. this.rotation.y = yaw + yawCor;
  19076. this.rotation.z = rollCor;
  19077. }
  19078. return this;
  19079. };
  19080. /**
  19081. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19082. * This Vector3 is expressed in the World space.
  19083. */
  19084. TransformNode.prototype.getDirection = function (localAxis) {
  19085. var result = BABYLON.Vector3.Zero();
  19086. this.getDirectionToRef(localAxis, result);
  19087. return result;
  19088. };
  19089. /**
  19090. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19091. * localAxis is expressed in the mesh local space.
  19092. * result is computed in the Wordl space from the mesh World matrix.
  19093. * Returns the TransformNode.
  19094. */
  19095. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19096. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19097. return this;
  19098. };
  19099. /**
  19100. * Sets a new pivot point to the current node
  19101. * @param point defines the new pivot point to use
  19102. * @param space defines if the point is in world or local space (local by default)
  19103. * @returns the current TransformNode
  19104. */
  19105. TransformNode.prototype.setPivotPoint = function (point, space) {
  19106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19107. if (this.getScene().getRenderId() == 0) {
  19108. this.computeWorldMatrix(true);
  19109. }
  19110. var wm = this.getWorldMatrix();
  19111. if (space == BABYLON.Space.WORLD) {
  19112. var tmat = BABYLON.Tmp.Matrix[0];
  19113. wm.invertToRef(tmat);
  19114. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19115. }
  19116. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19117. };
  19118. /**
  19119. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19120. */
  19121. TransformNode.prototype.getPivotPoint = function () {
  19122. var point = BABYLON.Vector3.Zero();
  19123. this.getPivotPointToRef(point);
  19124. return point;
  19125. };
  19126. /**
  19127. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19128. * Returns the TransformNode.
  19129. */
  19130. TransformNode.prototype.getPivotPointToRef = function (result) {
  19131. result.x = -this._pivotMatrix.m[12];
  19132. result.y = -this._pivotMatrix.m[13];
  19133. result.z = -this._pivotMatrix.m[14];
  19134. return this;
  19135. };
  19136. /**
  19137. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19138. */
  19139. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19140. var point = BABYLON.Vector3.Zero();
  19141. this.getAbsolutePivotPointToRef(point);
  19142. return point;
  19143. };
  19144. /**
  19145. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19146. * Returns the TransformNode.
  19147. */
  19148. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19149. result.x = this._pivotMatrix.m[12];
  19150. result.y = this._pivotMatrix.m[13];
  19151. result.z = this._pivotMatrix.m[14];
  19152. this.getPivotPointToRef(result);
  19153. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19154. return this;
  19155. };
  19156. /**
  19157. * Defines the passed node as the parent of the current node.
  19158. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19159. * Returns the TransformNode.
  19160. */
  19161. TransformNode.prototype.setParent = function (node) {
  19162. if (!node && !this.parent) {
  19163. return this;
  19164. }
  19165. if (!node) {
  19166. var rotation = BABYLON.Tmp.Quaternion[0];
  19167. var position = BABYLON.Tmp.Vector3[0];
  19168. var scale = BABYLON.Tmp.Vector3[1];
  19169. if (this.parent && this.parent.computeWorldMatrix) {
  19170. this.parent.computeWorldMatrix(true);
  19171. }
  19172. this.computeWorldMatrix(true);
  19173. this.getWorldMatrix().decompose(scale, rotation, position);
  19174. if (this.rotationQuaternion) {
  19175. this.rotationQuaternion.copyFrom(rotation);
  19176. }
  19177. else {
  19178. rotation.toEulerAnglesToRef(this.rotation);
  19179. }
  19180. this.scaling.x = scale.x;
  19181. this.scaling.y = scale.y;
  19182. this.scaling.z = scale.z;
  19183. this.position.x = position.x;
  19184. this.position.y = position.y;
  19185. this.position.z = position.z;
  19186. }
  19187. else {
  19188. var rotation = BABYLON.Tmp.Quaternion[0];
  19189. var position = BABYLON.Tmp.Vector3[0];
  19190. var scale = BABYLON.Tmp.Vector3[1];
  19191. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19192. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19193. this.computeWorldMatrix(true);
  19194. node.computeWorldMatrix(true);
  19195. node.getWorldMatrix().invertToRef(invParentMatrix);
  19196. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19197. diffMatrix.decompose(scale, rotation, position);
  19198. if (this.rotationQuaternion) {
  19199. this.rotationQuaternion.copyFrom(rotation);
  19200. }
  19201. else {
  19202. rotation.toEulerAnglesToRef(this.rotation);
  19203. }
  19204. this.position.x = position.x;
  19205. this.position.y = position.y;
  19206. this.position.z = position.z;
  19207. this.scaling.x = scale.x;
  19208. this.scaling.y = scale.y;
  19209. this.scaling.z = scale.z;
  19210. }
  19211. this.parent = node;
  19212. return this;
  19213. };
  19214. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19215. get: function () {
  19216. return this._nonUniformScaling;
  19217. },
  19218. enumerable: true,
  19219. configurable: true
  19220. });
  19221. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19222. if (this._nonUniformScaling === value) {
  19223. return false;
  19224. }
  19225. this._nonUniformScaling = value;
  19226. return true;
  19227. };
  19228. /**
  19229. * Attach the current TransformNode to another TransformNode associated with a bone
  19230. * @param bone Bone affecting the TransformNode
  19231. * @param affectedTransformNode TransformNode associated with the bone
  19232. */
  19233. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19234. this._transformToBoneReferal = affectedTransformNode;
  19235. this.parent = bone;
  19236. if (bone.getWorldMatrix().determinant() < 0) {
  19237. this.scalingDeterminant *= -1;
  19238. }
  19239. return this;
  19240. };
  19241. TransformNode.prototype.detachFromBone = function () {
  19242. if (!this.parent) {
  19243. return this;
  19244. }
  19245. if (this.parent.getWorldMatrix().determinant() < 0) {
  19246. this.scalingDeterminant *= -1;
  19247. }
  19248. this._transformToBoneReferal = null;
  19249. this.parent = null;
  19250. return this;
  19251. };
  19252. /**
  19253. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19254. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19255. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19256. * The passed axis is also normalized.
  19257. * Returns the TransformNode.
  19258. */
  19259. TransformNode.prototype.rotate = function (axis, amount, space) {
  19260. axis.normalize();
  19261. if (!this.rotationQuaternion) {
  19262. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19263. this.rotation = BABYLON.Vector3.Zero();
  19264. }
  19265. var rotationQuaternion;
  19266. if (!space || space === BABYLON.Space.LOCAL) {
  19267. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19268. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19269. }
  19270. else {
  19271. if (this.parent) {
  19272. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19273. invertParentWorldMatrix.invert();
  19274. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19275. }
  19276. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19277. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19278. }
  19279. return this;
  19280. };
  19281. /**
  19282. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19283. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19284. * The passed axis is also normalized.
  19285. * Returns the TransformNode.
  19286. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19287. */
  19288. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19289. axis.normalize();
  19290. if (!this.rotationQuaternion) {
  19291. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19292. this.rotation.copyFromFloats(0, 0, 0);
  19293. }
  19294. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19295. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19296. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19297. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19298. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19299. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19300. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19301. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19302. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19303. return this;
  19304. };
  19305. /**
  19306. * Translates the mesh along the axis vector for the passed distance in the given space.
  19307. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19308. * Returns the TransformNode.
  19309. */
  19310. TransformNode.prototype.translate = function (axis, distance, space) {
  19311. var displacementVector = axis.scale(distance);
  19312. if (!space || space === BABYLON.Space.LOCAL) {
  19313. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19314. this.setPositionWithLocalVector(tempV3);
  19315. }
  19316. else {
  19317. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19318. }
  19319. return this;
  19320. };
  19321. /**
  19322. * Adds a rotation step to the mesh current rotation.
  19323. * x, y, z are Euler angles expressed in radians.
  19324. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19325. * This means this rotation is made in the mesh local space only.
  19326. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19327. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19328. * ```javascript
  19329. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19330. * ```
  19331. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19332. * 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.
  19333. * Returns the TransformNode.
  19334. */
  19335. TransformNode.prototype.addRotation = function (x, y, z) {
  19336. var rotationQuaternion;
  19337. if (this.rotationQuaternion) {
  19338. rotationQuaternion = this.rotationQuaternion;
  19339. }
  19340. else {
  19341. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19342. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19343. }
  19344. var accumulation = BABYLON.Tmp.Quaternion[0];
  19345. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19346. rotationQuaternion.multiplyInPlace(accumulation);
  19347. if (!this.rotationQuaternion) {
  19348. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19349. }
  19350. return this;
  19351. };
  19352. /**
  19353. * Computes the mesh World matrix and returns it.
  19354. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19355. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19356. * If the parameter `force`is set to `true`, the actual computation is done.
  19357. * Returns the mesh World Matrix.
  19358. */
  19359. TransformNode.prototype.computeWorldMatrix = function (force) {
  19360. if (this._isWorldMatrixFrozen) {
  19361. return this._worldMatrix;
  19362. }
  19363. if (!force && this.isSynchronized(true)) {
  19364. this._currentRenderId = this.getScene().getRenderId();
  19365. return this._worldMatrix;
  19366. }
  19367. this._cache.position.copyFrom(this.position);
  19368. this._cache.scaling.copyFrom(this.scaling);
  19369. this._cache.pivotMatrixUpdated = false;
  19370. this._cache.billboardMode = this.billboardMode;
  19371. this._currentRenderId = this.getScene().getRenderId();
  19372. this._childRenderId = this.getScene().getRenderId();
  19373. this._isDirty = false;
  19374. // Scaling
  19375. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19376. // Rotation
  19377. //rotate, if quaternion is set and rotation was used
  19378. if (this.rotationQuaternion) {
  19379. var len = this.rotation.length();
  19380. if (len) {
  19381. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19382. this.rotation.copyFromFloats(0, 0, 0);
  19383. }
  19384. }
  19385. if (this.rotationQuaternion) {
  19386. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19387. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19388. }
  19389. else {
  19390. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19391. this._cache.rotation.copyFrom(this.rotation);
  19392. }
  19393. // Translation
  19394. var camera = this.getScene().activeCamera;
  19395. if (this.infiniteDistance && !this.parent && camera) {
  19396. var cameraWorldMatrix = camera.getWorldMatrix();
  19397. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19398. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19399. }
  19400. else {
  19401. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19402. }
  19403. // Composing transformations
  19404. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19405. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19406. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19407. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19408. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19409. // Need to decompose each rotation here
  19410. var currentPosition = BABYLON.Tmp.Vector3[3];
  19411. if (this.parent && this.parent.getWorldMatrix) {
  19412. if (this._transformToBoneReferal) {
  19413. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19414. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19415. }
  19416. else {
  19417. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19418. }
  19419. }
  19420. else {
  19421. currentPosition.copyFrom(this.position);
  19422. }
  19423. currentPosition.subtractInPlace(camera.globalPosition);
  19424. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19425. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19426. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19427. }
  19428. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19429. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19430. }
  19431. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19432. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19433. }
  19434. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19435. }
  19436. else {
  19437. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19438. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19439. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19440. }
  19441. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19442. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19443. }
  19444. // Local world
  19445. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19446. // Parent
  19447. if (this.parent && this.parent.getWorldMatrix) {
  19448. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19449. if (this._transformToBoneReferal) {
  19450. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19451. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19452. }
  19453. else {
  19454. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19455. }
  19456. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19457. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19458. this._worldMatrix.copyFrom(this._localWorld);
  19459. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19460. }
  19461. else {
  19462. if (this._transformToBoneReferal) {
  19463. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19464. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19465. }
  19466. else {
  19467. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19468. }
  19469. }
  19470. this._markSyncedWithParent();
  19471. }
  19472. else {
  19473. this._worldMatrix.copyFrom(this._localWorld);
  19474. }
  19475. // Post multiply inverse of pivotMatrix
  19476. if (this._postMultiplyPivotMatrix) {
  19477. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19478. }
  19479. // Normal matrix
  19480. if (!this.ignoreNonUniformScaling) {
  19481. if (this.scaling.isNonUniform) {
  19482. this._updateNonUniformScalingState(true);
  19483. }
  19484. else if (this.parent && this.parent._nonUniformScaling) {
  19485. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19486. }
  19487. else {
  19488. this._updateNonUniformScalingState(false);
  19489. }
  19490. }
  19491. else {
  19492. this._updateNonUniformScalingState(false);
  19493. }
  19494. this._afterComputeWorldMatrix();
  19495. // Absolute position
  19496. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19497. // Callbacks
  19498. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19499. if (!this._poseMatrix) {
  19500. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19501. }
  19502. // Cache the determinant
  19503. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19504. return this._worldMatrix;
  19505. };
  19506. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19507. };
  19508. /**
  19509. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19510. * @param func: callback function to add
  19511. *
  19512. * Returns the TransformNode.
  19513. */
  19514. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19515. this.onAfterWorldMatrixUpdateObservable.add(func);
  19516. return this;
  19517. };
  19518. /**
  19519. * Removes a registered callback function.
  19520. * Returns the TransformNode.
  19521. */
  19522. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19523. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19524. return this;
  19525. };
  19526. /**
  19527. * Clone the current transform node
  19528. * Returns the new transform node
  19529. * @param name Name of the new clone
  19530. * @param newParent New parent for the clone
  19531. * @param doNotCloneChildren Do not clone children hierarchy
  19532. */
  19533. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19534. var _this = this;
  19535. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19536. result.name = name;
  19537. result.id = name;
  19538. if (newParent) {
  19539. result.parent = newParent;
  19540. }
  19541. if (!doNotCloneChildren) {
  19542. // Children
  19543. var directDescendants = this.getDescendants(true);
  19544. for (var index = 0; index < directDescendants.length; index++) {
  19545. var child = directDescendants[index];
  19546. if (child.clone) {
  19547. child.clone(name + "." + child.name, result);
  19548. }
  19549. }
  19550. }
  19551. return result;
  19552. };
  19553. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19554. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19555. serializationObject.type = this.getClassName();
  19556. // Parent
  19557. if (this.parent) {
  19558. serializationObject.parentId = this.parent.id;
  19559. }
  19560. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19561. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19562. }
  19563. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19564. serializationObject.isEnabled = this.isEnabled();
  19565. // Parent
  19566. if (this.parent) {
  19567. serializationObject.parentId = this.parent.id;
  19568. }
  19569. return serializationObject;
  19570. };
  19571. // Statics
  19572. /**
  19573. * Returns a new TransformNode object parsed from the source provided.
  19574. * The parameter `parsedMesh` is the source.
  19575. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19576. */
  19577. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19578. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19579. if (BABYLON.Tags) {
  19580. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19581. }
  19582. if (parsedTransformNode.localMatrix) {
  19583. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19584. }
  19585. else if (parsedTransformNode.pivotMatrix) {
  19586. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19587. }
  19588. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19589. // Parent
  19590. if (parsedTransformNode.parentId) {
  19591. transformNode._waitingParentId = parsedTransformNode.parentId;
  19592. }
  19593. return transformNode;
  19594. };
  19595. /**
  19596. * Releases resources associated with this transform node.
  19597. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19598. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19599. */
  19600. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19601. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19602. // Animations
  19603. this.getScene().stopAnimation(this);
  19604. // Remove from scene
  19605. this.getScene().removeTransformNode(this);
  19606. this.onAfterWorldMatrixUpdateObservable.clear();
  19607. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19608. };
  19609. // Statics
  19610. TransformNode.BILLBOARDMODE_NONE = 0;
  19611. TransformNode.BILLBOARDMODE_X = 1;
  19612. TransformNode.BILLBOARDMODE_Y = 2;
  19613. TransformNode.BILLBOARDMODE_Z = 4;
  19614. TransformNode.BILLBOARDMODE_ALL = 7;
  19615. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19616. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19617. __decorate([
  19618. BABYLON.serializeAsVector3()
  19619. ], TransformNode.prototype, "_rotation", void 0);
  19620. __decorate([
  19621. BABYLON.serializeAsQuaternion()
  19622. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19623. __decorate([
  19624. BABYLON.serializeAsVector3()
  19625. ], TransformNode.prototype, "_scaling", void 0);
  19626. __decorate([
  19627. BABYLON.serialize()
  19628. ], TransformNode.prototype, "billboardMode", void 0);
  19629. __decorate([
  19630. BABYLON.serialize()
  19631. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19632. __decorate([
  19633. BABYLON.serialize()
  19634. ], TransformNode.prototype, "infiniteDistance", void 0);
  19635. __decorate([
  19636. BABYLON.serialize()
  19637. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19638. __decorate([
  19639. BABYLON.serializeAsVector3()
  19640. ], TransformNode.prototype, "position", void 0);
  19641. return TransformNode;
  19642. }(BABYLON.Node));
  19643. BABYLON.TransformNode = TransformNode;
  19644. })(BABYLON || (BABYLON = {}));
  19645. //# sourceMappingURL=babylon.transformNode.js.map
  19646. var BABYLON;
  19647. (function (BABYLON) {
  19648. /**
  19649. * Class used to store all common mesh properties
  19650. */
  19651. var AbstractMesh = /** @class */ (function (_super) {
  19652. __extends(AbstractMesh, _super);
  19653. // Constructor
  19654. /**
  19655. * Creates a new AbstractMesh
  19656. * @param name defines the name of the mesh
  19657. * @param scene defines the hosting scene
  19658. */
  19659. function AbstractMesh(name, scene) {
  19660. if (scene === void 0) { scene = null; }
  19661. var _this = _super.call(this, name, scene, false) || this;
  19662. _this._facetNb = 0; // facet number
  19663. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19664. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19665. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19666. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19667. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19668. _this._subDiv = {
  19669. max: 1,
  19670. X: 1,
  19671. Y: 1,
  19672. Z: 1
  19673. };
  19674. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19675. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19676. // Events
  19677. /**
  19678. * An event triggered when this mesh collides with another one
  19679. */
  19680. _this.onCollideObservable = new BABYLON.Observable();
  19681. /**
  19682. * An event triggered when the collision's position changes
  19683. */
  19684. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19685. /**
  19686. * An event triggered when material is changed
  19687. */
  19688. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19689. // Properties
  19690. /**
  19691. * Gets or sets the orientation for POV movement & rotation
  19692. */
  19693. _this.definedFacingForward = true;
  19694. /**
  19695. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19696. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19697. * * 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.
  19698. * @see http://doc.babylonjs.com/features/occlusionquery
  19699. */
  19700. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19701. /**
  19702. * 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:
  19703. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19704. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19705. * * 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.
  19706. * @see http://doc.babylonjs.com/features/occlusionquery
  19707. */
  19708. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19709. /**
  19710. * 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.
  19711. * The default value is -1 which means don't break the query and wait till the result
  19712. * @see http://doc.babylonjs.com/features/occlusionquery
  19713. */
  19714. _this.occlusionRetryCount = -1;
  19715. _this._occlusionInternalRetryCounter = 0;
  19716. _this._isOccluded = false;
  19717. _this._isOcclusionQueryInProgress = false;
  19718. _this._visibility = 1.0;
  19719. /** Gets or sets the alpha index used to sort transparent meshes
  19720. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19721. */
  19722. _this.alphaIndex = Number.MAX_VALUE;
  19723. /**
  19724. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19725. */
  19726. _this.isVisible = true;
  19727. /**
  19728. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19729. */
  19730. _this.isPickable = true;
  19731. /**
  19732. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19733. */
  19734. _this.showBoundingBox = false;
  19735. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19736. _this.showSubMeshesBoundingBox = false;
  19737. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19738. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19739. */
  19740. _this.isBlocker = false;
  19741. /**
  19742. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19743. */
  19744. _this.enablePointerMoveEvents = false;
  19745. /**
  19746. * Specifies the rendering group id for this mesh (0 by default)
  19747. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19748. */
  19749. _this.renderingGroupId = 0;
  19750. _this._receiveShadows = false;
  19751. /**
  19752. * Gets or sets a boolean indicating if the outline must be rendered as well
  19753. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19754. */
  19755. _this.renderOutline = false;
  19756. /** Defines color to use when rendering outline */
  19757. _this.outlineColor = BABYLON.Color3.Red();
  19758. /** Define width to use when rendering outline */
  19759. _this.outlineWidth = 0.02;
  19760. /**
  19761. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19762. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19763. */
  19764. _this.renderOverlay = false;
  19765. /** Defines color to use when rendering overlay */
  19766. _this.overlayColor = BABYLON.Color3.Red();
  19767. /** Defines alpha to use when rendering overlay */
  19768. _this.overlayAlpha = 0.5;
  19769. _this._hasVertexAlpha = false;
  19770. _this._useVertexColors = true;
  19771. _this._computeBonesUsingShaders = true;
  19772. _this._numBoneInfluencers = 4;
  19773. _this._applyFog = true;
  19774. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19775. _this.useOctreeForRenderingSelection = true;
  19776. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19777. _this.useOctreeForPicking = true;
  19778. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19779. _this.useOctreeForCollisions = true;
  19780. _this._layerMask = 0x0FFFFFFF;
  19781. /**
  19782. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19783. */
  19784. _this.alwaysSelectAsActiveMesh = false;
  19785. /**
  19786. * Gets or sets the current action manager
  19787. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19788. */
  19789. _this.actionManager = null;
  19790. /**
  19791. * Gets or sets impostor used for physic simulation
  19792. * @see http://doc.babylonjs.com/features/physics_engine
  19793. */
  19794. _this.physicsImpostor = null;
  19795. // Collisions
  19796. _this._checkCollisions = false;
  19797. _this._collisionMask = -1;
  19798. _this._collisionGroup = -1;
  19799. /**
  19800. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19801. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19802. */
  19803. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19804. /**
  19805. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19806. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19807. */
  19808. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19809. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19810. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19811. // Edges
  19812. /**
  19813. * Defines edge width used when edgesRenderer is enabled
  19814. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19815. */
  19816. _this.edgesWidth = 1;
  19817. /**
  19818. * Defines edge color used when edgesRenderer is enabled
  19819. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19820. */
  19821. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19822. // Cache
  19823. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19824. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19825. /** @hidden */
  19826. _this._renderId = 0;
  19827. /** @hidden */
  19828. _this._intersectionsInProgress = new Array();
  19829. /** @hidden */
  19830. _this._unIndexed = false;
  19831. /** @hidden */
  19832. _this._lightSources = new Array();
  19833. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19834. if (collidedMesh === void 0) { collidedMesh = null; }
  19835. //TODO move this to the collision coordinator!
  19836. if (_this.getScene().workerCollisions)
  19837. newPosition.multiplyInPlace(_this._collider._radius);
  19838. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19839. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19840. _this.position.addInPlace(_this._diffPositionForCollisions);
  19841. }
  19842. if (collidedMesh) {
  19843. _this.onCollideObservable.notifyObservers(collidedMesh);
  19844. }
  19845. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19846. };
  19847. _this.getScene().addMesh(_this);
  19848. _this._resyncLightSources();
  19849. return _this;
  19850. }
  19851. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19852. /**
  19853. * No billboard
  19854. */
  19855. get: function () {
  19856. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19862. /** Billboard on X axis */
  19863. get: function () {
  19864. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19865. },
  19866. enumerable: true,
  19867. configurable: true
  19868. });
  19869. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19870. /** Billboard on Y axis */
  19871. get: function () {
  19872. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19878. /** Billboard on Z axis */
  19879. get: function () {
  19880. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19886. /** Billboard on all axes */
  19887. get: function () {
  19888. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19894. /**
  19895. * Gets the number of facets in the mesh
  19896. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19897. */
  19898. get: function () {
  19899. return this._facetNb;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19905. /**
  19906. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19907. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19908. */
  19909. get: function () {
  19910. return this._partitioningSubdivisions;
  19911. },
  19912. set: function (nb) {
  19913. this._partitioningSubdivisions = nb;
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19919. /**
  19920. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19921. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19922. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19923. */
  19924. get: function () {
  19925. return this._partitioningBBoxRatio;
  19926. },
  19927. set: function (ratio) {
  19928. this._partitioningBBoxRatio = ratio;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19934. /**
  19935. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19936. * Works only for updatable meshes.
  19937. * Doesn't work with multi-materials
  19938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19939. */
  19940. get: function () {
  19941. return this._facetDepthSort;
  19942. },
  19943. set: function (sort) {
  19944. this._facetDepthSort = sort;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19950. /**
  19951. * The location (Vector3) where the facet depth sort must be computed from.
  19952. * By default, the active camera position.
  19953. * Used only when facet depth sort is enabled
  19954. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19955. */
  19956. get: function () {
  19957. return this._facetDepthSortFrom;
  19958. },
  19959. set: function (location) {
  19960. this._facetDepthSortFrom = location;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19966. /**
  19967. * gets a boolean indicating if facetData is enabled
  19968. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19969. */
  19970. get: function () {
  19971. return this._facetDataEnabled;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. /** @hidden */
  19977. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19978. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19979. return false;
  19980. }
  19981. this._markSubMeshesAsMiscDirty();
  19982. return true;
  19983. };
  19984. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19985. /** Set a function to call when this mesh collides with another one */
  19986. set: function (callback) {
  19987. if (this._onCollideObserver) {
  19988. this.onCollideObservable.remove(this._onCollideObserver);
  19989. }
  19990. this._onCollideObserver = this.onCollideObservable.add(callback);
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19996. /** Set a function to call when the collision's position changes */
  19997. set: function (callback) {
  19998. if (this._onCollisionPositionChangeObserver) {
  19999. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20000. }
  20001. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20002. },
  20003. enumerable: true,
  20004. configurable: true
  20005. });
  20006. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20007. /**
  20008. * 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
  20009. * @see http://doc.babylonjs.com/features/occlusionquery
  20010. */
  20011. get: function () {
  20012. return this._isOccluded;
  20013. },
  20014. set: function (value) {
  20015. this._isOccluded = value;
  20016. },
  20017. enumerable: true,
  20018. configurable: true
  20019. });
  20020. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20021. /**
  20022. * Flag to check the progress status of the query
  20023. * @see http://doc.babylonjs.com/features/occlusionquery
  20024. */
  20025. get: function () {
  20026. return this._isOcclusionQueryInProgress;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20032. /**
  20033. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20034. */
  20035. get: function () {
  20036. return this._visibility;
  20037. },
  20038. /**
  20039. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20040. */
  20041. set: function (value) {
  20042. if (this._visibility === value) {
  20043. return;
  20044. }
  20045. this._visibility = value;
  20046. this._markSubMeshesAsMiscDirty();
  20047. },
  20048. enumerable: true,
  20049. configurable: true
  20050. });
  20051. Object.defineProperty(AbstractMesh.prototype, "material", {
  20052. /** Gets or sets current material */
  20053. get: function () {
  20054. return this._material;
  20055. },
  20056. set: function (value) {
  20057. if (this._material === value) {
  20058. return;
  20059. }
  20060. this._material = value;
  20061. if (this.onMaterialChangedObservable.hasObservers) {
  20062. this.onMaterialChangedObservable.notifyObservers(this);
  20063. }
  20064. if (!this.subMeshes) {
  20065. return;
  20066. }
  20067. this._unBindEffect();
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20073. /**
  20074. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20075. * @see http://doc.babylonjs.com/babylon101/shadows
  20076. */
  20077. get: function () {
  20078. return this._receiveShadows;
  20079. },
  20080. set: function (value) {
  20081. if (this._receiveShadows === value) {
  20082. return;
  20083. }
  20084. this._receiveShadows = value;
  20085. this._markSubMeshesAsLightDirty();
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20091. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20092. get: function () {
  20093. return this._hasVertexAlpha;
  20094. },
  20095. set: function (value) {
  20096. if (this._hasVertexAlpha === value) {
  20097. return;
  20098. }
  20099. this._hasVertexAlpha = value;
  20100. this._markSubMeshesAsAttributesDirty();
  20101. this._markSubMeshesAsMiscDirty();
  20102. },
  20103. enumerable: true,
  20104. configurable: true
  20105. });
  20106. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20107. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20108. get: function () {
  20109. return this._useVertexColors;
  20110. },
  20111. set: function (value) {
  20112. if (this._useVertexColors === value) {
  20113. return;
  20114. }
  20115. this._useVertexColors = value;
  20116. this._markSubMeshesAsAttributesDirty();
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20122. /**
  20123. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20124. */
  20125. get: function () {
  20126. return this._computeBonesUsingShaders;
  20127. },
  20128. set: function (value) {
  20129. if (this._computeBonesUsingShaders === value) {
  20130. return;
  20131. }
  20132. this._computeBonesUsingShaders = value;
  20133. this._markSubMeshesAsAttributesDirty();
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20139. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20140. get: function () {
  20141. return this._numBoneInfluencers;
  20142. },
  20143. set: function (value) {
  20144. if (this._numBoneInfluencers === value) {
  20145. return;
  20146. }
  20147. this._numBoneInfluencers = value;
  20148. this._markSubMeshesAsAttributesDirty();
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20154. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20155. get: function () {
  20156. return this._applyFog;
  20157. },
  20158. set: function (value) {
  20159. if (this._applyFog === value) {
  20160. return;
  20161. }
  20162. this._applyFog = value;
  20163. this._markSubMeshesAsMiscDirty();
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20169. /**
  20170. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20171. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20172. */
  20173. get: function () {
  20174. return this._layerMask;
  20175. },
  20176. set: function (value) {
  20177. if (value === this._layerMask) {
  20178. return;
  20179. }
  20180. this._layerMask = value;
  20181. this._resyncLightSources();
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20187. /**
  20188. * Gets or sets a collision mask used to mask collisions (default is -1).
  20189. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20190. */
  20191. get: function () {
  20192. return this._collisionMask;
  20193. },
  20194. set: function (mask) {
  20195. this._collisionMask = !isNaN(mask) ? mask : -1;
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20201. /**
  20202. * Gets or sets the current collision group mask (-1 by default).
  20203. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20204. */
  20205. get: function () {
  20206. return this._collisionGroup;
  20207. },
  20208. set: function (mask) {
  20209. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20215. /** @hidden */
  20216. get: function () {
  20217. return null;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20223. get: function () {
  20224. return this._skeleton;
  20225. },
  20226. /**
  20227. * Gets or sets a skeleton to apply skining transformations
  20228. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20229. */
  20230. set: function (value) {
  20231. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20232. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20233. }
  20234. if (value && value.needInitialSkinMatrix) {
  20235. value._registerMeshWithPoseMatrix(this);
  20236. }
  20237. this._skeleton = value;
  20238. if (!this._skeleton) {
  20239. this._bonesTransformMatrices = null;
  20240. }
  20241. this._markSubMeshesAsAttributesDirty();
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. /**
  20247. * Returns the string "AbstractMesh"
  20248. * @returns "AbstractMesh"
  20249. */
  20250. AbstractMesh.prototype.getClassName = function () {
  20251. return "AbstractMesh";
  20252. };
  20253. /**
  20254. * Gets a string representation of the current mesh
  20255. * @param fullDetails defines a boolean indicating if full details must be included
  20256. * @returns a string representation of the current mesh
  20257. */
  20258. AbstractMesh.prototype.toString = function (fullDetails) {
  20259. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20260. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20261. if (this._skeleton) {
  20262. ret += ", skeleton: " + this._skeleton.name;
  20263. }
  20264. if (fullDetails) {
  20265. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20266. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20267. }
  20268. return ret;
  20269. };
  20270. /** @hidden */
  20271. AbstractMesh.prototype._rebuild = function () {
  20272. if (this._occlusionQuery) {
  20273. this._occlusionQuery = null;
  20274. }
  20275. if (this._edgesRenderer) {
  20276. this._edgesRenderer._rebuild();
  20277. }
  20278. if (!this.subMeshes) {
  20279. return;
  20280. }
  20281. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20282. var subMesh = _a[_i];
  20283. subMesh._rebuild();
  20284. }
  20285. };
  20286. /** @hidden */
  20287. AbstractMesh.prototype._resyncLightSources = function () {
  20288. this._lightSources.length = 0;
  20289. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20290. var light = _a[_i];
  20291. if (!light.isEnabled()) {
  20292. continue;
  20293. }
  20294. if (light.canAffectMesh(this)) {
  20295. this._lightSources.push(light);
  20296. }
  20297. }
  20298. this._markSubMeshesAsLightDirty();
  20299. };
  20300. /** @hidden */
  20301. AbstractMesh.prototype._resyncLighSource = function (light) {
  20302. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20303. var index = this._lightSources.indexOf(light);
  20304. if (index === -1) {
  20305. if (!isIn) {
  20306. return;
  20307. }
  20308. this._lightSources.push(light);
  20309. }
  20310. else {
  20311. if (isIn) {
  20312. return;
  20313. }
  20314. this._lightSources.splice(index, 1);
  20315. }
  20316. this._markSubMeshesAsLightDirty();
  20317. };
  20318. /** @hidden */
  20319. AbstractMesh.prototype._unBindEffect = function () {
  20320. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20321. var subMesh = _a[_i];
  20322. subMesh.setEffect(null);
  20323. }
  20324. };
  20325. /** @hidden */
  20326. AbstractMesh.prototype._removeLightSource = function (light) {
  20327. var index = this._lightSources.indexOf(light);
  20328. if (index === -1) {
  20329. return;
  20330. }
  20331. this._lightSources.splice(index, 1);
  20332. this._markSubMeshesAsLightDirty();
  20333. };
  20334. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20335. if (!this.subMeshes) {
  20336. return;
  20337. }
  20338. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20339. var subMesh = _a[_i];
  20340. if (subMesh._materialDefines) {
  20341. func(subMesh._materialDefines);
  20342. }
  20343. }
  20344. };
  20345. /** @hidden */
  20346. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20347. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20348. };
  20349. /** @hidden */
  20350. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20351. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20352. };
  20353. /** @hidden */
  20354. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20355. if (!this.subMeshes) {
  20356. return;
  20357. }
  20358. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20359. var subMesh = _a[_i];
  20360. var material = subMesh.getMaterial();
  20361. if (material) {
  20362. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20363. }
  20364. }
  20365. };
  20366. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20367. /**
  20368. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20369. */
  20370. get: function () {
  20371. return this._scaling;
  20372. },
  20373. set: function (newScaling) {
  20374. this._scaling = newScaling;
  20375. if (this.physicsImpostor) {
  20376. this.physicsImpostor.forceUpdate();
  20377. }
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. // Methods
  20383. /**
  20384. * Disables the mesh edge rendering mode
  20385. * @returns the currentAbstractMesh
  20386. */
  20387. AbstractMesh.prototype.disableEdgesRendering = function () {
  20388. if (this._edgesRenderer) {
  20389. this._edgesRenderer.dispose();
  20390. this._edgesRenderer = null;
  20391. }
  20392. return this;
  20393. };
  20394. /**
  20395. * Enables the edge rendering mode on the mesh.
  20396. * This mode makes the mesh edges visible
  20397. * @param epsilon defines the maximal distance between two angles to detect a face
  20398. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20399. * @returns the currentAbstractMesh
  20400. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20401. */
  20402. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20403. if (epsilon === void 0) { epsilon = 0.95; }
  20404. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20405. this.disableEdgesRendering();
  20406. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20407. return this;
  20408. };
  20409. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20410. /**
  20411. * Gets the edgesRenderer associated with the mesh
  20412. */
  20413. get: function () {
  20414. return this._edgesRenderer;
  20415. },
  20416. enumerable: true,
  20417. configurable: true
  20418. });
  20419. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20420. /**
  20421. * Returns true if the mesh is blocked. Implemented by child classes
  20422. */
  20423. get: function () {
  20424. return false;
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. /**
  20430. * Returns the mesh itself by default. Implemented by child classes
  20431. * @param camera defines the camera to use to pick the right LOD level
  20432. * @returns the currentAbstractMesh
  20433. */
  20434. AbstractMesh.prototype.getLOD = function (camera) {
  20435. return this;
  20436. };
  20437. /**
  20438. * Returns 0 by default. Implemented by child classes
  20439. * @returns an integer
  20440. */
  20441. AbstractMesh.prototype.getTotalVertices = function () {
  20442. return 0;
  20443. };
  20444. /**
  20445. * Returns null by default. Implemented by child classes
  20446. * @returns null
  20447. */
  20448. AbstractMesh.prototype.getIndices = function () {
  20449. return null;
  20450. };
  20451. /**
  20452. * Returns the array of the requested vertex data kind. Implemented by child classes
  20453. * @param kind defines the vertex data kind to use
  20454. * @returns null
  20455. */
  20456. AbstractMesh.prototype.getVerticesData = function (kind) {
  20457. return null;
  20458. };
  20459. /**
  20460. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20461. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20462. * Note that a new underlying VertexBuffer object is created each call.
  20463. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20464. * @param kind defines vertex data kind:
  20465. * * BABYLON.VertexBuffer.PositionKind
  20466. * * BABYLON.VertexBuffer.UVKind
  20467. * * BABYLON.VertexBuffer.UV2Kind
  20468. * * BABYLON.VertexBuffer.UV3Kind
  20469. * * BABYLON.VertexBuffer.UV4Kind
  20470. * * BABYLON.VertexBuffer.UV5Kind
  20471. * * BABYLON.VertexBuffer.UV6Kind
  20472. * * BABYLON.VertexBuffer.ColorKind
  20473. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20474. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20475. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20476. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20477. * @param data defines the data source
  20478. * @param updatable defines if the data must be flagged as updatable (or static)
  20479. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20480. * @returns the current mesh
  20481. */
  20482. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20483. return this;
  20484. };
  20485. /**
  20486. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20487. * If the mesh has no geometry, it is simply returned as it is.
  20488. * @param kind defines vertex data kind:
  20489. * * BABYLON.VertexBuffer.PositionKind
  20490. * * BABYLON.VertexBuffer.UVKind
  20491. * * BABYLON.VertexBuffer.UV2Kind
  20492. * * BABYLON.VertexBuffer.UV3Kind
  20493. * * BABYLON.VertexBuffer.UV4Kind
  20494. * * BABYLON.VertexBuffer.UV5Kind
  20495. * * BABYLON.VertexBuffer.UV6Kind
  20496. * * BABYLON.VertexBuffer.ColorKind
  20497. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20498. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20499. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20500. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20501. * @param data defines the data source
  20502. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20503. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20504. * @returns the current mesh
  20505. */
  20506. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20507. return this;
  20508. };
  20509. /**
  20510. * Sets the mesh indices,
  20511. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20512. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20513. * @param totalVertices Defines the total number of vertices
  20514. * @returns the current mesh
  20515. */
  20516. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20517. return this;
  20518. };
  20519. /**
  20520. * Gets a boolean indicating if specific vertex data is present
  20521. * @param kind defines the vertex data kind to use
  20522. * @returns true is data kind is present
  20523. */
  20524. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20525. return false;
  20526. };
  20527. /**
  20528. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20529. * @returns a BoundingInfo
  20530. */
  20531. AbstractMesh.prototype.getBoundingInfo = function () {
  20532. if (this._masterMesh) {
  20533. return this._masterMesh.getBoundingInfo();
  20534. }
  20535. if (!this._boundingInfo) {
  20536. // this._boundingInfo is being created here
  20537. this._updateBoundingInfo();
  20538. }
  20539. // cannot be null.
  20540. return this._boundingInfo;
  20541. };
  20542. /**
  20543. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20544. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20545. * @returns the current mesh
  20546. */
  20547. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20548. if (includeDescendants === void 0) { includeDescendants = true; }
  20549. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20550. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20551. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20552. if (maxDimension === 0) {
  20553. return this;
  20554. }
  20555. var scale = 1 / maxDimension;
  20556. this.scaling.scaleInPlace(scale);
  20557. return this;
  20558. };
  20559. /**
  20560. * Overwrite the current bounding info
  20561. * @param boundingInfo defines the new bounding info
  20562. * @returns the current mesh
  20563. */
  20564. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20565. this._boundingInfo = boundingInfo;
  20566. return this;
  20567. };
  20568. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20569. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20570. get: function () {
  20571. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20572. },
  20573. enumerable: true,
  20574. configurable: true
  20575. });
  20576. /** @hidden */
  20577. AbstractMesh.prototype._preActivate = function () {
  20578. };
  20579. /** @hidden */
  20580. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20581. };
  20582. /** @hidden */
  20583. AbstractMesh.prototype._activate = function (renderId) {
  20584. this._renderId = renderId;
  20585. };
  20586. /**
  20587. * Gets the current world matrix
  20588. * @returns a Matrix
  20589. */
  20590. AbstractMesh.prototype.getWorldMatrix = function () {
  20591. if (this._masterMesh) {
  20592. return this._masterMesh.getWorldMatrix();
  20593. }
  20594. return _super.prototype.getWorldMatrix.call(this);
  20595. };
  20596. /** @hidden */
  20597. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20598. if (this._masterMesh) {
  20599. return this._masterMesh._getWorldMatrixDeterminant();
  20600. }
  20601. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20602. };
  20603. // ================================== Point of View Movement =================================
  20604. /**
  20605. * Perform relative position change from the point of view of behind the front of the mesh.
  20606. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20607. * Supports definition of mesh facing forward or backward
  20608. * @param amountRight defines the distance on the right axis
  20609. * @param amountUp defines the distance on the up axis
  20610. * @param amountForward defines the distance on the forward axis
  20611. * @returns the current mesh
  20612. */
  20613. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20614. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20615. return this;
  20616. };
  20617. /**
  20618. * Calculate relative position change from the point of view of behind the front of the mesh.
  20619. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20620. * Supports definition of mesh facing forward or backward
  20621. * @param amountRight defines the distance on the right axis
  20622. * @param amountUp defines the distance on the up axis
  20623. * @param amountForward defines the distance on the forward axis
  20624. * @returns the new displacement vector
  20625. */
  20626. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20627. var rotMatrix = new BABYLON.Matrix();
  20628. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20629. rotQuaternion.toRotationMatrix(rotMatrix);
  20630. var translationDelta = BABYLON.Vector3.Zero();
  20631. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20632. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20633. return translationDelta;
  20634. };
  20635. // ================================== Point of View Rotation =================================
  20636. /**
  20637. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20638. * Supports definition of mesh facing forward or backward
  20639. * @param flipBack defines the flip
  20640. * @param twirlClockwise defines the twirl
  20641. * @param tiltRight defines the tilt
  20642. * @returns the current mesh
  20643. */
  20644. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20645. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20646. return this;
  20647. };
  20648. /**
  20649. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20650. * Supports definition of mesh facing forward or backward.
  20651. * @param flipBack defines the flip
  20652. * @param twirlClockwise defines the twirl
  20653. * @param tiltRight defines the tilt
  20654. * @returns the new rotation vector
  20655. */
  20656. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20657. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20658. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20659. };
  20660. /**
  20661. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20662. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20663. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20664. * @returns the new bounding vectors
  20665. */
  20666. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20667. if (includeDescendants === void 0) { includeDescendants = true; }
  20668. if (predicate === void 0) { predicate = null; }
  20669. // Ensures that all world matrix will be recomputed.
  20670. this.getScene().incrementRenderId();
  20671. this.computeWorldMatrix(true);
  20672. var min;
  20673. var max;
  20674. var boundingInfo = this.getBoundingInfo();
  20675. if (!this.subMeshes) {
  20676. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20677. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20678. }
  20679. else {
  20680. min = boundingInfo.boundingBox.minimumWorld;
  20681. max = boundingInfo.boundingBox.maximumWorld;
  20682. }
  20683. if (includeDescendants) {
  20684. var descendants = this.getDescendants(false);
  20685. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20686. var descendant = descendants_1[_i];
  20687. var childMesh = descendant;
  20688. childMesh.computeWorldMatrix(true);
  20689. // Filters meshes based on custom predicate function.
  20690. if (predicate && !predicate(childMesh)) {
  20691. continue;
  20692. }
  20693. //make sure we have the needed params to get mix and max
  20694. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20695. continue;
  20696. }
  20697. var childBoundingInfo = childMesh.getBoundingInfo();
  20698. var boundingBox = childBoundingInfo.boundingBox;
  20699. var minBox = boundingBox.minimumWorld;
  20700. var maxBox = boundingBox.maximumWorld;
  20701. BABYLON.Tools.CheckExtends(minBox, min, max);
  20702. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20703. }
  20704. }
  20705. return {
  20706. min: min,
  20707. max: max
  20708. };
  20709. };
  20710. /** @hidden */
  20711. AbstractMesh.prototype._updateBoundingInfo = function () {
  20712. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20713. this._boundingInfo.update(this.worldMatrixFromCache);
  20714. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20715. return this;
  20716. };
  20717. /** @hidden */
  20718. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20719. if (!this.subMeshes) {
  20720. return this;
  20721. }
  20722. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20723. var subMesh = this.subMeshes[subIndex];
  20724. if (!subMesh.IsGlobal) {
  20725. subMesh.updateBoundingInfo(matrix);
  20726. }
  20727. }
  20728. return this;
  20729. };
  20730. /** @hidden */
  20731. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20732. // Bounding info
  20733. this._updateBoundingInfo();
  20734. };
  20735. /**
  20736. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20737. * A mesh is in the frustum if its bounding box intersects the frustum
  20738. * @param frustumPlanes defines the frustum to test
  20739. * @returns true if the mesh is in the frustum planes
  20740. */
  20741. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20742. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20743. };
  20744. /**
  20745. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20746. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20747. * @param frustumPlanes defines the frustum to test
  20748. * @returns true if the mesh is completely in the frustum planes
  20749. */
  20750. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20751. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20752. };
  20753. /**
  20754. * True if the mesh intersects another mesh or a SolidParticle object
  20755. * @param mesh defines a target mesh or SolidParticle to test
  20756. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20757. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20758. * @returns true if there is an intersection
  20759. */
  20760. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20761. if (precise === void 0) { precise = false; }
  20762. if (!this._boundingInfo || !mesh._boundingInfo) {
  20763. return false;
  20764. }
  20765. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20766. return true;
  20767. }
  20768. if (includeDescendants) {
  20769. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20770. var child = _a[_i];
  20771. if (child.intersectsMesh(mesh, precise, true)) {
  20772. return true;
  20773. }
  20774. }
  20775. }
  20776. return false;
  20777. };
  20778. /**
  20779. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20780. * @param point defines the point to test
  20781. * @returns true if there is an intersection
  20782. */
  20783. AbstractMesh.prototype.intersectsPoint = function (point) {
  20784. if (!this._boundingInfo) {
  20785. return false;
  20786. }
  20787. return this._boundingInfo.intersectsPoint(point);
  20788. };
  20789. /**
  20790. * Gets the current physics impostor
  20791. * @see http://doc.babylonjs.com/features/physics_engine
  20792. * @returns a physics impostor or null
  20793. */
  20794. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20795. return this.physicsImpostor;
  20796. };
  20797. /**
  20798. * Gets the position of the current mesh in camera space
  20799. * @param camera defines the camera to use
  20800. * @returns a position
  20801. */
  20802. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20803. if (camera === void 0) { camera = null; }
  20804. if (!camera) {
  20805. camera = this.getScene().activeCamera;
  20806. }
  20807. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20808. };
  20809. /**
  20810. * Returns the distance from the mesh to the active camera
  20811. * @param camera defines the camera to use
  20812. * @returns the distance
  20813. */
  20814. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20815. if (camera === void 0) { camera = null; }
  20816. if (!camera) {
  20817. camera = this.getScene().activeCamera;
  20818. }
  20819. return this.absolutePosition.subtract(camera.position).length();
  20820. };
  20821. /**
  20822. * Apply a physic impulse to the mesh
  20823. * @param force defines the force to apply
  20824. * @param contactPoint defines where to apply the force
  20825. * @returns the current mesh
  20826. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20827. */
  20828. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20829. if (!this.physicsImpostor) {
  20830. return this;
  20831. }
  20832. this.physicsImpostor.applyImpulse(force, contactPoint);
  20833. return this;
  20834. };
  20835. /**
  20836. * Creates a physic joint between two meshes
  20837. * @param otherMesh defines the other mesh to use
  20838. * @param pivot1 defines the pivot to use on this mesh
  20839. * @param pivot2 defines the pivot to use on the other mesh
  20840. * @param options defines additional options (can be plugin dependent)
  20841. * @returns the current mesh
  20842. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20843. */
  20844. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20845. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20846. return this;
  20847. }
  20848. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20849. mainPivot: pivot1,
  20850. connectedPivot: pivot2,
  20851. nativeParams: options
  20852. });
  20853. return this;
  20854. };
  20855. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20856. // Collisions
  20857. /**
  20858. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20859. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20860. */
  20861. get: function () {
  20862. return this._checkCollisions;
  20863. },
  20864. set: function (collisionEnabled) {
  20865. this._checkCollisions = collisionEnabled;
  20866. if (this.getScene().workerCollisions) {
  20867. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20868. }
  20869. },
  20870. enumerable: true,
  20871. configurable: true
  20872. });
  20873. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20874. /**
  20875. * Gets Collider object used to compute collisions (not physics)
  20876. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20877. */
  20878. get: function () {
  20879. return this._collider;
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. /**
  20885. * Move the mesh using collision engine
  20886. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20887. * @param displacement defines the requested displacement vector
  20888. * @returns the current mesh
  20889. */
  20890. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20891. var globalPosition = this.getAbsolutePosition();
  20892. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20893. if (!this._collider) {
  20894. this._collider = new BABYLON.Collider();
  20895. }
  20896. this._collider._radius = this.ellipsoid;
  20897. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20898. return this;
  20899. };
  20900. // Submeshes octree
  20901. /**
  20902. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20903. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20904. * @param maxCapacity defines the maximum size of each block (64 by default)
  20905. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20906. * @returns the new octree
  20907. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20908. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20909. */
  20910. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20911. if (maxCapacity === void 0) { maxCapacity = 64; }
  20912. if (maxDepth === void 0) { maxDepth = 2; }
  20913. if (!this._submeshesOctree) {
  20914. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20915. }
  20916. this.computeWorldMatrix(true);
  20917. var boundingInfo = this.getBoundingInfo();
  20918. // Update octree
  20919. var bbox = boundingInfo.boundingBox;
  20920. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20921. return this._submeshesOctree;
  20922. };
  20923. // Collisions
  20924. /** @hidden */
  20925. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20926. this._generatePointsArray();
  20927. if (!this._positions) {
  20928. return this;
  20929. }
  20930. // Transformation
  20931. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20932. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20933. subMesh._lastColliderWorldVertices = [];
  20934. subMesh._trianglePlanes = [];
  20935. var start = subMesh.verticesStart;
  20936. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20937. for (var i = start; i < end; i++) {
  20938. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20939. }
  20940. }
  20941. // Collide
  20942. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20943. if (collider.collisionFound) {
  20944. collider.collidedMesh = this;
  20945. }
  20946. return this;
  20947. };
  20948. /** @hidden */
  20949. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20950. var subMeshes;
  20951. var len;
  20952. // Octrees
  20953. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20954. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20955. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20956. len = intersections.length;
  20957. subMeshes = intersections.data;
  20958. }
  20959. else {
  20960. subMeshes = this.subMeshes;
  20961. len = subMeshes.length;
  20962. }
  20963. for (var index = 0; index < len; index++) {
  20964. var subMesh = subMeshes[index];
  20965. // Bounding test
  20966. if (len > 1 && !subMesh._checkCollision(collider))
  20967. continue;
  20968. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20969. }
  20970. return this;
  20971. };
  20972. /** @hidden */
  20973. AbstractMesh.prototype._checkCollision = function (collider) {
  20974. // Bounding box test
  20975. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20976. return this;
  20977. // Transformation matrix
  20978. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20979. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20980. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20981. return this;
  20982. };
  20983. // Picking
  20984. /** @hidden */
  20985. AbstractMesh.prototype._generatePointsArray = function () {
  20986. return false;
  20987. };
  20988. /**
  20989. * Checks if the passed Ray intersects with the mesh
  20990. * @param ray defines the ray to use
  20991. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20992. * @returns the picking info
  20993. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20994. */
  20995. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20996. var pickingInfo = new BABYLON.PickingInfo();
  20997. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20998. return pickingInfo;
  20999. }
  21000. if (!this._generatePointsArray()) {
  21001. return pickingInfo;
  21002. }
  21003. var intersectInfo = null;
  21004. // Octrees
  21005. var subMeshes;
  21006. var len;
  21007. if (this._submeshesOctree && this.useOctreeForPicking) {
  21008. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  21009. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  21010. len = intersections.length;
  21011. subMeshes = intersections.data;
  21012. }
  21013. else {
  21014. subMeshes = this.subMeshes;
  21015. len = subMeshes.length;
  21016. }
  21017. for (var index = 0; index < len; index++) {
  21018. var subMesh = subMeshes[index];
  21019. // Bounding test
  21020. if (len > 1 && !subMesh.canIntersects(ray))
  21021. continue;
  21022. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21023. if (currentIntersectInfo) {
  21024. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21025. intersectInfo = currentIntersectInfo;
  21026. intersectInfo.subMeshId = index;
  21027. if (fastCheck) {
  21028. break;
  21029. }
  21030. }
  21031. }
  21032. }
  21033. if (intersectInfo) {
  21034. // Get picked point
  21035. var world = this.getWorldMatrix();
  21036. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21037. var direction = ray.direction.clone();
  21038. direction = direction.scale(intersectInfo.distance);
  21039. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21040. var pickedPoint = worldOrigin.add(worldDirection);
  21041. // Return result
  21042. pickingInfo.hit = true;
  21043. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21044. pickingInfo.pickedPoint = pickedPoint;
  21045. pickingInfo.pickedMesh = this;
  21046. pickingInfo.bu = intersectInfo.bu || 0;
  21047. pickingInfo.bv = intersectInfo.bv || 0;
  21048. pickingInfo.faceId = intersectInfo.faceId;
  21049. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21050. return pickingInfo;
  21051. }
  21052. return pickingInfo;
  21053. };
  21054. /**
  21055. * Clones the current mesh
  21056. * @param name defines the mesh name
  21057. * @param newParent defines the new mesh parent
  21058. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21059. * @returns the new mesh
  21060. */
  21061. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21062. return null;
  21063. };
  21064. /**
  21065. * Disposes all the submeshes of the current meshnp
  21066. * @returns the current mesh
  21067. */
  21068. AbstractMesh.prototype.releaseSubMeshes = function () {
  21069. if (this.subMeshes) {
  21070. while (this.subMeshes.length) {
  21071. this.subMeshes[0].dispose();
  21072. }
  21073. }
  21074. else {
  21075. this.subMeshes = new Array();
  21076. }
  21077. return this;
  21078. };
  21079. /**
  21080. * Releases resources associated with this abstract mesh.
  21081. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21082. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21083. */
  21084. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21085. var _this = this;
  21086. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21087. var index;
  21088. // Smart Array Retainers.
  21089. this.getScene().freeActiveMeshes();
  21090. this.getScene().freeRenderingGroups();
  21091. // Action manager
  21092. if (this.actionManager !== undefined && this.actionManager !== null) {
  21093. this.actionManager.dispose();
  21094. this.actionManager = null;
  21095. }
  21096. // Skeleton
  21097. this._skeleton = null;
  21098. // Physics
  21099. if (this.physicsImpostor) {
  21100. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21101. }
  21102. // Intersections in progress
  21103. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21104. var other = this._intersectionsInProgress[index];
  21105. var pos = other._intersectionsInProgress.indexOf(this);
  21106. other._intersectionsInProgress.splice(pos, 1);
  21107. }
  21108. this._intersectionsInProgress = [];
  21109. // Lights
  21110. var lights = this.getScene().lights;
  21111. lights.forEach(function (light) {
  21112. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21113. if (meshIndex !== -1) {
  21114. light.includedOnlyMeshes.splice(meshIndex, 1);
  21115. }
  21116. meshIndex = light.excludedMeshes.indexOf(_this);
  21117. if (meshIndex !== -1) {
  21118. light.excludedMeshes.splice(meshIndex, 1);
  21119. }
  21120. // Shadow generators
  21121. var generator = light.getShadowGenerator();
  21122. if (generator) {
  21123. var shadowMap = generator.getShadowMap();
  21124. if (shadowMap && shadowMap.renderList) {
  21125. meshIndex = shadowMap.renderList.indexOf(_this);
  21126. if (meshIndex !== -1) {
  21127. shadowMap.renderList.splice(meshIndex, 1);
  21128. }
  21129. }
  21130. }
  21131. });
  21132. // Edges
  21133. if (this._edgesRenderer) {
  21134. this._edgesRenderer.dispose();
  21135. this._edgesRenderer = null;
  21136. }
  21137. // SubMeshes
  21138. if (this.getClassName() !== "InstancedMesh") {
  21139. this.releaseSubMeshes();
  21140. }
  21141. // Octree
  21142. var sceneOctree = this.getScene().selectionOctree;
  21143. if (sceneOctree !== undefined && sceneOctree !== null) {
  21144. var index = sceneOctree.dynamicContent.indexOf(this);
  21145. if (index !== -1) {
  21146. sceneOctree.dynamicContent.splice(index, 1);
  21147. }
  21148. }
  21149. // Query
  21150. var engine = this.getScene().getEngine();
  21151. if (this._occlusionQuery) {
  21152. this._isOcclusionQueryInProgress = false;
  21153. engine.deleteQuery(this._occlusionQuery);
  21154. this._occlusionQuery = null;
  21155. }
  21156. // Engine
  21157. engine.wipeCaches();
  21158. // Remove from scene
  21159. this.getScene().removeMesh(this);
  21160. if (disposeMaterialAndTextures) {
  21161. if (this.material) {
  21162. this.material.dispose(false, true);
  21163. }
  21164. }
  21165. if (!doNotRecurse) {
  21166. // Particles
  21167. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21168. if (this.getScene().particleSystems[index].emitter === this) {
  21169. this.getScene().particleSystems[index].dispose();
  21170. index--;
  21171. }
  21172. }
  21173. }
  21174. // facet data
  21175. if (this._facetDataEnabled) {
  21176. this.disableFacetData();
  21177. }
  21178. this.onAfterWorldMatrixUpdateObservable.clear();
  21179. this.onCollideObservable.clear();
  21180. this.onCollisionPositionChangeObservable.clear();
  21181. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21182. };
  21183. /**
  21184. * Adds the passed mesh as a child to the current mesh
  21185. * @param mesh defines the child mesh
  21186. * @returns the current mesh
  21187. */
  21188. AbstractMesh.prototype.addChild = function (mesh) {
  21189. mesh.setParent(this);
  21190. return this;
  21191. };
  21192. /**
  21193. * Removes the passed mesh from the current mesh children list
  21194. * @param mesh defines the child mesh
  21195. * @returns the current mesh
  21196. */
  21197. AbstractMesh.prototype.removeChild = function (mesh) {
  21198. mesh.setParent(null);
  21199. return this;
  21200. };
  21201. // Facet data
  21202. /** @hidden */
  21203. AbstractMesh.prototype._initFacetData = function () {
  21204. if (!this._facetNormals) {
  21205. this._facetNormals = new Array();
  21206. }
  21207. if (!this._facetPositions) {
  21208. this._facetPositions = new Array();
  21209. }
  21210. if (!this._facetPartitioning) {
  21211. this._facetPartitioning = new Array();
  21212. }
  21213. this._facetNb = (this.getIndices().length / 3) | 0;
  21214. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21215. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21216. for (var f = 0; f < this._facetNb; f++) {
  21217. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21218. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21219. }
  21220. this._facetDataEnabled = true;
  21221. return this;
  21222. };
  21223. /**
  21224. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21225. * This method can be called within the render loop.
  21226. * 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
  21227. * @returns the current mesh
  21228. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21229. */
  21230. AbstractMesh.prototype.updateFacetData = function () {
  21231. if (!this._facetDataEnabled) {
  21232. this._initFacetData();
  21233. }
  21234. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21235. var indices = this.getIndices();
  21236. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21237. var bInfo = this.getBoundingInfo();
  21238. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21239. // init arrays, matrix and sort function on first call
  21240. this._facetDepthSortEnabled = true;
  21241. if (indices instanceof Uint16Array) {
  21242. this._depthSortedIndices = new Uint16Array(indices);
  21243. }
  21244. else if (indices instanceof Uint32Array) {
  21245. this._depthSortedIndices = new Uint32Array(indices);
  21246. }
  21247. else {
  21248. var needs32bits = false;
  21249. for (var i = 0; i < indices.length; i++) {
  21250. if (indices[i] > 65535) {
  21251. needs32bits = true;
  21252. break;
  21253. }
  21254. }
  21255. if (needs32bits) {
  21256. this._depthSortedIndices = new Uint32Array(indices);
  21257. }
  21258. else {
  21259. this._depthSortedIndices = new Uint16Array(indices);
  21260. }
  21261. }
  21262. this._facetDepthSortFunction = function (f1, f2) {
  21263. return (f2.sqDistance - f1.sqDistance);
  21264. };
  21265. if (!this._facetDepthSortFrom) {
  21266. var camera = this.getScene().activeCamera;
  21267. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21268. }
  21269. this._depthSortedFacets = [];
  21270. for (var f = 0; f < this._facetNb; f++) {
  21271. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21272. this._depthSortedFacets.push(depthSortedFacet);
  21273. }
  21274. this._invertedMatrix = BABYLON.Matrix.Identity();
  21275. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21276. }
  21277. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21278. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21279. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21280. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21281. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21282. this._subDiv.max = this._partitioningSubdivisions;
  21283. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21284. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21285. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21286. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21287. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21288. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21289. // set the parameters for ComputeNormals()
  21290. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21291. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21292. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21293. this._facetParameters.bInfo = bInfo;
  21294. this._facetParameters.bbSize = this._bbSize;
  21295. this._facetParameters.subDiv = this._subDiv;
  21296. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21297. this._facetParameters.depthSort = this._facetDepthSort;
  21298. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21299. this.computeWorldMatrix(true);
  21300. this._worldMatrix.invertToRef(this._invertedMatrix);
  21301. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21302. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21303. }
  21304. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21305. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21306. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21307. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21308. var l = (this._depthSortedIndices.length / 3) | 0;
  21309. for (var f = 0; f < l; f++) {
  21310. var sind = this._depthSortedFacets[f].ind;
  21311. this._depthSortedIndices[f * 3] = indices[sind];
  21312. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21313. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21314. }
  21315. this.updateIndices(this._depthSortedIndices);
  21316. }
  21317. return this;
  21318. };
  21319. /**
  21320. * Returns the facetLocalNormals array.
  21321. * The normals are expressed in the mesh local spac
  21322. * @returns an array of Vector3
  21323. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21324. */
  21325. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21326. if (!this._facetNormals) {
  21327. this.updateFacetData();
  21328. }
  21329. return this._facetNormals;
  21330. };
  21331. /**
  21332. * Returns the facetLocalPositions array.
  21333. * The facet positions are expressed in the mesh local space
  21334. * @returns an array of Vector3
  21335. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21336. */
  21337. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21338. if (!this._facetPositions) {
  21339. this.updateFacetData();
  21340. }
  21341. return this._facetPositions;
  21342. };
  21343. /**
  21344. * Returns the facetLocalPartioning array
  21345. * @returns an array of array of numbers
  21346. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21347. */
  21348. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21349. if (!this._facetPartitioning) {
  21350. this.updateFacetData();
  21351. }
  21352. return this._facetPartitioning;
  21353. };
  21354. /**
  21355. * Returns the i-th facet position in the world system.
  21356. * This method allocates a new Vector3 per call
  21357. * @param i defines the facet index
  21358. * @returns a new Vector3
  21359. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21360. */
  21361. AbstractMesh.prototype.getFacetPosition = function (i) {
  21362. var pos = BABYLON.Vector3.Zero();
  21363. this.getFacetPositionToRef(i, pos);
  21364. return pos;
  21365. };
  21366. /**
  21367. * Sets the reference Vector3 with the i-th facet position in the world system
  21368. * @param i defines the facet index
  21369. * @param ref defines the target vector
  21370. * @returns the current mesh
  21371. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21372. */
  21373. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21374. var localPos = (this.getFacetLocalPositions())[i];
  21375. var world = this.getWorldMatrix();
  21376. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21377. return this;
  21378. };
  21379. /**
  21380. * Returns the i-th facet normal in the world system.
  21381. * This method allocates a new Vector3 per call
  21382. * @param i defines the facet index
  21383. * @returns a new Vector3
  21384. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21385. */
  21386. AbstractMesh.prototype.getFacetNormal = function (i) {
  21387. var norm = BABYLON.Vector3.Zero();
  21388. this.getFacetNormalToRef(i, norm);
  21389. return norm;
  21390. };
  21391. /**
  21392. * Sets the reference Vector3 with the i-th facet normal in the world system
  21393. * @param i defines the facet index
  21394. * @param ref defines the target vector
  21395. * @returns the current mesh
  21396. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21397. */
  21398. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21399. var localNorm = (this.getFacetLocalNormals())[i];
  21400. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21401. return this;
  21402. };
  21403. /**
  21404. * 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)
  21405. * @param x defines x coordinate
  21406. * @param y defines y coordinate
  21407. * @param z defines z coordinate
  21408. * @returns the array of facet indexes
  21409. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21410. */
  21411. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21412. var bInfo = this.getBoundingInfo();
  21413. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21414. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21415. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21416. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21417. return null;
  21418. }
  21419. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21420. };
  21421. /**
  21422. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21423. * @param projected sets as the (x,y,z) world projection on the facet
  21424. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21425. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21426. * @param x defines x coordinate
  21427. * @param y defines y coordinate
  21428. * @param z defines z coordinate
  21429. * @returns the face index if found (or null instead)
  21430. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21431. */
  21432. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21433. if (checkFace === void 0) { checkFace = false; }
  21434. if (facing === void 0) { facing = true; }
  21435. var world = this.getWorldMatrix();
  21436. var invMat = BABYLON.Tmp.Matrix[5];
  21437. world.invertToRef(invMat);
  21438. var invVect = BABYLON.Tmp.Vector3[8];
  21439. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21440. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21441. if (projected) {
  21442. // tranform the local computed projected vector to world coordinates
  21443. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21444. }
  21445. return closest;
  21446. };
  21447. /**
  21448. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21449. * @param projected sets as the (x,y,z) local projection on the facet
  21450. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21451. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21452. * @param x defines x coordinate
  21453. * @param y defines y coordinate
  21454. * @param z defines z coordinate
  21455. * @returns the face index if found (or null instead)
  21456. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21457. */
  21458. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21459. if (checkFace === void 0) { checkFace = false; }
  21460. if (facing === void 0) { facing = true; }
  21461. var closest = null;
  21462. var tmpx = 0.0;
  21463. var tmpy = 0.0;
  21464. var tmpz = 0.0;
  21465. var d = 0.0; // tmp dot facet normal * facet position
  21466. var t0 = 0.0;
  21467. var projx = 0.0;
  21468. var projy = 0.0;
  21469. var projz = 0.0;
  21470. // Get all the facets in the same partitioning block than (x, y, z)
  21471. var facetPositions = this.getFacetLocalPositions();
  21472. var facetNormals = this.getFacetLocalNormals();
  21473. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21474. if (!facetsInBlock) {
  21475. return null;
  21476. }
  21477. // Get the closest facet to (x, y, z)
  21478. var shortest = Number.MAX_VALUE; // init distance vars
  21479. var tmpDistance = shortest;
  21480. var fib; // current facet in the block
  21481. var norm; // current facet normal
  21482. var p0; // current facet barycenter position
  21483. // loop on all the facets in the current partitioning block
  21484. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21485. fib = facetsInBlock[idx];
  21486. norm = facetNormals[fib];
  21487. p0 = facetPositions[fib];
  21488. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21489. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21490. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21491. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21492. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21493. projx = x + norm.x * t0;
  21494. projy = y + norm.y * t0;
  21495. projz = z + norm.z * t0;
  21496. tmpx = projx - x;
  21497. tmpy = projy - y;
  21498. tmpz = projz - z;
  21499. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21500. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21501. shortest = tmpDistance;
  21502. closest = fib;
  21503. if (projected) {
  21504. projected.x = projx;
  21505. projected.y = projy;
  21506. projected.z = projz;
  21507. }
  21508. }
  21509. }
  21510. }
  21511. return closest;
  21512. };
  21513. /**
  21514. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21515. * @returns the parameters
  21516. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21517. */
  21518. AbstractMesh.prototype.getFacetDataParameters = function () {
  21519. return this._facetParameters;
  21520. };
  21521. /**
  21522. * Disables the feature FacetData and frees the related memory
  21523. * @returns the current mesh
  21524. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21525. */
  21526. AbstractMesh.prototype.disableFacetData = function () {
  21527. if (this._facetDataEnabled) {
  21528. this._facetDataEnabled = false;
  21529. this._facetPositions = new Array();
  21530. this._facetNormals = new Array();
  21531. this._facetPartitioning = new Array();
  21532. this._facetParameters = null;
  21533. this._depthSortedIndices = new Uint32Array(0);
  21534. }
  21535. return this;
  21536. };
  21537. /**
  21538. * Updates the AbstractMesh indices array
  21539. * @param indices defines the data source
  21540. * @returns the current mesh
  21541. */
  21542. AbstractMesh.prototype.updateIndices = function (indices) {
  21543. return this;
  21544. };
  21545. /**
  21546. * Creates new normals data for the mesh
  21547. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21548. * @returns the current mesh
  21549. */
  21550. AbstractMesh.prototype.createNormals = function (updatable) {
  21551. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21552. var indices = this.getIndices();
  21553. var normals;
  21554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21555. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21556. }
  21557. else {
  21558. normals = [];
  21559. }
  21560. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21561. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21562. return this;
  21563. };
  21564. /**
  21565. * Align the mesh with a normal
  21566. * @param normal defines the normal to use
  21567. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21568. * @returns the current mesh
  21569. */
  21570. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21571. if (!upDirection) {
  21572. upDirection = BABYLON.Axis.Y;
  21573. }
  21574. var axisX = BABYLON.Tmp.Vector3[0];
  21575. var axisZ = BABYLON.Tmp.Vector3[1];
  21576. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21577. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21578. if (this.rotationQuaternion) {
  21579. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21580. }
  21581. else {
  21582. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21583. }
  21584. return this;
  21585. };
  21586. /** @hidden */
  21587. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21588. var engine = this.getEngine();
  21589. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21590. this._isOccluded = false;
  21591. return;
  21592. }
  21593. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21594. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21595. if (isOcclusionQueryAvailable) {
  21596. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21597. this._isOcclusionQueryInProgress = false;
  21598. this._occlusionInternalRetryCounter = 0;
  21599. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21600. }
  21601. else {
  21602. this._occlusionInternalRetryCounter++;
  21603. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21604. this._isOcclusionQueryInProgress = false;
  21605. this._occlusionInternalRetryCounter = 0;
  21606. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21607. // if strict continue the last state of the object.
  21608. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21609. }
  21610. else {
  21611. return;
  21612. }
  21613. }
  21614. }
  21615. var scene = this.getScene();
  21616. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21617. if (!this._occlusionQuery) {
  21618. this._occlusionQuery = engine.createQuery();
  21619. }
  21620. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21621. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21622. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21623. this._isOcclusionQueryInProgress = true;
  21624. };
  21625. /** No occlusion */
  21626. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21627. /** Occlusion set to optimisitic */
  21628. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21629. /** Occlusion set to strict */
  21630. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21631. /** Use an accurante occlusion algorithm */
  21632. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21633. /** Use a conservative occlusion algorithm */
  21634. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21635. return AbstractMesh;
  21636. }(BABYLON.TransformNode));
  21637. BABYLON.AbstractMesh = AbstractMesh;
  21638. })(BABYLON || (BABYLON = {}));
  21639. //# sourceMappingURL=babylon.abstractMesh.js.map
  21640. var BABYLON;
  21641. (function (BABYLON) {
  21642. /**
  21643. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21644. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21645. * 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.
  21646. */
  21647. var Light = /** @class */ (function (_super) {
  21648. __extends(Light, _super);
  21649. /**
  21650. * Creates a Light object in the scene.
  21651. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21652. * @param name The firendly name of the light
  21653. * @param scene The scene the light belongs too
  21654. */
  21655. function Light(name, scene) {
  21656. var _this = _super.call(this, name, scene) || this;
  21657. /**
  21658. * Diffuse gives the basic color to an object.
  21659. */
  21660. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21661. /**
  21662. * Specular produces a highlight color on an object.
  21663. * Note: This is note affecting PBR materials.
  21664. */
  21665. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21666. /**
  21667. * Strength of the light.
  21668. * Note: By default it is define in the framework own unit.
  21669. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21670. */
  21671. _this.intensity = 1.0;
  21672. /**
  21673. * Defines how far from the source the light is impacting in scene units.
  21674. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21675. */
  21676. _this.range = Number.MAX_VALUE;
  21677. /**
  21678. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21679. * of light.
  21680. */
  21681. _this._photometricScale = 1.0;
  21682. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21683. _this._radius = 0.00001;
  21684. /**
  21685. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21686. * exceeding the number allowed of the materials.
  21687. */
  21688. _this.renderPriority = 0;
  21689. _this._shadowEnabled = true;
  21690. _this._excludeWithLayerMask = 0;
  21691. _this._includeOnlyWithLayerMask = 0;
  21692. _this._lightmapMode = 0;
  21693. /**
  21694. * @hidden Internal use only.
  21695. */
  21696. _this._excludedMeshesIds = new Array();
  21697. /**
  21698. * @hidden Internal use only.
  21699. */
  21700. _this._includedOnlyMeshesIds = new Array();
  21701. _this.getScene().addLight(_this);
  21702. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21703. _this._buildUniformLayout();
  21704. _this.includedOnlyMeshes = new Array();
  21705. _this.excludedMeshes = new Array();
  21706. _this._resyncMeshes();
  21707. return _this;
  21708. }
  21709. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21710. /**
  21711. * If every light affecting the material is in this lightmapMode,
  21712. * material.lightmapTexture adds or multiplies
  21713. * (depends on material.useLightmapAsShadowmap)
  21714. * after every other light calculations.
  21715. */
  21716. get: function () {
  21717. return Light._LIGHTMAP_DEFAULT;
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21723. /**
  21724. * material.lightmapTexture as only diffuse lighting from this light
  21725. * adds only specular lighting from this light
  21726. * adds dynamic shadows
  21727. */
  21728. get: function () {
  21729. return Light._LIGHTMAP_SPECULAR;
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21735. /**
  21736. * material.lightmapTexture as only lighting
  21737. * no light calculation from this light
  21738. * only adds dynamic shadows from this light
  21739. */
  21740. get: function () {
  21741. return Light._LIGHTMAP_SHADOWSONLY;
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21747. /**
  21748. * Each light type uses the default quantity according to its type:
  21749. * point/spot lights use luminous intensity
  21750. * directional lights use illuminance
  21751. */
  21752. get: function () {
  21753. return Light._INTENSITYMODE_AUTOMATIC;
  21754. },
  21755. enumerable: true,
  21756. configurable: true
  21757. });
  21758. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21759. /**
  21760. * lumen (lm)
  21761. */
  21762. get: function () {
  21763. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21764. },
  21765. enumerable: true,
  21766. configurable: true
  21767. });
  21768. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21769. /**
  21770. * candela (lm/sr)
  21771. */
  21772. get: function () {
  21773. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21779. /**
  21780. * lux (lm/m^2)
  21781. */
  21782. get: function () {
  21783. return Light._INTENSITYMODE_ILLUMINANCE;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21789. /**
  21790. * nit (cd/m^2)
  21791. */
  21792. get: function () {
  21793. return Light._INTENSITYMODE_LUMINANCE;
  21794. },
  21795. enumerable: true,
  21796. configurable: true
  21797. });
  21798. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21799. /**
  21800. * Light type const id of the point light.
  21801. */
  21802. get: function () {
  21803. return Light._LIGHTTYPEID_POINTLIGHT;
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21809. /**
  21810. * Light type const id of the directional light.
  21811. */
  21812. get: function () {
  21813. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21819. /**
  21820. * Light type const id of the spot light.
  21821. */
  21822. get: function () {
  21823. return Light._LIGHTTYPEID_SPOTLIGHT;
  21824. },
  21825. enumerable: true,
  21826. configurable: true
  21827. });
  21828. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21829. /**
  21830. * Light type const id of the hemispheric light.
  21831. */
  21832. get: function () {
  21833. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Light.prototype, "intensityMode", {
  21839. /**
  21840. * Gets the photometric scale used to interpret the intensity.
  21841. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21842. */
  21843. get: function () {
  21844. return this._intensityMode;
  21845. },
  21846. /**
  21847. * Sets the photometric scale used to interpret the intensity.
  21848. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21849. */
  21850. set: function (value) {
  21851. this._intensityMode = value;
  21852. this._computePhotometricScale();
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. ;
  21858. ;
  21859. Object.defineProperty(Light.prototype, "radius", {
  21860. /**
  21861. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21862. */
  21863. get: function () {
  21864. return this._radius;
  21865. },
  21866. /**
  21867. * sets the light radius used by PBR Materials to simulate soft area lights.
  21868. */
  21869. set: function (value) {
  21870. this._radius = value;
  21871. this._computePhotometricScale();
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. ;
  21877. ;
  21878. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21879. /**
  21880. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21881. * the current shadow generator.
  21882. */
  21883. get: function () {
  21884. return this._shadowEnabled;
  21885. },
  21886. /**
  21887. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21888. * the current shadow generator.
  21889. */
  21890. set: function (value) {
  21891. if (this._shadowEnabled === value) {
  21892. return;
  21893. }
  21894. this._shadowEnabled = value;
  21895. this._markMeshesAsLightDirty();
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21901. /**
  21902. * Gets the only meshes impacted by this light.
  21903. */
  21904. get: function () {
  21905. return this._includedOnlyMeshes;
  21906. },
  21907. /**
  21908. * Sets the only meshes impacted by this light.
  21909. */
  21910. set: function (value) {
  21911. this._includedOnlyMeshes = value;
  21912. this._hookArrayForIncludedOnly(value);
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21918. /**
  21919. * Gets the meshes not impacted by this light.
  21920. */
  21921. get: function () {
  21922. return this._excludedMeshes;
  21923. },
  21924. /**
  21925. * Sets the meshes not impacted by this light.
  21926. */
  21927. set: function (value) {
  21928. this._excludedMeshes = value;
  21929. this._hookArrayForExcluded(value);
  21930. },
  21931. enumerable: true,
  21932. configurable: true
  21933. });
  21934. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21935. /**
  21936. * Gets the layer id use to find what meshes are not impacted by the light.
  21937. * Inactive if 0
  21938. */
  21939. get: function () {
  21940. return this._excludeWithLayerMask;
  21941. },
  21942. /**
  21943. * Sets the layer id use to find what meshes are not impacted by the light.
  21944. * Inactive if 0
  21945. */
  21946. set: function (value) {
  21947. this._excludeWithLayerMask = value;
  21948. this._resyncMeshes();
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21954. /**
  21955. * Gets the layer id use to find what meshes are impacted by the light.
  21956. * Inactive if 0
  21957. */
  21958. get: function () {
  21959. return this._includeOnlyWithLayerMask;
  21960. },
  21961. /**
  21962. * Sets the layer id use to find what meshes are impacted by the light.
  21963. * Inactive if 0
  21964. */
  21965. set: function (value) {
  21966. this._includeOnlyWithLayerMask = value;
  21967. this._resyncMeshes();
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Light.prototype, "lightmapMode", {
  21973. /**
  21974. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21975. */
  21976. get: function () {
  21977. return this._lightmapMode;
  21978. },
  21979. /**
  21980. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21981. */
  21982. set: function (value) {
  21983. if (this._lightmapMode === value) {
  21984. return;
  21985. }
  21986. this._lightmapMode = value;
  21987. this._markMeshesAsLightDirty();
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. /**
  21993. * Returns the string "Light".
  21994. * @returns the class name
  21995. */
  21996. Light.prototype.getClassName = function () {
  21997. return "Light";
  21998. };
  21999. /**
  22000. * Converts the light information to a readable string for debug purpose.
  22001. * @param fullDetails Supports for multiple levels of logging within scene loading
  22002. * @returns the human readable light info
  22003. */
  22004. Light.prototype.toString = function (fullDetails) {
  22005. var ret = "Name: " + this.name;
  22006. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22007. if (this.animations) {
  22008. for (var i = 0; i < this.animations.length; i++) {
  22009. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22010. }
  22011. }
  22012. if (fullDetails) {
  22013. }
  22014. return ret;
  22015. };
  22016. /**
  22017. * Set the enabled state of this node.
  22018. * @param value - the new enabled state
  22019. */
  22020. Light.prototype.setEnabled = function (value) {
  22021. _super.prototype.setEnabled.call(this, value);
  22022. this._resyncMeshes();
  22023. };
  22024. /**
  22025. * Returns the Light associated shadow generator if any.
  22026. * @return the associated shadow generator.
  22027. */
  22028. Light.prototype.getShadowGenerator = function () {
  22029. return this._shadowGenerator;
  22030. };
  22031. /**
  22032. * Returns a Vector3, the absolute light position in the World.
  22033. * @returns the world space position of the light
  22034. */
  22035. Light.prototype.getAbsolutePosition = function () {
  22036. return BABYLON.Vector3.Zero();
  22037. };
  22038. /**
  22039. * Specifies if the light will affect the passed mesh.
  22040. * @param mesh The mesh to test against the light
  22041. * @return true the mesh is affected otherwise, false.
  22042. */
  22043. Light.prototype.canAffectMesh = function (mesh) {
  22044. if (!mesh) {
  22045. return true;
  22046. }
  22047. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22048. return false;
  22049. }
  22050. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22051. return false;
  22052. }
  22053. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22054. return false;
  22055. }
  22056. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22057. return false;
  22058. }
  22059. return true;
  22060. };
  22061. /**
  22062. * Computes and Returns the light World matrix.
  22063. * @returns the world matrix
  22064. */
  22065. Light.prototype.getWorldMatrix = function () {
  22066. this._currentRenderId = this.getScene().getRenderId();
  22067. this._childRenderId = this._currentRenderId;
  22068. var worldMatrix = this._getWorldMatrix();
  22069. if (this.parent && this.parent.getWorldMatrix) {
  22070. if (!this._parentedWorldMatrix) {
  22071. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22072. }
  22073. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22074. this._markSyncedWithParent();
  22075. return this._parentedWorldMatrix;
  22076. }
  22077. return worldMatrix;
  22078. };
  22079. /**
  22080. * Sort function to order lights for rendering.
  22081. * @param a First Light object to compare to second.
  22082. * @param b Second Light object to compare first.
  22083. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22084. */
  22085. Light.CompareLightsPriority = function (a, b) {
  22086. //shadow-casting lights have priority over non-shadow-casting lights
  22087. //the renderPrioirty is a secondary sort criterion
  22088. if (a.shadowEnabled !== b.shadowEnabled) {
  22089. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22090. }
  22091. return b.renderPriority - a.renderPriority;
  22092. };
  22093. /**
  22094. * Releases resources associated with this node.
  22095. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22096. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22097. */
  22098. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22099. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22100. if (this._shadowGenerator) {
  22101. this._shadowGenerator.dispose();
  22102. this._shadowGenerator = null;
  22103. }
  22104. // Animations
  22105. this.getScene().stopAnimation(this);
  22106. // Remove from meshes
  22107. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22108. var mesh = _a[_i];
  22109. mesh._removeLightSource(this);
  22110. }
  22111. this._uniformBuffer.dispose();
  22112. // Remove from scene
  22113. this.getScene().removeLight(this);
  22114. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22115. };
  22116. /**
  22117. * Returns the light type ID (integer).
  22118. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22119. */
  22120. Light.prototype.getTypeID = function () {
  22121. return 0;
  22122. };
  22123. /**
  22124. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22125. * @returns the scaled intensity in intensity mode unit
  22126. */
  22127. Light.prototype.getScaledIntensity = function () {
  22128. return this._photometricScale * this.intensity;
  22129. };
  22130. /**
  22131. * Returns a new Light object, named "name", from the current one.
  22132. * @param name The name of the cloned light
  22133. * @returns the new created light
  22134. */
  22135. Light.prototype.clone = function (name) {
  22136. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22137. if (!constructor) {
  22138. return null;
  22139. }
  22140. return BABYLON.SerializationHelper.Clone(constructor, this);
  22141. };
  22142. /**
  22143. * Serializes the current light into a Serialization object.
  22144. * @returns the serialized object.
  22145. */
  22146. Light.prototype.serialize = function () {
  22147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22148. // Type
  22149. serializationObject.type = this.getTypeID();
  22150. // Parent
  22151. if (this.parent) {
  22152. serializationObject.parentId = this.parent.id;
  22153. }
  22154. // Inclusion / exclusions
  22155. if (this.excludedMeshes.length > 0) {
  22156. serializationObject.excludedMeshesIds = [];
  22157. this.excludedMeshes.forEach(function (mesh) {
  22158. serializationObject.excludedMeshesIds.push(mesh.id);
  22159. });
  22160. }
  22161. if (this.includedOnlyMeshes.length > 0) {
  22162. serializationObject.includedOnlyMeshesIds = [];
  22163. this.includedOnlyMeshes.forEach(function (mesh) {
  22164. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22165. });
  22166. }
  22167. // Animations
  22168. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22169. serializationObject.ranges = this.serializeAnimationRanges();
  22170. return serializationObject;
  22171. };
  22172. /**
  22173. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22174. * This new light is named "name" and added to the passed scene.
  22175. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22176. * @param name The friendly name of the light
  22177. * @param scene The scene the new light will belong to
  22178. * @returns the constructor function
  22179. */
  22180. Light.GetConstructorFromName = function (type, name, scene) {
  22181. switch (type) {
  22182. case 0:
  22183. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22184. case 1:
  22185. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22186. case 2:
  22187. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22188. case 3:
  22189. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22190. }
  22191. return null;
  22192. };
  22193. /**
  22194. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22195. * @param parsedLight The JSON representation of the light
  22196. * @param scene The scene to create the parsed light in
  22197. * @returns the created light after parsing
  22198. */
  22199. Light.Parse = function (parsedLight, scene) {
  22200. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22201. if (!constructor) {
  22202. return null;
  22203. }
  22204. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22205. // Inclusion / exclusions
  22206. if (parsedLight.excludedMeshesIds) {
  22207. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22208. }
  22209. if (parsedLight.includedOnlyMeshesIds) {
  22210. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22211. }
  22212. // Parent
  22213. if (parsedLight.parentId) {
  22214. light._waitingParentId = parsedLight.parentId;
  22215. }
  22216. // Animations
  22217. if (parsedLight.animations) {
  22218. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22219. var parsedAnimation = parsedLight.animations[animationIndex];
  22220. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22221. }
  22222. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22223. }
  22224. if (parsedLight.autoAnimate) {
  22225. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22226. }
  22227. return light;
  22228. };
  22229. Light.prototype._hookArrayForExcluded = function (array) {
  22230. var _this = this;
  22231. var oldPush = array.push;
  22232. array.push = function () {
  22233. var items = [];
  22234. for (var _i = 0; _i < arguments.length; _i++) {
  22235. items[_i] = arguments[_i];
  22236. }
  22237. var result = oldPush.apply(array, items);
  22238. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22239. var item = items_1[_a];
  22240. item._resyncLighSource(_this);
  22241. }
  22242. return result;
  22243. };
  22244. var oldSplice = array.splice;
  22245. array.splice = function (index, deleteCount) {
  22246. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22247. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22248. var item = deleted_1[_i];
  22249. item._resyncLighSource(_this);
  22250. }
  22251. return deleted;
  22252. };
  22253. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22254. var item = array_1[_i];
  22255. item._resyncLighSource(this);
  22256. }
  22257. };
  22258. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22259. var _this = this;
  22260. var oldPush = array.push;
  22261. array.push = function () {
  22262. var items = [];
  22263. for (var _i = 0; _i < arguments.length; _i++) {
  22264. items[_i] = arguments[_i];
  22265. }
  22266. var result = oldPush.apply(array, items);
  22267. _this._resyncMeshes();
  22268. return result;
  22269. };
  22270. var oldSplice = array.splice;
  22271. array.splice = function (index, deleteCount) {
  22272. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22273. _this._resyncMeshes();
  22274. return deleted;
  22275. };
  22276. this._resyncMeshes();
  22277. };
  22278. Light.prototype._resyncMeshes = function () {
  22279. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22280. var mesh = _a[_i];
  22281. mesh._resyncLighSource(this);
  22282. }
  22283. };
  22284. /**
  22285. * Forces the meshes to update their light related information in their rendering used effects
  22286. * @hidden Internal Use Only
  22287. */
  22288. Light.prototype._markMeshesAsLightDirty = function () {
  22289. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22290. var mesh = _a[_i];
  22291. if (mesh._lightSources.indexOf(this) !== -1) {
  22292. mesh._markSubMeshesAsLightDirty();
  22293. }
  22294. }
  22295. };
  22296. /**
  22297. * Recomputes the cached photometric scale if needed.
  22298. */
  22299. Light.prototype._computePhotometricScale = function () {
  22300. this._photometricScale = this._getPhotometricScale();
  22301. this.getScene().resetCachedMaterial();
  22302. };
  22303. /**
  22304. * Returns the Photometric Scale according to the light type and intensity mode.
  22305. */
  22306. Light.prototype._getPhotometricScale = function () {
  22307. var photometricScale = 0.0;
  22308. var lightTypeID = this.getTypeID();
  22309. //get photometric mode
  22310. var photometricMode = this.intensityMode;
  22311. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22312. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22313. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22314. }
  22315. else {
  22316. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22317. }
  22318. }
  22319. //compute photometric scale
  22320. switch (lightTypeID) {
  22321. case Light.LIGHTTYPEID_POINTLIGHT:
  22322. case Light.LIGHTTYPEID_SPOTLIGHT:
  22323. switch (photometricMode) {
  22324. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22325. photometricScale = 1.0 / (4.0 * Math.PI);
  22326. break;
  22327. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22328. photometricScale = 1.0;
  22329. break;
  22330. case Light.INTENSITYMODE_LUMINANCE:
  22331. photometricScale = this.radius * this.radius;
  22332. break;
  22333. }
  22334. break;
  22335. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22336. switch (photometricMode) {
  22337. case Light.INTENSITYMODE_ILLUMINANCE:
  22338. photometricScale = 1.0;
  22339. break;
  22340. case Light.INTENSITYMODE_LUMINANCE:
  22341. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22342. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22343. var apexAngleRadians = this.radius;
  22344. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22345. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22346. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22347. photometricScale = solidAngle;
  22348. break;
  22349. }
  22350. break;
  22351. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22352. // No fall off in hemisperic light.
  22353. photometricScale = 1.0;
  22354. break;
  22355. }
  22356. return photometricScale;
  22357. };
  22358. /**
  22359. * Reorder the light in the scene according to their defined priority.
  22360. * @hidden Internal Use Only
  22361. */
  22362. Light.prototype._reorderLightsInScene = function () {
  22363. var scene = this.getScene();
  22364. if (this._renderPriority != 0) {
  22365. scene.requireLightSorting = true;
  22366. }
  22367. this.getScene().sortLightsByPriority();
  22368. };
  22369. //lightmapMode Consts
  22370. Light._LIGHTMAP_DEFAULT = 0;
  22371. Light._LIGHTMAP_SPECULAR = 1;
  22372. Light._LIGHTMAP_SHADOWSONLY = 2;
  22373. // Intensity Mode Consts
  22374. Light._INTENSITYMODE_AUTOMATIC = 0;
  22375. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22376. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22377. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22378. Light._INTENSITYMODE_LUMINANCE = 4;
  22379. // Light types ids const.
  22380. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22381. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22382. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22383. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22384. __decorate([
  22385. BABYLON.serializeAsColor3()
  22386. ], Light.prototype, "diffuse", void 0);
  22387. __decorate([
  22388. BABYLON.serializeAsColor3()
  22389. ], Light.prototype, "specular", void 0);
  22390. __decorate([
  22391. BABYLON.serialize()
  22392. ], Light.prototype, "intensity", void 0);
  22393. __decorate([
  22394. BABYLON.serialize()
  22395. ], Light.prototype, "range", void 0);
  22396. __decorate([
  22397. BABYLON.serialize()
  22398. ], Light.prototype, "intensityMode", null);
  22399. __decorate([
  22400. BABYLON.serialize()
  22401. ], Light.prototype, "radius", null);
  22402. __decorate([
  22403. BABYLON.serialize()
  22404. ], Light.prototype, "_renderPriority", void 0);
  22405. __decorate([
  22406. BABYLON.expandToProperty("_reorderLightsInScene")
  22407. ], Light.prototype, "renderPriority", void 0);
  22408. __decorate([
  22409. BABYLON.serialize("shadowEnabled")
  22410. ], Light.prototype, "_shadowEnabled", void 0);
  22411. __decorate([
  22412. BABYLON.serialize("excludeWithLayerMask")
  22413. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22414. __decorate([
  22415. BABYLON.serialize("includeOnlyWithLayerMask")
  22416. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22417. __decorate([
  22418. BABYLON.serialize("lightmapMode")
  22419. ], Light.prototype, "_lightmapMode", void 0);
  22420. return Light;
  22421. }(BABYLON.Node));
  22422. BABYLON.Light = Light;
  22423. })(BABYLON || (BABYLON = {}));
  22424. //# sourceMappingURL=babylon.light.js.map
  22425. var BABYLON;
  22426. (function (BABYLON) {
  22427. var Camera = /** @class */ (function (_super) {
  22428. __extends(Camera, _super);
  22429. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22430. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22431. var _this = _super.call(this, name, scene) || this;
  22432. /**
  22433. * The vector the camera should consider as up.
  22434. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22435. */
  22436. _this.upVector = BABYLON.Vector3.Up();
  22437. _this.orthoLeft = null;
  22438. _this.orthoRight = null;
  22439. _this.orthoBottom = null;
  22440. _this.orthoTop = null;
  22441. /**
  22442. * FOV is set in Radians. (default is 0.8)
  22443. */
  22444. _this.fov = 0.8;
  22445. _this.minZ = 1;
  22446. _this.maxZ = 10000.0;
  22447. _this.inertia = 0.9;
  22448. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22449. _this.isIntermediate = false;
  22450. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22451. /**
  22452. * Restricts the camera to viewing objects with the same layerMask.
  22453. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22454. */
  22455. _this.layerMask = 0x0FFFFFFF;
  22456. /**
  22457. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22458. */
  22459. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22460. // Camera rig members
  22461. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22462. _this._rigCameras = new Array();
  22463. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22464. _this._skipRendering = false;
  22465. _this.customRenderTargets = new Array();
  22466. // Observables
  22467. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22468. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22469. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22470. _this.onRestoreStateObservable = new BABYLON.Observable();
  22471. // Cache
  22472. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22473. _this._projectionMatrix = new BABYLON.Matrix();
  22474. _this._doNotComputeProjectionMatrix = false;
  22475. _this._worldMatrix = BABYLON.Matrix.Identity();
  22476. _this._postProcesses = new Array();
  22477. _this._transformMatrix = BABYLON.Matrix.Zero();
  22478. _this._activeMeshes = new BABYLON.SmartArray(256);
  22479. _this._globalPosition = BABYLON.Vector3.Zero();
  22480. _this._refreshFrustumPlanes = true;
  22481. _this.getScene().addCamera(_this);
  22482. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22483. _this.getScene().activeCamera = _this;
  22484. }
  22485. _this.position = position;
  22486. return _this;
  22487. }
  22488. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22489. get: function () {
  22490. return Camera._PERSPECTIVE_CAMERA;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22496. get: function () {
  22497. return Camera._ORTHOGRAPHIC_CAMERA;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22503. /**
  22504. * This is the default FOV mode for perspective cameras.
  22505. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22506. *
  22507. */
  22508. get: function () {
  22509. return Camera._FOVMODE_VERTICAL_FIXED;
  22510. },
  22511. enumerable: true,
  22512. configurable: true
  22513. });
  22514. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22515. /**
  22516. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22517. *
  22518. */
  22519. get: function () {
  22520. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22526. get: function () {
  22527. return Camera._RIG_MODE_NONE;
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22533. get: function () {
  22534. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22540. get: function () {
  22541. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22547. get: function () {
  22548. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22549. },
  22550. enumerable: true,
  22551. configurable: true
  22552. });
  22553. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22554. get: function () {
  22555. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22561. get: function () {
  22562. return Camera._RIG_MODE_VR;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22568. get: function () {
  22569. return Camera._RIG_MODE_WEBVR;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. /**
  22575. * Store current camera state (fov, position, etc..)
  22576. */
  22577. Camera.prototype.storeState = function () {
  22578. this._stateStored = true;
  22579. this._storedFov = this.fov;
  22580. return this;
  22581. };
  22582. /**
  22583. * Restores the camera state values if it has been stored. You must call storeState() first
  22584. */
  22585. Camera.prototype._restoreStateValues = function () {
  22586. if (!this._stateStored) {
  22587. return false;
  22588. }
  22589. this.fov = this._storedFov;
  22590. return true;
  22591. };
  22592. /**
  22593. * Restored camera state. You must call storeState() first
  22594. */
  22595. Camera.prototype.restoreState = function () {
  22596. if (this._restoreStateValues()) {
  22597. this.onRestoreStateObservable.notifyObservers(this);
  22598. return true;
  22599. }
  22600. return false;
  22601. };
  22602. Camera.prototype.getClassName = function () {
  22603. return "Camera";
  22604. };
  22605. /**
  22606. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22607. */
  22608. Camera.prototype.toString = function (fullDetails) {
  22609. var ret = "Name: " + this.name;
  22610. ret += ", type: " + this.getClassName();
  22611. if (this.animations) {
  22612. for (var i = 0; i < this.animations.length; i++) {
  22613. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22614. }
  22615. }
  22616. if (fullDetails) {
  22617. }
  22618. return ret;
  22619. };
  22620. Object.defineProperty(Camera.prototype, "globalPosition", {
  22621. get: function () {
  22622. return this._globalPosition;
  22623. },
  22624. enumerable: true,
  22625. configurable: true
  22626. });
  22627. Camera.prototype.getActiveMeshes = function () {
  22628. return this._activeMeshes;
  22629. };
  22630. Camera.prototype.isActiveMesh = function (mesh) {
  22631. return (this._activeMeshes.indexOf(mesh) !== -1);
  22632. };
  22633. /**
  22634. * Is this camera ready to be used/rendered
  22635. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22636. * @return true if the camera is ready
  22637. */
  22638. Camera.prototype.isReady = function (completeCheck) {
  22639. if (completeCheck === void 0) { completeCheck = false; }
  22640. if (completeCheck) {
  22641. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22642. var pp = _a[_i];
  22643. if (pp && !pp.isReady()) {
  22644. return false;
  22645. }
  22646. }
  22647. }
  22648. return _super.prototype.isReady.call(this, completeCheck);
  22649. };
  22650. //Cache
  22651. Camera.prototype._initCache = function () {
  22652. _super.prototype._initCache.call(this);
  22653. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22654. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22655. this._cache.mode = undefined;
  22656. this._cache.minZ = undefined;
  22657. this._cache.maxZ = undefined;
  22658. this._cache.fov = undefined;
  22659. this._cache.fovMode = undefined;
  22660. this._cache.aspectRatio = undefined;
  22661. this._cache.orthoLeft = undefined;
  22662. this._cache.orthoRight = undefined;
  22663. this._cache.orthoBottom = undefined;
  22664. this._cache.orthoTop = undefined;
  22665. this._cache.renderWidth = undefined;
  22666. this._cache.renderHeight = undefined;
  22667. };
  22668. Camera.prototype._updateCache = function (ignoreParentClass) {
  22669. if (!ignoreParentClass) {
  22670. _super.prototype._updateCache.call(this);
  22671. }
  22672. this._cache.position.copyFrom(this.position);
  22673. this._cache.upVector.copyFrom(this.upVector);
  22674. };
  22675. // Synchronized
  22676. Camera.prototype._isSynchronized = function () {
  22677. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22678. };
  22679. Camera.prototype._isSynchronizedViewMatrix = function () {
  22680. if (!_super.prototype._isSynchronized.call(this))
  22681. return false;
  22682. return this._cache.position.equals(this.position)
  22683. && this._cache.upVector.equals(this.upVector)
  22684. && this.isSynchronizedWithParent();
  22685. };
  22686. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22687. var check = this._cache.mode === this.mode
  22688. && this._cache.minZ === this.minZ
  22689. && this._cache.maxZ === this.maxZ;
  22690. if (!check) {
  22691. return false;
  22692. }
  22693. var engine = this.getEngine();
  22694. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22695. check = this._cache.fov === this.fov
  22696. && this._cache.fovMode === this.fovMode
  22697. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22698. }
  22699. else {
  22700. check = this._cache.orthoLeft === this.orthoLeft
  22701. && this._cache.orthoRight === this.orthoRight
  22702. && this._cache.orthoBottom === this.orthoBottom
  22703. && this._cache.orthoTop === this.orthoTop
  22704. && this._cache.renderWidth === engine.getRenderWidth()
  22705. && this._cache.renderHeight === engine.getRenderHeight();
  22706. }
  22707. return check;
  22708. };
  22709. // Controls
  22710. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22711. };
  22712. Camera.prototype.detachControl = function (element) {
  22713. };
  22714. Camera.prototype.update = function () {
  22715. this._checkInputs();
  22716. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22717. this._updateRigCameras();
  22718. }
  22719. };
  22720. Camera.prototype._checkInputs = function () {
  22721. this.onAfterCheckInputsObservable.notifyObservers(this);
  22722. };
  22723. Object.defineProperty(Camera.prototype, "rigCameras", {
  22724. get: function () {
  22725. return this._rigCameras;
  22726. },
  22727. enumerable: true,
  22728. configurable: true
  22729. });
  22730. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22731. get: function () {
  22732. return this._rigPostProcess;
  22733. },
  22734. enumerable: true,
  22735. configurable: true
  22736. });
  22737. /**
  22738. * Internal, gets the first post proces.
  22739. * @returns the first post process to be run on this camera.
  22740. */
  22741. Camera.prototype._getFirstPostProcess = function () {
  22742. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22743. if (this._postProcesses[ppIndex] !== null) {
  22744. return this._postProcesses[ppIndex];
  22745. }
  22746. }
  22747. return null;
  22748. };
  22749. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22750. // invalidate framebuffer
  22751. var firstPostProcess = this._getFirstPostProcess();
  22752. if (firstPostProcess) {
  22753. firstPostProcess.markTextureDirty();
  22754. }
  22755. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22756. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22757. var cam = this._rigCameras[i];
  22758. var rigPostProcess = cam._rigPostProcess;
  22759. // for VR rig, there does not have to be a post process
  22760. if (rigPostProcess) {
  22761. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22762. if (isPass) {
  22763. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22764. cam.isIntermediate = this._postProcesses.length === 0;
  22765. }
  22766. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22767. rigPostProcess.markTextureDirty();
  22768. }
  22769. else {
  22770. cam._postProcesses = this._postProcesses.slice(0);
  22771. }
  22772. }
  22773. };
  22774. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22775. if (insertAt === void 0) { insertAt = null; }
  22776. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22777. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22778. return 0;
  22779. }
  22780. if (insertAt == null || insertAt < 0) {
  22781. this._postProcesses.push(postProcess);
  22782. }
  22783. else if (this._postProcesses[insertAt] === null) {
  22784. this._postProcesses[insertAt] = postProcess;
  22785. }
  22786. else {
  22787. this._postProcesses.splice(insertAt, 0, postProcess);
  22788. }
  22789. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22790. return this._postProcesses.indexOf(postProcess);
  22791. };
  22792. Camera.prototype.detachPostProcess = function (postProcess) {
  22793. var idx = this._postProcesses.indexOf(postProcess);
  22794. if (idx !== -1) {
  22795. this._postProcesses[idx] = null;
  22796. }
  22797. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22798. };
  22799. Camera.prototype.getWorldMatrix = function () {
  22800. if (this._isSynchronizedViewMatrix()) {
  22801. return this._worldMatrix;
  22802. }
  22803. // Getting the the view matrix will also compute the world matrix.
  22804. this.getViewMatrix();
  22805. return this._worldMatrix;
  22806. };
  22807. Camera.prototype._getViewMatrix = function () {
  22808. return BABYLON.Matrix.Identity();
  22809. };
  22810. Camera.prototype.getViewMatrix = function (force) {
  22811. if (!force && this._isSynchronizedViewMatrix()) {
  22812. return this._computedViewMatrix;
  22813. }
  22814. this.updateCache();
  22815. this._computedViewMatrix = this._getViewMatrix();
  22816. this._currentRenderId = this.getScene().getRenderId();
  22817. this._childRenderId = this._currentRenderId;
  22818. this._refreshFrustumPlanes = true;
  22819. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22820. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22821. }
  22822. this.onViewMatrixChangedObservable.notifyObservers(this);
  22823. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22824. return this._computedViewMatrix;
  22825. };
  22826. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22827. this._doNotComputeProjectionMatrix = true;
  22828. if (projection !== undefined) {
  22829. this._projectionMatrix = projection;
  22830. }
  22831. };
  22832. ;
  22833. Camera.prototype.unfreezeProjectionMatrix = function () {
  22834. this._doNotComputeProjectionMatrix = false;
  22835. };
  22836. ;
  22837. Camera.prototype.getProjectionMatrix = function (force) {
  22838. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22839. return this._projectionMatrix;
  22840. }
  22841. // Cache
  22842. this._cache.mode = this.mode;
  22843. this._cache.minZ = this.minZ;
  22844. this._cache.maxZ = this.maxZ;
  22845. // Matrix
  22846. this._refreshFrustumPlanes = true;
  22847. var engine = this.getEngine();
  22848. var scene = this.getScene();
  22849. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22850. this._cache.fov = this.fov;
  22851. this._cache.fovMode = this.fovMode;
  22852. this._cache.aspectRatio = engine.getAspectRatio(this);
  22853. if (this.minZ <= 0) {
  22854. this.minZ = 0.1;
  22855. }
  22856. if (scene.useRightHandedSystem) {
  22857. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22858. }
  22859. else {
  22860. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22861. }
  22862. }
  22863. else {
  22864. var halfWidth = engine.getRenderWidth() / 2.0;
  22865. var halfHeight = engine.getRenderHeight() / 2.0;
  22866. if (scene.useRightHandedSystem) {
  22867. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22868. }
  22869. else {
  22870. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22871. }
  22872. this._cache.orthoLeft = this.orthoLeft;
  22873. this._cache.orthoRight = this.orthoRight;
  22874. this._cache.orthoBottom = this.orthoBottom;
  22875. this._cache.orthoTop = this.orthoTop;
  22876. this._cache.renderWidth = engine.getRenderWidth();
  22877. this._cache.renderHeight = engine.getRenderHeight();
  22878. }
  22879. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22880. return this._projectionMatrix;
  22881. };
  22882. Camera.prototype.getTranformationMatrix = function () {
  22883. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22884. return this._transformMatrix;
  22885. };
  22886. Camera.prototype.updateFrustumPlanes = function () {
  22887. if (!this._refreshFrustumPlanes) {
  22888. return;
  22889. }
  22890. this.getTranformationMatrix();
  22891. if (!this._frustumPlanes) {
  22892. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22893. }
  22894. else {
  22895. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22896. }
  22897. this._refreshFrustumPlanes = false;
  22898. };
  22899. Camera.prototype.isInFrustum = function (target) {
  22900. this.updateFrustumPlanes();
  22901. return target.isInFrustum(this._frustumPlanes);
  22902. };
  22903. Camera.prototype.isCompletelyInFrustum = function (target) {
  22904. this.updateFrustumPlanes();
  22905. return target.isCompletelyInFrustum(this._frustumPlanes);
  22906. };
  22907. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22908. if (length === void 0) { length = 100; }
  22909. if (!transform) {
  22910. transform = this.getWorldMatrix();
  22911. }
  22912. if (!origin) {
  22913. origin = this.position;
  22914. }
  22915. var forward = new BABYLON.Vector3(0, 0, 1);
  22916. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22917. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22918. return new BABYLON.Ray(origin, direction, length);
  22919. };
  22920. /**
  22921. * Releases resources associated with this node.
  22922. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22923. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22924. */
  22925. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22926. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22927. // Observables
  22928. this.onViewMatrixChangedObservable.clear();
  22929. this.onProjectionMatrixChangedObservable.clear();
  22930. this.onAfterCheckInputsObservable.clear();
  22931. this.onRestoreStateObservable.clear();
  22932. // Inputs
  22933. if (this.inputs) {
  22934. this.inputs.clear();
  22935. }
  22936. // Animations
  22937. this.getScene().stopAnimation(this);
  22938. // Remove from scene
  22939. this.getScene().removeCamera(this);
  22940. while (this._rigCameras.length > 0) {
  22941. var camera = this._rigCameras.pop();
  22942. if (camera) {
  22943. camera.dispose();
  22944. }
  22945. }
  22946. // Postprocesses
  22947. if (this._rigPostProcess) {
  22948. this._rigPostProcess.dispose(this);
  22949. this._rigPostProcess = null;
  22950. this._postProcesses = [];
  22951. }
  22952. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22953. this._rigPostProcess = null;
  22954. this._postProcesses = [];
  22955. }
  22956. else {
  22957. var i = this._postProcesses.length;
  22958. while (--i >= 0) {
  22959. var postProcess = this._postProcesses[i];
  22960. if (postProcess) {
  22961. postProcess.dispose(this);
  22962. }
  22963. }
  22964. }
  22965. // Render targets
  22966. var i = this.customRenderTargets.length;
  22967. while (--i >= 0) {
  22968. this.customRenderTargets[i].dispose();
  22969. }
  22970. this.customRenderTargets = [];
  22971. // Active Meshes
  22972. this._activeMeshes.dispose();
  22973. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22974. };
  22975. Object.defineProperty(Camera.prototype, "leftCamera", {
  22976. // ---- Camera rigs section ----
  22977. get: function () {
  22978. if (this._rigCameras.length < 1) {
  22979. return null;
  22980. }
  22981. return this._rigCameras[0];
  22982. },
  22983. enumerable: true,
  22984. configurable: true
  22985. });
  22986. Object.defineProperty(Camera.prototype, "rightCamera", {
  22987. get: function () {
  22988. if (this._rigCameras.length < 2) {
  22989. return null;
  22990. }
  22991. return this._rigCameras[1];
  22992. },
  22993. enumerable: true,
  22994. configurable: true
  22995. });
  22996. Camera.prototype.getLeftTarget = function () {
  22997. if (this._rigCameras.length < 1) {
  22998. return null;
  22999. }
  23000. return this._rigCameras[0].getTarget();
  23001. };
  23002. Camera.prototype.getRightTarget = function () {
  23003. if (this._rigCameras.length < 2) {
  23004. return null;
  23005. }
  23006. return this._rigCameras[1].getTarget();
  23007. };
  23008. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23009. if (this.cameraRigMode === mode) {
  23010. return;
  23011. }
  23012. while (this._rigCameras.length > 0) {
  23013. var camera = this._rigCameras.pop();
  23014. if (camera) {
  23015. camera.dispose();
  23016. }
  23017. }
  23018. this.cameraRigMode = mode;
  23019. this._cameraRigParams = {};
  23020. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23021. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23022. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23023. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23024. // create the rig cameras, unless none
  23025. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23026. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23027. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23028. if (leftCamera && rightCamera) {
  23029. this._rigCameras.push(leftCamera);
  23030. this._rigCameras.push(rightCamera);
  23031. }
  23032. }
  23033. switch (this.cameraRigMode) {
  23034. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23035. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23036. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23037. break;
  23038. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23039. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23040. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23041. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23042. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23043. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23044. break;
  23045. case Camera.RIG_MODE_VR:
  23046. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23047. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23048. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23049. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23050. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23051. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23052. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23053. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23054. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23055. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23056. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23057. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23058. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23059. if (metrics.compensateDistortion) {
  23060. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23061. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23062. }
  23063. break;
  23064. case Camera.RIG_MODE_WEBVR:
  23065. if (rigParams.vrDisplay) {
  23066. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23067. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23068. //Left eye
  23069. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23070. this._rigCameras[0].setCameraRigParameter("left", true);
  23071. //leaving this for future reference
  23072. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23073. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23074. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23075. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23076. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23077. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23078. this._rigCameras[0].parent = this;
  23079. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23080. //Right eye
  23081. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23082. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23083. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23084. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23085. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23086. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23087. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23088. this._rigCameras[1].parent = this;
  23089. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23090. if (Camera.UseAlternateWebVRRendering) {
  23091. this._rigCameras[1]._skipRendering = true;
  23092. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23093. }
  23094. }
  23095. break;
  23096. }
  23097. this._cascadePostProcessesToRigCams();
  23098. this.update();
  23099. };
  23100. Camera.prototype._getVRProjectionMatrix = function () {
  23101. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23102. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23103. return this._projectionMatrix;
  23104. };
  23105. Camera.prototype._updateCameraRotationMatrix = function () {
  23106. //Here for WebVR
  23107. };
  23108. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23109. //Here for WebVR
  23110. };
  23111. /**
  23112. * This function MUST be overwritten by the different WebVR cameras available.
  23113. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23114. */
  23115. Camera.prototype._getWebVRProjectionMatrix = function () {
  23116. return BABYLON.Matrix.Identity();
  23117. };
  23118. /**
  23119. * This function MUST be overwritten by the different WebVR cameras available.
  23120. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23121. */
  23122. Camera.prototype._getWebVRViewMatrix = function () {
  23123. return BABYLON.Matrix.Identity();
  23124. };
  23125. Camera.prototype.setCameraRigParameter = function (name, value) {
  23126. if (!this._cameraRigParams) {
  23127. this._cameraRigParams = {};
  23128. }
  23129. this._cameraRigParams[name] = value;
  23130. //provisionnally:
  23131. if (name === "interaxialDistance") {
  23132. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23133. }
  23134. };
  23135. /**
  23136. * needs to be overridden by children so sub has required properties to be copied
  23137. */
  23138. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23139. return null;
  23140. };
  23141. /**
  23142. * May need to be overridden by children
  23143. */
  23144. Camera.prototype._updateRigCameras = function () {
  23145. for (var i = 0; i < this._rigCameras.length; i++) {
  23146. this._rigCameras[i].minZ = this.minZ;
  23147. this._rigCameras[i].maxZ = this.maxZ;
  23148. this._rigCameras[i].fov = this.fov;
  23149. }
  23150. // only update viewport when ANAGLYPH
  23151. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23152. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23153. }
  23154. };
  23155. Camera.prototype._setupInputs = function () {
  23156. };
  23157. Camera.prototype.serialize = function () {
  23158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23159. // Type
  23160. serializationObject.type = this.getClassName();
  23161. // Parent
  23162. if (this.parent) {
  23163. serializationObject.parentId = this.parent.id;
  23164. }
  23165. if (this.inputs) {
  23166. this.inputs.serialize(serializationObject);
  23167. }
  23168. // Animations
  23169. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23170. serializationObject.ranges = this.serializeAnimationRanges();
  23171. return serializationObject;
  23172. };
  23173. Camera.prototype.clone = function (name) {
  23174. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23175. };
  23176. Camera.prototype.getDirection = function (localAxis) {
  23177. var result = BABYLON.Vector3.Zero();
  23178. this.getDirectionToRef(localAxis, result);
  23179. return result;
  23180. };
  23181. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23182. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23183. };
  23184. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23185. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23186. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23187. switch (type) {
  23188. case "ArcRotateCamera":
  23189. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23190. case "DeviceOrientationCamera":
  23191. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23192. case "FollowCamera":
  23193. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23194. case "ArcFollowCamera":
  23195. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23196. case "GamepadCamera":
  23197. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23198. case "TouchCamera":
  23199. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23200. case "VirtualJoysticksCamera":
  23201. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23202. case "WebVRFreeCamera":
  23203. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23204. case "WebVRGamepadCamera":
  23205. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23206. case "VRDeviceOrientationFreeCamera":
  23207. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23208. case "VRDeviceOrientationGamepadCamera":
  23209. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23210. case "AnaglyphArcRotateCamera":
  23211. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23212. case "AnaglyphFreeCamera":
  23213. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23214. case "AnaglyphGamepadCamera":
  23215. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23216. case "AnaglyphUniversalCamera":
  23217. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23218. case "StereoscopicArcRotateCamera":
  23219. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23220. case "StereoscopicFreeCamera":
  23221. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23222. case "StereoscopicGamepadCamera":
  23223. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23224. case "StereoscopicUniversalCamera":
  23225. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23226. case "FreeCamera": // Forcing Universal here
  23227. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23228. default: // Universal Camera is the default value
  23229. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23230. }
  23231. };
  23232. Camera.prototype.computeWorldMatrix = function () {
  23233. return this.getWorldMatrix();
  23234. };
  23235. Camera.Parse = function (parsedCamera, scene) {
  23236. var type = parsedCamera.type;
  23237. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23238. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23239. // Parent
  23240. if (parsedCamera.parentId) {
  23241. camera._waitingParentId = parsedCamera.parentId;
  23242. }
  23243. //If camera has an input manager, let it parse inputs settings
  23244. if (camera.inputs) {
  23245. camera.inputs.parse(parsedCamera);
  23246. camera._setupInputs();
  23247. }
  23248. if (camera.setPosition) { // need to force position
  23249. camera.position.copyFromFloats(0, 0, 0);
  23250. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23251. }
  23252. // Target
  23253. if (parsedCamera.target) {
  23254. if (camera.setTarget) {
  23255. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23256. }
  23257. }
  23258. // Apply 3d rig, when found
  23259. if (parsedCamera.cameraRigMode) {
  23260. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23261. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23262. }
  23263. // Animations
  23264. if (parsedCamera.animations) {
  23265. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23266. var parsedAnimation = parsedCamera.animations[animationIndex];
  23267. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23268. }
  23269. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23270. }
  23271. if (parsedCamera.autoAnimate) {
  23272. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23273. }
  23274. return camera;
  23275. };
  23276. // Statics
  23277. Camera._PERSPECTIVE_CAMERA = 0;
  23278. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23279. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23280. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23281. Camera._RIG_MODE_NONE = 0;
  23282. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23283. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23284. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23285. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23286. Camera._RIG_MODE_VR = 20;
  23287. Camera._RIG_MODE_WEBVR = 21;
  23288. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23289. Camera.UseAlternateWebVRRendering = false;
  23290. __decorate([
  23291. BABYLON.serializeAsVector3()
  23292. ], Camera.prototype, "position", void 0);
  23293. __decorate([
  23294. BABYLON.serializeAsVector3()
  23295. ], Camera.prototype, "upVector", void 0);
  23296. __decorate([
  23297. BABYLON.serialize()
  23298. ], Camera.prototype, "orthoLeft", void 0);
  23299. __decorate([
  23300. BABYLON.serialize()
  23301. ], Camera.prototype, "orthoRight", void 0);
  23302. __decorate([
  23303. BABYLON.serialize()
  23304. ], Camera.prototype, "orthoBottom", void 0);
  23305. __decorate([
  23306. BABYLON.serialize()
  23307. ], Camera.prototype, "orthoTop", void 0);
  23308. __decorate([
  23309. BABYLON.serialize()
  23310. ], Camera.prototype, "fov", void 0);
  23311. __decorate([
  23312. BABYLON.serialize()
  23313. ], Camera.prototype, "minZ", void 0);
  23314. __decorate([
  23315. BABYLON.serialize()
  23316. ], Camera.prototype, "maxZ", void 0);
  23317. __decorate([
  23318. BABYLON.serialize()
  23319. ], Camera.prototype, "inertia", void 0);
  23320. __decorate([
  23321. BABYLON.serialize()
  23322. ], Camera.prototype, "mode", void 0);
  23323. __decorate([
  23324. BABYLON.serialize()
  23325. ], Camera.prototype, "layerMask", void 0);
  23326. __decorate([
  23327. BABYLON.serialize()
  23328. ], Camera.prototype, "fovMode", void 0);
  23329. __decorate([
  23330. BABYLON.serialize()
  23331. ], Camera.prototype, "cameraRigMode", void 0);
  23332. __decorate([
  23333. BABYLON.serialize()
  23334. ], Camera.prototype, "interaxialDistance", void 0);
  23335. __decorate([
  23336. BABYLON.serialize()
  23337. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23338. return Camera;
  23339. }(BABYLON.Node));
  23340. BABYLON.Camera = Camera;
  23341. })(BABYLON || (BABYLON = {}));
  23342. //# sourceMappingURL=babylon.camera.js.map
  23343. var BABYLON;
  23344. (function (BABYLON) {
  23345. var RenderingManager = /** @class */ (function () {
  23346. function RenderingManager(scene) {
  23347. this._renderingGroups = new Array();
  23348. this._autoClearDepthStencil = {};
  23349. this._customOpaqueSortCompareFn = {};
  23350. this._customAlphaTestSortCompareFn = {};
  23351. this._customTransparentSortCompareFn = {};
  23352. this._renderinGroupInfo = null;
  23353. this._scene = scene;
  23354. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23355. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23356. }
  23357. }
  23358. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23359. if (depth === void 0) { depth = true; }
  23360. if (stencil === void 0) { stencil = true; }
  23361. if (this._depthStencilBufferAlreadyCleaned) {
  23362. return;
  23363. }
  23364. this._scene.getEngine().clear(null, false, depth, stencil);
  23365. this._depthStencilBufferAlreadyCleaned = true;
  23366. };
  23367. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23368. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23369. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23370. var info = null;
  23371. if (observable) {
  23372. if (!this._renderinGroupInfo) {
  23373. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23374. }
  23375. info = this._renderinGroupInfo;
  23376. info.scene = this._scene;
  23377. info.camera = this._scene.activeCamera;
  23378. }
  23379. // Dispatch sprites
  23380. if (renderSprites) {
  23381. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23382. var manager = this._scene.spriteManagers[index];
  23383. this.dispatchSprites(manager);
  23384. }
  23385. }
  23386. // Render
  23387. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23388. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23389. var renderingGroup = this._renderingGroups[index];
  23390. if (!renderingGroup && !observable)
  23391. continue;
  23392. var renderingGroupMask = 0;
  23393. // Fire PRECLEAR stage
  23394. if (observable && info) {
  23395. renderingGroupMask = Math.pow(2, index);
  23396. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23397. info.renderingGroupId = index;
  23398. observable.notifyObservers(info, renderingGroupMask);
  23399. }
  23400. // Clear depth/stencil if needed
  23401. if (RenderingManager.AUTOCLEAR) {
  23402. var autoClear = this._autoClearDepthStencil[index];
  23403. if (autoClear && autoClear.autoClear) {
  23404. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23405. }
  23406. }
  23407. if (observable && info) {
  23408. // Fire PREOPAQUE stage
  23409. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23410. observable.notifyObservers(info, renderingGroupMask);
  23411. // Fire PRETRANSPARENT stage
  23412. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23413. observable.notifyObservers(info, renderingGroupMask);
  23414. }
  23415. if (renderingGroup)
  23416. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23417. // Fire POSTTRANSPARENT stage
  23418. if (observable && info) {
  23419. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23420. observable.notifyObservers(info, renderingGroupMask);
  23421. }
  23422. }
  23423. };
  23424. RenderingManager.prototype.reset = function () {
  23425. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23426. var renderingGroup = this._renderingGroups[index];
  23427. if (renderingGroup) {
  23428. renderingGroup.prepare();
  23429. }
  23430. }
  23431. };
  23432. RenderingManager.prototype.dispose = function () {
  23433. this.freeRenderingGroups();
  23434. this._renderingGroups.length = 0;
  23435. };
  23436. /**
  23437. * Clear the info related to rendering groups preventing retention points during dispose.
  23438. */
  23439. RenderingManager.prototype.freeRenderingGroups = function () {
  23440. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23441. var renderingGroup = this._renderingGroups[index];
  23442. if (renderingGroup) {
  23443. renderingGroup.dispose();
  23444. }
  23445. }
  23446. };
  23447. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23448. if (this._renderingGroups[renderingGroupId] === undefined) {
  23449. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23450. }
  23451. };
  23452. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23453. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23454. this._prepareRenderingGroup(renderingGroupId);
  23455. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23456. };
  23457. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23458. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23459. this._prepareRenderingGroup(renderingGroupId);
  23460. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23461. };
  23462. /**
  23463. * @param subMesh The submesh to dispatch
  23464. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23465. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23466. */
  23467. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23468. if (mesh === undefined) {
  23469. mesh = subMesh.getMesh();
  23470. }
  23471. var renderingGroupId = mesh.renderingGroupId || 0;
  23472. this._prepareRenderingGroup(renderingGroupId);
  23473. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23474. };
  23475. /**
  23476. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23477. * This allowed control for front to back rendering or reversly depending of the special needs.
  23478. *
  23479. * @param renderingGroupId The rendering group id corresponding to its index
  23480. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23481. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23482. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23483. */
  23484. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23485. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23486. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23487. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23488. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23489. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23490. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23491. if (this._renderingGroups[renderingGroupId]) {
  23492. var group = this._renderingGroups[renderingGroupId];
  23493. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23494. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23495. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23496. }
  23497. };
  23498. /**
  23499. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23500. *
  23501. * @param renderingGroupId The rendering group id corresponding to its index
  23502. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23503. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23504. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23505. */
  23506. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23507. if (depth === void 0) { depth = true; }
  23508. if (stencil === void 0) { stencil = true; }
  23509. this._autoClearDepthStencil[renderingGroupId] = {
  23510. autoClear: autoClearDepthStencil,
  23511. depth: depth,
  23512. stencil: stencil
  23513. };
  23514. };
  23515. /**
  23516. * The max id used for rendering groups (not included)
  23517. */
  23518. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23519. /**
  23520. * The min id used for rendering groups (included)
  23521. */
  23522. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23523. /**
  23524. * Used to globally prevent autoclearing scenes.
  23525. */
  23526. RenderingManager.AUTOCLEAR = true;
  23527. return RenderingManager;
  23528. }());
  23529. BABYLON.RenderingManager = RenderingManager;
  23530. })(BABYLON || (BABYLON = {}));
  23531. //# sourceMappingURL=babylon.renderingManager.js.map
  23532. var BABYLON;
  23533. (function (BABYLON) {
  23534. var RenderingGroup = /** @class */ (function () {
  23535. /**
  23536. * Creates a new rendering group.
  23537. * @param index The rendering group index
  23538. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23539. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23540. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23541. */
  23542. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23543. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23544. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23545. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23546. this.index = index;
  23547. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23548. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23549. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23550. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23551. this._particleSystems = new BABYLON.SmartArray(256);
  23552. this._spriteManagers = new BABYLON.SmartArray(256);
  23553. this._edgesRenderers = new BABYLON.SmartArray(16);
  23554. this._scene = scene;
  23555. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23556. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23557. this.transparentSortCompareFn = transparentSortCompareFn;
  23558. }
  23559. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23560. /**
  23561. * Set the opaque sort comparison function.
  23562. * If null the sub meshes will be render in the order they were created
  23563. */
  23564. set: function (value) {
  23565. this._opaqueSortCompareFn = value;
  23566. if (value) {
  23567. this._renderOpaque = this.renderOpaqueSorted;
  23568. }
  23569. else {
  23570. this._renderOpaque = RenderingGroup.renderUnsorted;
  23571. }
  23572. },
  23573. enumerable: true,
  23574. configurable: true
  23575. });
  23576. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23577. /**
  23578. * Set the alpha test sort comparison function.
  23579. * If null the sub meshes will be render in the order they were created
  23580. */
  23581. set: function (value) {
  23582. this._alphaTestSortCompareFn = value;
  23583. if (value) {
  23584. this._renderAlphaTest = this.renderAlphaTestSorted;
  23585. }
  23586. else {
  23587. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23588. }
  23589. },
  23590. enumerable: true,
  23591. configurable: true
  23592. });
  23593. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23594. /**
  23595. * Set the transparent sort comparison function.
  23596. * If null the sub meshes will be render in the order they were created
  23597. */
  23598. set: function (value) {
  23599. if (value) {
  23600. this._transparentSortCompareFn = value;
  23601. }
  23602. else {
  23603. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23604. }
  23605. this._renderTransparent = this.renderTransparentSorted;
  23606. },
  23607. enumerable: true,
  23608. configurable: true
  23609. });
  23610. /**
  23611. * Render all the sub meshes contained in the group.
  23612. * @param customRenderFunction Used to override the default render behaviour of the group.
  23613. * @returns true if rendered some submeshes.
  23614. */
  23615. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23616. if (customRenderFunction) {
  23617. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23618. return;
  23619. }
  23620. var engine = this._scene.getEngine();
  23621. // Depth only
  23622. if (this._depthOnlySubMeshes.length !== 0) {
  23623. engine.setColorWrite(false);
  23624. this._renderAlphaTest(this._depthOnlySubMeshes);
  23625. engine.setColorWrite(true);
  23626. }
  23627. // Opaque
  23628. if (this._opaqueSubMeshes.length !== 0) {
  23629. this._renderOpaque(this._opaqueSubMeshes);
  23630. }
  23631. // Alpha test
  23632. if (this._alphaTestSubMeshes.length !== 0) {
  23633. this._renderAlphaTest(this._alphaTestSubMeshes);
  23634. }
  23635. var stencilState = engine.getStencilBuffer();
  23636. engine.setStencilBuffer(false);
  23637. // Sprites
  23638. if (renderSprites) {
  23639. this._renderSprites();
  23640. }
  23641. // Particles
  23642. if (renderParticles) {
  23643. this._renderParticles(activeMeshes);
  23644. }
  23645. if (this.onBeforeTransparentRendering) {
  23646. this.onBeforeTransparentRendering();
  23647. }
  23648. // Transparent
  23649. if (this._transparentSubMeshes.length !== 0) {
  23650. this._renderTransparent(this._transparentSubMeshes);
  23651. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23652. }
  23653. // Set back stencil to false in case it changes before the edge renderer.
  23654. engine.setStencilBuffer(false);
  23655. // Edges
  23656. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23657. this._edgesRenderers.data[edgesRendererIndex].render();
  23658. }
  23659. // Restore Stencil state.
  23660. engine.setStencilBuffer(stencilState);
  23661. };
  23662. /**
  23663. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23664. * @param subMeshes The submeshes to render
  23665. */
  23666. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23667. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23668. };
  23669. /**
  23670. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23671. * @param subMeshes The submeshes to render
  23672. */
  23673. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23674. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23675. };
  23676. /**
  23677. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23678. * @param subMeshes The submeshes to render
  23679. */
  23680. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23681. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23682. };
  23683. /**
  23684. * Renders the submeshes in a specified order.
  23685. * @param subMeshes The submeshes to sort before render
  23686. * @param sortCompareFn The comparison function use to sort
  23687. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23688. * @param transparent Specifies to activate blending if true
  23689. */
  23690. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23691. var subIndex = 0;
  23692. var subMesh;
  23693. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23694. for (; subIndex < subMeshes.length; subIndex++) {
  23695. subMesh = subMeshes.data[subIndex];
  23696. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23697. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23698. }
  23699. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23700. if (sortCompareFn) {
  23701. sortedArray.sort(sortCompareFn);
  23702. }
  23703. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23704. subMesh = sortedArray[subIndex];
  23705. if (transparent) {
  23706. var material = subMesh.getMaterial();
  23707. if (material && material.needDepthPrePass) {
  23708. var engine = material.getScene().getEngine();
  23709. engine.setColorWrite(false);
  23710. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23711. subMesh.render(false);
  23712. engine.setColorWrite(true);
  23713. }
  23714. }
  23715. subMesh.render(transparent);
  23716. }
  23717. };
  23718. /**
  23719. * Renders the submeshes in the order they were dispatched (no sort applied).
  23720. * @param subMeshes The submeshes to render
  23721. */
  23722. RenderingGroup.renderUnsorted = function (subMeshes) {
  23723. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23724. var submesh = subMeshes.data[subIndex];
  23725. submesh.render(false);
  23726. }
  23727. };
  23728. /**
  23729. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23730. * are rendered back to front if in the same alpha index.
  23731. *
  23732. * @param a The first submesh
  23733. * @param b The second submesh
  23734. * @returns The result of the comparison
  23735. */
  23736. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23737. // Alpha index first
  23738. if (a._alphaIndex > b._alphaIndex) {
  23739. return 1;
  23740. }
  23741. if (a._alphaIndex < b._alphaIndex) {
  23742. return -1;
  23743. }
  23744. // Then distance to camera
  23745. return RenderingGroup.backToFrontSortCompare(a, b);
  23746. };
  23747. /**
  23748. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23749. * are rendered back to front.
  23750. *
  23751. * @param a The first submesh
  23752. * @param b The second submesh
  23753. * @returns The result of the comparison
  23754. */
  23755. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23756. // Then distance to camera
  23757. if (a._distanceToCamera < b._distanceToCamera) {
  23758. return 1;
  23759. }
  23760. if (a._distanceToCamera > b._distanceToCamera) {
  23761. return -1;
  23762. }
  23763. return 0;
  23764. };
  23765. /**
  23766. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23767. * are rendered front to back (prevent overdraw).
  23768. *
  23769. * @param a The first submesh
  23770. * @param b The second submesh
  23771. * @returns The result of the comparison
  23772. */
  23773. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23774. // Then distance to camera
  23775. if (a._distanceToCamera < b._distanceToCamera) {
  23776. return -1;
  23777. }
  23778. if (a._distanceToCamera > b._distanceToCamera) {
  23779. return 1;
  23780. }
  23781. return 0;
  23782. };
  23783. /**
  23784. * Resets the different lists of submeshes to prepare a new frame.
  23785. */
  23786. RenderingGroup.prototype.prepare = function () {
  23787. this._opaqueSubMeshes.reset();
  23788. this._transparentSubMeshes.reset();
  23789. this._alphaTestSubMeshes.reset();
  23790. this._depthOnlySubMeshes.reset();
  23791. this._particleSystems.reset();
  23792. this._spriteManagers.reset();
  23793. this._edgesRenderers.reset();
  23794. };
  23795. RenderingGroup.prototype.dispose = function () {
  23796. this._opaqueSubMeshes.dispose();
  23797. this._transparentSubMeshes.dispose();
  23798. this._alphaTestSubMeshes.dispose();
  23799. this._depthOnlySubMeshes.dispose();
  23800. this._particleSystems.dispose();
  23801. this._spriteManagers.dispose();
  23802. this._edgesRenderers.dispose();
  23803. };
  23804. /**
  23805. * Inserts the submesh in its correct queue depending on its material.
  23806. * @param subMesh The submesh to dispatch
  23807. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23808. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23809. */
  23810. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23811. // Get mesh and materials if not provided
  23812. if (mesh === undefined) {
  23813. mesh = subMesh.getMesh();
  23814. }
  23815. if (material === undefined) {
  23816. material = subMesh.getMaterial();
  23817. }
  23818. if (material === null || material === undefined) {
  23819. return;
  23820. }
  23821. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23822. this._transparentSubMeshes.push(subMesh);
  23823. }
  23824. else if (material.needAlphaTesting()) { // Alpha test
  23825. if (material.needDepthPrePass) {
  23826. this._depthOnlySubMeshes.push(subMesh);
  23827. }
  23828. this._alphaTestSubMeshes.push(subMesh);
  23829. }
  23830. else {
  23831. if (material.needDepthPrePass) {
  23832. this._depthOnlySubMeshes.push(subMesh);
  23833. }
  23834. this._opaqueSubMeshes.push(subMesh); // Opaque
  23835. }
  23836. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23837. this._edgesRenderers.push(mesh._edgesRenderer);
  23838. }
  23839. };
  23840. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23841. this._spriteManagers.push(spriteManager);
  23842. };
  23843. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23844. this._particleSystems.push(particleSystem);
  23845. };
  23846. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23847. if (this._particleSystems.length === 0) {
  23848. return;
  23849. }
  23850. // Particles
  23851. var activeCamera = this._scene.activeCamera;
  23852. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23853. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23854. var particleSystem = this._particleSystems.data[particleIndex];
  23855. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23856. continue;
  23857. }
  23858. var emitter = particleSystem.emitter;
  23859. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23860. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23861. }
  23862. }
  23863. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23864. };
  23865. RenderingGroup.prototype._renderSprites = function () {
  23866. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23867. return;
  23868. }
  23869. // Sprites
  23870. var activeCamera = this._scene.activeCamera;
  23871. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23872. for (var id = 0; id < this._spriteManagers.length; id++) {
  23873. var spriteManager = this._spriteManagers.data[id];
  23874. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23875. spriteManager.render();
  23876. }
  23877. }
  23878. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23879. };
  23880. return RenderingGroup;
  23881. }());
  23882. BABYLON.RenderingGroup = RenderingGroup;
  23883. })(BABYLON || (BABYLON = {}));
  23884. //# sourceMappingURL=babylon.renderingGroup.js.map
  23885. var BABYLON;
  23886. (function (BABYLON) {
  23887. /** @hidden */
  23888. var ClickInfo = /** @class */ (function () {
  23889. function ClickInfo() {
  23890. this._singleClick = false;
  23891. this._doubleClick = false;
  23892. this._hasSwiped = false;
  23893. this._ignore = false;
  23894. }
  23895. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23896. get: function () {
  23897. return this._singleClick;
  23898. },
  23899. set: function (b) {
  23900. this._singleClick = b;
  23901. },
  23902. enumerable: true,
  23903. configurable: true
  23904. });
  23905. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23906. get: function () {
  23907. return this._doubleClick;
  23908. },
  23909. set: function (b) {
  23910. this._doubleClick = b;
  23911. },
  23912. enumerable: true,
  23913. configurable: true
  23914. });
  23915. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23916. get: function () {
  23917. return this._hasSwiped;
  23918. },
  23919. set: function (b) {
  23920. this._hasSwiped = b;
  23921. },
  23922. enumerable: true,
  23923. configurable: true
  23924. });
  23925. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23926. get: function () {
  23927. return this._ignore;
  23928. },
  23929. set: function (b) {
  23930. this._ignore = b;
  23931. },
  23932. enumerable: true,
  23933. configurable: true
  23934. });
  23935. return ClickInfo;
  23936. }());
  23937. /**
  23938. * This class is used by the onRenderingGroupObservable
  23939. */
  23940. var RenderingGroupInfo = /** @class */ (function () {
  23941. function RenderingGroupInfo() {
  23942. }
  23943. /**
  23944. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23945. * This stage will be fired no matter what
  23946. */
  23947. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23948. /**
  23949. * Called before opaque object are rendered.
  23950. * This stage will be fired only if there's 3D Opaque content to render
  23951. */
  23952. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23953. /**
  23954. * Called after the opaque objects are rendered and before the transparent ones
  23955. * This stage will be fired only if there's 3D transparent content to render
  23956. */
  23957. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23958. /**
  23959. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23960. * This stage will be fired no matter what
  23961. */
  23962. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23963. return RenderingGroupInfo;
  23964. }());
  23965. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23966. /**
  23967. * Represents a scene to be rendered by the engine.
  23968. * @see http://doc.babylonjs.com/features/scene
  23969. */
  23970. var Scene = /** @class */ (function () {
  23971. /**
  23972. * Creates a new Scene
  23973. * @param engine defines the engine to use to render this scene
  23974. */
  23975. function Scene(engine) {
  23976. // Members
  23977. /**
  23978. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23979. */
  23980. this.autoClear = true;
  23981. /**
  23982. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23983. */
  23984. this.autoClearDepthAndStencil = true;
  23985. /**
  23986. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23987. */
  23988. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23989. /**
  23990. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23991. */
  23992. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23993. this._forceWireframe = false;
  23994. this._forcePointsCloud = false;
  23995. /**
  23996. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23997. */
  23998. this.forceShowBoundingBoxes = false;
  23999. /**
  24000. * Gets or sets a boolean indicating if animations are enabled
  24001. */
  24002. this.animationsEnabled = true;
  24003. this._animationPropertiesOverride = null;
  24004. /**
  24005. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24006. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24007. */
  24008. this.useConstantAnimationDeltaTime = false;
  24009. /**
  24010. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24011. * Please note that it requires to run a ray cast through the scene on every frame
  24012. */
  24013. this.constantlyUpdateMeshUnderPointer = false;
  24014. /**
  24015. * Defines the HTML cursor to use when hovering over interactive elements
  24016. */
  24017. this.hoverCursor = "pointer";
  24018. /**
  24019. * Defines the HTML default cursor to use (empty by default)
  24020. */
  24021. this.defaultCursor = "";
  24022. /**
  24023. * This is used to call preventDefault() on pointer down
  24024. * in order to block unwanted artifacts like system double clicks
  24025. */
  24026. this.preventDefaultOnPointerDown = true;
  24027. // Metadata
  24028. /**
  24029. * Gets or sets user defined metadata
  24030. */
  24031. this.metadata = null;
  24032. /**
  24033. * Use this array to add regular expressions used to disable offline support for specific urls
  24034. */
  24035. this.disableOfflineSupportExceptionRules = new Array();
  24036. /**
  24037. * An event triggered when the scene is disposed.
  24038. */
  24039. this.onDisposeObservable = new BABYLON.Observable();
  24040. this._onDisposeObserver = null;
  24041. /**
  24042. * An event triggered before rendering the scene (right after animations and physics)
  24043. */
  24044. this.onBeforeRenderObservable = new BABYLON.Observable();
  24045. this._onBeforeRenderObserver = null;
  24046. /**
  24047. * An event triggered after rendering the scene
  24048. */
  24049. this.onAfterRenderObservable = new BABYLON.Observable();
  24050. this._onAfterRenderObserver = null;
  24051. /**
  24052. * An event triggered before animating the scene
  24053. */
  24054. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24055. /**
  24056. * An event triggered after animations processing
  24057. */
  24058. this.onAfterAnimationsObservable = new BABYLON.Observable();
  24059. /**
  24060. * An event triggered before draw calls are ready to be sent
  24061. */
  24062. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24063. /**
  24064. * An event triggered after draw calls have been sent
  24065. */
  24066. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24067. /**
  24068. * An event triggered when physic simulation is about to be run
  24069. */
  24070. this.onBeforePhysicsObservable = new BABYLON.Observable();
  24071. /**
  24072. * An event triggered when physic simulation has been done
  24073. */
  24074. this.onAfterPhysicsObservable = new BABYLON.Observable();
  24075. /**
  24076. * An event triggered when the scene is ready
  24077. */
  24078. this.onReadyObservable = new BABYLON.Observable();
  24079. /**
  24080. * An event triggered before rendering a camera
  24081. */
  24082. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24083. this._onBeforeCameraRenderObserver = null;
  24084. /**
  24085. * An event triggered after rendering a camera
  24086. */
  24087. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24088. this._onAfterCameraRenderObserver = null;
  24089. /**
  24090. * An event triggered when active meshes evaluation is about to start
  24091. */
  24092. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24093. /**
  24094. * An event triggered when active meshes evaluation is done
  24095. */
  24096. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24097. /**
  24098. * An event triggered when particles rendering is about to start
  24099. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24100. */
  24101. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24102. /**
  24103. * An event triggered when particles rendering is done
  24104. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24105. */
  24106. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24107. /**
  24108. * An event triggered when sprites rendering is about to start
  24109. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24110. */
  24111. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24112. /**
  24113. * An event triggered when sprites rendering is done
  24114. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24115. */
  24116. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24117. /**
  24118. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24119. */
  24120. this.onDataLoadedObservable = new BABYLON.Observable();
  24121. /**
  24122. * An event triggered when a camera is created
  24123. */
  24124. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24125. /**
  24126. * An event triggered when a camera is removed
  24127. */
  24128. this.onCameraRemovedObservable = new BABYLON.Observable();
  24129. /**
  24130. * An event triggered when a light is created
  24131. */
  24132. this.onNewLightAddedObservable = new BABYLON.Observable();
  24133. /**
  24134. * An event triggered when a light is removed
  24135. */
  24136. this.onLightRemovedObservable = new BABYLON.Observable();
  24137. /**
  24138. * An event triggered when a geometry is created
  24139. */
  24140. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24141. /**
  24142. * An event triggered when a geometry is removed
  24143. */
  24144. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24145. /**
  24146. * An event triggered when a transform node is created
  24147. */
  24148. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24149. /**
  24150. * An event triggered when a transform node is removed
  24151. */
  24152. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24153. /**
  24154. * An event triggered when a mesh is created
  24155. */
  24156. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24157. /**
  24158. * An event triggered when a mesh is removed
  24159. */
  24160. this.onMeshRemovedObservable = new BABYLON.Observable();
  24161. /**
  24162. * An event triggered when render targets are about to be rendered
  24163. * Can happen multiple times per frame.
  24164. */
  24165. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24166. /**
  24167. * An event triggered when render targets were rendered.
  24168. * Can happen multiple times per frame.
  24169. */
  24170. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24171. /**
  24172. * An event triggered before calculating deterministic simulation step
  24173. */
  24174. this.onBeforeStepObservable = new BABYLON.Observable();
  24175. /**
  24176. * An event triggered after calculating deterministic simulation step
  24177. */
  24178. this.onAfterStepObservable = new BABYLON.Observable();
  24179. /**
  24180. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24181. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24182. * 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)
  24183. */
  24184. this.onRenderingGroupObservable = new BABYLON.Observable();
  24185. // Animations
  24186. /**
  24187. * Gets a list of Animations associated with the scene
  24188. */
  24189. this.animations = [];
  24190. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24191. /**
  24192. * 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).
  24193. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24194. */
  24195. this.onPrePointerObservable = new BABYLON.Observable();
  24196. /**
  24197. * Observable event triggered each time an input event is received from the rendering canvas
  24198. */
  24199. this.onPointerObservable = new BABYLON.Observable();
  24200. this._meshPickProceed = false;
  24201. this._currentPickResult = null;
  24202. this._previousPickResult = null;
  24203. this._totalPointersPressed = 0;
  24204. this._doubleClickOccured = false;
  24205. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24206. this.cameraToUseForPointers = null;
  24207. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24208. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24209. this._startingPointerTime = 0;
  24210. this._previousStartingPointerTime = 0;
  24211. this._pointerCaptures = {};
  24212. // Deterministic lockstep
  24213. this._timeAccumulator = 0;
  24214. this._currentStepId = 0;
  24215. this._currentInternalStep = 0;
  24216. // Keyboard
  24217. /**
  24218. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24219. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24220. */
  24221. this.onPreKeyboardObservable = new BABYLON.Observable();
  24222. /**
  24223. * Observable event triggered each time an keyboard event is received from the hosting window
  24224. */
  24225. this.onKeyboardObservable = new BABYLON.Observable();
  24226. // Coordinates system
  24227. this._useRightHandedSystem = false;
  24228. // Fog
  24229. this._fogEnabled = true;
  24230. this._fogMode = Scene.FOGMODE_NONE;
  24231. /**
  24232. * Gets or sets the fog color to use
  24233. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24234. */
  24235. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24236. /**
  24237. * Gets or sets the fog density to use
  24238. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24239. */
  24240. this.fogDensity = 0.1;
  24241. /**
  24242. * Gets or sets the fog start distance to use
  24243. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24244. */
  24245. this.fogStart = 0;
  24246. /**
  24247. * Gets or sets the fog end distance to use
  24248. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24249. */
  24250. this.fogEnd = 1000.0;
  24251. // Lights
  24252. this._shadowsEnabled = true;
  24253. this._lightsEnabled = true;
  24254. /**
  24255. * All of the lights added to this scene
  24256. * @see http://doc.babylonjs.com/babylon101/lights
  24257. */
  24258. this.lights = new Array();
  24259. // Cameras
  24260. /** All of the cameras added to this scene.
  24261. * @see http://doc.babylonjs.com/babylon101/cameras
  24262. */
  24263. this.cameras = new Array();
  24264. /** All of the active cameras added to this scene. */
  24265. this.activeCameras = new Array();
  24266. // Meshes
  24267. /**
  24268. * All of the tranform nodes added to this scene
  24269. * @see http://doc.babylonjs.com/how_to/transformnode
  24270. */
  24271. this.transformNodes = new Array();
  24272. /**
  24273. * All of the (abstract) meshes added to this scene
  24274. */
  24275. this.meshes = new Array();
  24276. /**
  24277. * All of the animation groups added to this scene
  24278. * @see http://doc.babylonjs.com/how_to/group
  24279. */
  24280. this.animationGroups = new Array();
  24281. // Geometries
  24282. this._geometries = new Array();
  24283. /**
  24284. * All of the materials added to this scene
  24285. * @see http://doc.babylonjs.com/babylon101/materials
  24286. */
  24287. this.materials = new Array();
  24288. /**
  24289. * All of the multi-materials added to this scene
  24290. * @see http://doc.babylonjs.com/how_to/multi_materials
  24291. */
  24292. this.multiMaterials = new Array();
  24293. // Textures
  24294. this._texturesEnabled = true;
  24295. /**
  24296. * All of the textures added to this scene
  24297. */
  24298. this.textures = new Array();
  24299. // Particles
  24300. /**
  24301. * Gets or sets a boolean indicating if particles are enabled on this scene
  24302. */
  24303. this.particlesEnabled = true;
  24304. /**
  24305. * All of the particle systems added to this scene
  24306. * @see http://doc.babylonjs.com/babylon101/particles
  24307. */
  24308. this.particleSystems = new Array();
  24309. // Sprites
  24310. /**
  24311. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24312. */
  24313. this.spritesEnabled = true;
  24314. /**
  24315. * All of the sprite managers added to this scene
  24316. * @see http://doc.babylonjs.com/babylon101/sprites
  24317. */
  24318. this.spriteManagers = new Array();
  24319. /**
  24320. * The list of layers (background and foreground) of the scene
  24321. */
  24322. this.layers = new Array();
  24323. /**
  24324. * The list of effect layers (highlights/glow) added to the scene
  24325. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24326. * @see http://doc.babylonjs.com/how_to/glow_layer
  24327. */
  24328. this.effectLayers = new Array();
  24329. // Skeletons
  24330. this._skeletonsEnabled = true;
  24331. /**
  24332. * The list of skeletons added to the scene
  24333. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24334. */
  24335. this.skeletons = new Array();
  24336. // Morph targets
  24337. /**
  24338. * The list of morph target managers added to the scene
  24339. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24340. */
  24341. this.morphTargetManagers = new Array();
  24342. // Lens flares
  24343. /**
  24344. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24345. */
  24346. this.lensFlaresEnabled = true;
  24347. /**
  24348. * The list of lens flare system added to the scene
  24349. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24350. */
  24351. this.lensFlareSystems = new Array();
  24352. // Collisions
  24353. /**
  24354. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24355. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24356. */
  24357. this.collisionsEnabled = true;
  24358. /**
  24359. * Defines the gravity applied to this scene (used only for collisions)
  24360. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24361. */
  24362. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24363. // Postprocesses
  24364. /**
  24365. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24366. */
  24367. this.postProcessesEnabled = true;
  24368. /**
  24369. * The list of postprocesses added to the scene
  24370. */
  24371. this.postProcesses = new Array();
  24372. // Customs render targets
  24373. /**
  24374. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24375. */
  24376. this.renderTargetsEnabled = true;
  24377. /**
  24378. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24379. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24380. */
  24381. this.dumpNextRenderTargets = false;
  24382. /**
  24383. * The list of user defined render targets added to the scene
  24384. */
  24385. this.customRenderTargets = new Array();
  24386. /**
  24387. * Gets the list of meshes imported to the scene through SceneLoader
  24388. */
  24389. this.importedMeshesFiles = new Array();
  24390. // Probes
  24391. /**
  24392. * Gets or sets a boolean indicating if probes are enabled on this scene
  24393. */
  24394. this.probesEnabled = true;
  24395. /**
  24396. * The list of reflection probes added to the scene
  24397. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24398. */
  24399. this.reflectionProbes = new Array();
  24400. /** @hidden */
  24401. this._actionManagers = new Array();
  24402. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24403. // Procedural textures
  24404. /**
  24405. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24406. */
  24407. this.proceduralTexturesEnabled = true;
  24408. /**
  24409. * The list of procedural textures added to the scene
  24410. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24411. */
  24412. this.proceduralTextures = new Array();
  24413. /**
  24414. * The list of sound tracks added to the scene
  24415. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24416. */
  24417. this.soundTracks = new Array();
  24418. this._audioEnabled = true;
  24419. this._headphone = false;
  24420. // Performance counters
  24421. this._totalVertices = new BABYLON.PerfCounter();
  24422. /** @hidden */
  24423. this._activeIndices = new BABYLON.PerfCounter();
  24424. /** @hidden */
  24425. this._activeParticles = new BABYLON.PerfCounter();
  24426. /** @hidden */
  24427. this._activeBones = new BABYLON.PerfCounter();
  24428. this._animationTime = 0;
  24429. /**
  24430. * Gets or sets a general scale for animation speed
  24431. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24432. */
  24433. this.animationTimeScale = 1;
  24434. this._renderId = 0;
  24435. this._executeWhenReadyTimeoutId = -1;
  24436. this._intermediateRendering = false;
  24437. this._viewUpdateFlag = -1;
  24438. this._projectionUpdateFlag = -1;
  24439. this._alternateViewUpdateFlag = -1;
  24440. this._alternateProjectionUpdateFlag = -1;
  24441. /** @hidden */
  24442. this._toBeDisposed = new BABYLON.SmartArray(256);
  24443. this._activeRequests = new Array();
  24444. this._pendingData = new Array();
  24445. this._isDisposed = false;
  24446. /**
  24447. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24448. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24449. */
  24450. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24451. this._activeMeshes = new BABYLON.SmartArray(256);
  24452. this._processedMaterials = new BABYLON.SmartArray(256);
  24453. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24454. /** @hidden */
  24455. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24456. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24457. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24458. /** @hidden */
  24459. this._activeAnimatables = new Array();
  24460. this._transformMatrix = BABYLON.Matrix.Zero();
  24461. this._useAlternateCameraConfiguration = false;
  24462. this._alternateRendering = false;
  24463. /**
  24464. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24465. * This is useful if there are more lights that the maximum simulteanous authorized
  24466. */
  24467. this.requireLightSorting = false;
  24468. this._depthRenderer = {};
  24469. this._activeMeshesFrozen = false;
  24470. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24471. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24472. this._engine.scenes.push(this);
  24473. this._uid = null;
  24474. this._renderingManager = new BABYLON.RenderingManager(this);
  24475. if (BABYLON.PostProcessManager) {
  24476. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24477. }
  24478. if (BABYLON.OutlineRenderer) {
  24479. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24480. }
  24481. if (BABYLON.Tools.IsWindowObjectExist()) {
  24482. this.attachControl();
  24483. }
  24484. //simplification queue
  24485. if (BABYLON.SimplificationQueue) {
  24486. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24487. }
  24488. //collision coordinator initialization. For now legacy per default.
  24489. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24490. // Uniform Buffer
  24491. this._createUbo();
  24492. // Default Image processing definition
  24493. if (BABYLON.ImageProcessingConfiguration) {
  24494. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24495. }
  24496. }
  24497. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24498. /** The fog is deactivated */
  24499. get: function () {
  24500. return Scene._FOGMODE_NONE;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24506. /** The fog density is following an exponential function */
  24507. get: function () {
  24508. return Scene._FOGMODE_EXP;
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24514. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24515. get: function () {
  24516. return Scene._FOGMODE_EXP2;
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24522. /** The fog density is following a linear function. */
  24523. get: function () {
  24524. return Scene._FOGMODE_LINEAR;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24530. /**
  24531. * Texture used in all pbr material as the reflection texture.
  24532. * As in the majority of the scene they are the same (exception for multi room and so on),
  24533. * this is easier to reference from here than from all the materials.
  24534. */
  24535. get: function () {
  24536. return this._environmentTexture;
  24537. },
  24538. /**
  24539. * Texture used in all pbr material as the reflection texture.
  24540. * As in the majority of the scene they are the same (exception for multi room and so on),
  24541. * this is easier to set here than in all the materials.
  24542. */
  24543. set: function (value) {
  24544. if (this._environmentTexture === value) {
  24545. return;
  24546. }
  24547. this._environmentTexture = value;
  24548. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24554. /**
  24555. * Default image processing configuration used either in the rendering
  24556. * Forward main pass or through the imageProcessingPostProcess if present.
  24557. * As in the majority of the scene they are the same (exception for multi camera),
  24558. * this is easier to reference from here than from all the materials and post process.
  24559. *
  24560. * No setter as we it is a shared configuration, you can set the values instead.
  24561. */
  24562. get: function () {
  24563. return this._imageProcessingConfiguration;
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24569. get: function () {
  24570. return this._forceWireframe;
  24571. },
  24572. /**
  24573. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24574. */
  24575. set: function (value) {
  24576. if (this._forceWireframe === value) {
  24577. return;
  24578. }
  24579. this._forceWireframe = value;
  24580. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24581. },
  24582. enumerable: true,
  24583. configurable: true
  24584. });
  24585. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24586. get: function () {
  24587. return this._forcePointsCloud;
  24588. },
  24589. /**
  24590. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24591. */
  24592. set: function (value) {
  24593. if (this._forcePointsCloud === value) {
  24594. return;
  24595. }
  24596. this._forcePointsCloud = value;
  24597. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24603. /**
  24604. * Gets or sets the animation properties override
  24605. */
  24606. get: function () {
  24607. return this._animationPropertiesOverride;
  24608. },
  24609. set: function (value) {
  24610. this._animationPropertiesOverride = value;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "onDispose", {
  24616. /** Sets a function to be executed when this scene is disposed. */
  24617. set: function (callback) {
  24618. if (this._onDisposeObserver) {
  24619. this.onDisposeObservable.remove(this._onDisposeObserver);
  24620. }
  24621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene.prototype, "beforeRender", {
  24627. /** Sets a function to be executed before rendering this scene */
  24628. set: function (callback) {
  24629. if (this._onBeforeRenderObserver) {
  24630. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24631. }
  24632. if (callback) {
  24633. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24634. }
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. Object.defineProperty(Scene.prototype, "afterRender", {
  24640. /** Sets a function to be executed after rendering this scene */
  24641. set: function (callback) {
  24642. if (this._onAfterRenderObserver) {
  24643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24644. }
  24645. if (callback) {
  24646. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24647. }
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24653. /** Sets a function to be executed before rendering a camera*/
  24654. set: function (callback) {
  24655. if (this._onBeforeCameraRenderObserver) {
  24656. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24657. }
  24658. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24664. /** Sets a function to be executed after rendering a camera*/
  24665. set: function (callback) {
  24666. if (this._onAfterCameraRenderObserver) {
  24667. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24668. }
  24669. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24675. /**
  24676. * Gets the gamepad manager associated with the scene
  24677. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24678. */
  24679. get: function () {
  24680. if (!this._gamepadManager) {
  24681. this._gamepadManager = new BABYLON.GamepadManager(this);
  24682. }
  24683. return this._gamepadManager;
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24689. /**
  24690. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24691. */
  24692. get: function () {
  24693. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24694. },
  24695. enumerable: true,
  24696. configurable: true
  24697. });
  24698. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24699. get: function () {
  24700. return this._useRightHandedSystem;
  24701. },
  24702. /**
  24703. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24704. */
  24705. set: function (value) {
  24706. if (this._useRightHandedSystem === value) {
  24707. return;
  24708. }
  24709. this._useRightHandedSystem = value;
  24710. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. /**
  24716. * Sets the step Id used by deterministic lock step
  24717. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24718. * @param newStepId defines the step Id
  24719. */
  24720. Scene.prototype.setStepId = function (newStepId) {
  24721. this._currentStepId = newStepId;
  24722. };
  24723. ;
  24724. /**
  24725. * Gets the step Id used by deterministic lock step
  24726. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24727. * @returns the step Id
  24728. */
  24729. Scene.prototype.getStepId = function () {
  24730. return this._currentStepId;
  24731. };
  24732. ;
  24733. /**
  24734. * Gets the internal step used by deterministic lock step
  24735. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24736. * @returns the internal step
  24737. */
  24738. Scene.prototype.getInternalStep = function () {
  24739. return this._currentInternalStep;
  24740. };
  24741. ;
  24742. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24743. get: function () {
  24744. return this._fogEnabled;
  24745. },
  24746. /**
  24747. * Gets or sets a boolean indicating if fog is enabled on this scene
  24748. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24749. */
  24750. set: function (value) {
  24751. if (this._fogEnabled === value) {
  24752. return;
  24753. }
  24754. this._fogEnabled = value;
  24755. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "fogMode", {
  24761. get: function () {
  24762. return this._fogMode;
  24763. },
  24764. /**
  24765. * Gets or sets the fog mode to use
  24766. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24767. */
  24768. set: function (value) {
  24769. if (this._fogMode === value) {
  24770. return;
  24771. }
  24772. this._fogMode = value;
  24773. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24779. get: function () {
  24780. return this._shadowsEnabled;
  24781. },
  24782. /**
  24783. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24784. */
  24785. set: function (value) {
  24786. if (this._shadowsEnabled === value) {
  24787. return;
  24788. }
  24789. this._shadowsEnabled = value;
  24790. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24791. },
  24792. enumerable: true,
  24793. configurable: true
  24794. });
  24795. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24796. get: function () {
  24797. return this._lightsEnabled;
  24798. },
  24799. /**
  24800. * Gets or sets a boolean indicating if lights are enabled on this scene
  24801. */
  24802. set: function (value) {
  24803. if (this._lightsEnabled === value) {
  24804. return;
  24805. }
  24806. this._lightsEnabled = value;
  24807. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24813. /** The default material used on meshes when no material is affected */
  24814. get: function () {
  24815. if (!this._defaultMaterial) {
  24816. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24817. }
  24818. return this._defaultMaterial;
  24819. },
  24820. /** The default material used on meshes when no material is affected */
  24821. set: function (value) {
  24822. this._defaultMaterial = value;
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24828. get: function () {
  24829. return this._texturesEnabled;
  24830. },
  24831. /**
  24832. * Gets or sets a boolean indicating if textures are enabled on this scene
  24833. */
  24834. set: function (value) {
  24835. if (this._texturesEnabled === value) {
  24836. return;
  24837. }
  24838. this._texturesEnabled = value;
  24839. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24840. },
  24841. enumerable: true,
  24842. configurable: true
  24843. });
  24844. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24845. get: function () {
  24846. return this._skeletonsEnabled;
  24847. },
  24848. /**
  24849. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24850. */
  24851. set: function (value) {
  24852. if (this._skeletonsEnabled === value) {
  24853. return;
  24854. }
  24855. this._skeletonsEnabled = value;
  24856. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24862. /**
  24863. * Gets the postprocess render pipeline manager
  24864. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24865. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24866. */
  24867. get: function () {
  24868. if (!this._postProcessRenderPipelineManager) {
  24869. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24870. }
  24871. return this._postProcessRenderPipelineManager;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24877. /**
  24878. * Gets the main soundtrack associated with the scene
  24879. */
  24880. get: function () {
  24881. if (!this._mainSoundTrack) {
  24882. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24883. }
  24884. return this._mainSoundTrack;
  24885. },
  24886. enumerable: true,
  24887. configurable: true
  24888. });
  24889. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24890. /** @hidden */
  24891. get: function () {
  24892. return this._alternateRendering;
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24898. /**
  24899. * Gets the list of frustum planes (built from the active camera)
  24900. */
  24901. get: function () {
  24902. return this._frustumPlanes;
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24908. /**
  24909. * Gets the current geometry buffer associated to the scene.
  24910. */
  24911. get: function () {
  24912. return this._geometryBufferRenderer;
  24913. },
  24914. /**
  24915. * Sets the current geometry buffer for the scene.
  24916. */
  24917. set: function (geometryBufferRenderer) {
  24918. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24919. this._geometryBufferRenderer = geometryBufferRenderer;
  24920. }
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Object.defineProperty(Scene.prototype, "debugLayer", {
  24926. /**
  24927. * Gets the debug layer (aka Inspector) associated with the scene
  24928. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24929. */
  24930. get: function () {
  24931. if (!this._debugLayer) {
  24932. this._debugLayer = new BABYLON.DebugLayer(this);
  24933. }
  24934. return this._debugLayer;
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24940. /**
  24941. * Gets a boolean indicating if collisions are processed on a web worker
  24942. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24943. */
  24944. get: function () {
  24945. return this._workerCollisions;
  24946. },
  24947. set: function (enabled) {
  24948. if (!BABYLON.CollisionCoordinatorLegacy) {
  24949. return;
  24950. }
  24951. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24952. this._workerCollisions = enabled;
  24953. if (this.collisionCoordinator) {
  24954. this.collisionCoordinator.destroy();
  24955. }
  24956. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24957. this.collisionCoordinator.init(this);
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24963. /**
  24964. * Gets the octree used to boost mesh selection (picking)
  24965. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24966. */
  24967. get: function () {
  24968. return this._selectionOctree;
  24969. },
  24970. enumerable: true,
  24971. configurable: true
  24972. });
  24973. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24974. /**
  24975. * Gets the mesh that is currently under the pointer
  24976. */
  24977. get: function () {
  24978. return this._pointerOverMesh;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. Object.defineProperty(Scene.prototype, "pointerX", {
  24984. /**
  24985. * Gets the current on-screen X position of the pointer
  24986. */
  24987. get: function () {
  24988. return this._pointerX;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. Object.defineProperty(Scene.prototype, "pointerY", {
  24994. /**
  24995. * Gets the current on-screen Y position of the pointer
  24996. */
  24997. get: function () {
  24998. return this._pointerY;
  24999. },
  25000. enumerable: true,
  25001. configurable: true
  25002. });
  25003. /**
  25004. * Gets the cached material (ie. the latest rendered one)
  25005. * @returns the cached material
  25006. */
  25007. Scene.prototype.getCachedMaterial = function () {
  25008. return this._cachedMaterial;
  25009. };
  25010. /**
  25011. * Gets the cached effect (ie. the latest rendered one)
  25012. * @returns the cached effect
  25013. */
  25014. Scene.prototype.getCachedEffect = function () {
  25015. return this._cachedEffect;
  25016. };
  25017. /**
  25018. * Gets the cached visibility state (ie. the latest rendered one)
  25019. * @returns the cached visibility state
  25020. */
  25021. Scene.prototype.getCachedVisibility = function () {
  25022. return this._cachedVisibility;
  25023. };
  25024. /**
  25025. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25026. * @param material defines the current material
  25027. * @param effect defines the current effect
  25028. * @param visibility defines the current visibility state
  25029. * @returns true if one parameter is not cached
  25030. */
  25031. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25032. if (visibility === void 0) { visibility = 1; }
  25033. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25034. };
  25035. /**
  25036. * Gets the bounding box renderer associated with the scene
  25037. * @returns a BoundingBoxRenderer
  25038. */
  25039. Scene.prototype.getBoundingBoxRenderer = function () {
  25040. if (!this._boundingBoxRenderer) {
  25041. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25042. }
  25043. return this._boundingBoxRenderer;
  25044. };
  25045. /**
  25046. * Gets the outline renderer associated with the scene
  25047. * @returns a OutlineRenderer
  25048. */
  25049. Scene.prototype.getOutlineRenderer = function () {
  25050. return this._outlineRenderer;
  25051. };
  25052. /**
  25053. * Gets the engine associated with the scene
  25054. * @returns an Engine
  25055. */
  25056. Scene.prototype.getEngine = function () {
  25057. return this._engine;
  25058. };
  25059. /**
  25060. * Gets the total number of vertices rendered per frame
  25061. * @returns the total number of vertices rendered per frame
  25062. */
  25063. Scene.prototype.getTotalVertices = function () {
  25064. return this._totalVertices.current;
  25065. };
  25066. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25067. /**
  25068. * Gets the performance counter for total vertices
  25069. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25070. */
  25071. get: function () {
  25072. return this._totalVertices;
  25073. },
  25074. enumerable: true,
  25075. configurable: true
  25076. });
  25077. /**
  25078. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25079. * @returns the total number of active indices rendered per frame
  25080. */
  25081. Scene.prototype.getActiveIndices = function () {
  25082. return this._activeIndices.current;
  25083. };
  25084. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25085. /**
  25086. * Gets the performance counter for active indices
  25087. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25088. */
  25089. get: function () {
  25090. return this._activeIndices;
  25091. },
  25092. enumerable: true,
  25093. configurable: true
  25094. });
  25095. /**
  25096. * Gets the total number of active particles rendered per frame
  25097. * @returns the total number of active particles rendered per frame
  25098. */
  25099. Scene.prototype.getActiveParticles = function () {
  25100. return this._activeParticles.current;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25103. /**
  25104. * Gets the performance counter for active particles
  25105. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25106. */
  25107. get: function () {
  25108. return this._activeParticles;
  25109. },
  25110. enumerable: true,
  25111. configurable: true
  25112. });
  25113. /**
  25114. * Gets the total number of active bones rendered per frame
  25115. * @returns the total number of active bones rendered per frame
  25116. */
  25117. Scene.prototype.getActiveBones = function () {
  25118. return this._activeBones.current;
  25119. };
  25120. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25121. /**
  25122. * Gets the performance counter for active bones
  25123. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25124. */
  25125. get: function () {
  25126. return this._activeBones;
  25127. },
  25128. enumerable: true,
  25129. configurable: true
  25130. });
  25131. /** @hidden */
  25132. Scene.prototype.getInterFramePerfCounter = function () {
  25133. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25134. return 0;
  25135. };
  25136. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25137. /** @hidden */
  25138. get: function () {
  25139. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25140. return null;
  25141. },
  25142. enumerable: true,
  25143. configurable: true
  25144. });
  25145. /** @hidden */
  25146. Scene.prototype.getLastFrameDuration = function () {
  25147. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25148. return 0;
  25149. };
  25150. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25151. /** @hidden */
  25152. get: function () {
  25153. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25154. return null;
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. /** @hidden */
  25160. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25161. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25162. return 0;
  25163. };
  25164. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25165. /** @hidden */
  25166. get: function () {
  25167. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25168. return null;
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. /**
  25174. * Gets the array of active meshes
  25175. * @returns an array of AbstractMesh
  25176. */
  25177. Scene.prototype.getActiveMeshes = function () {
  25178. return this._activeMeshes;
  25179. };
  25180. /** @hidden */
  25181. Scene.prototype.getRenderTargetsDuration = function () {
  25182. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25183. return 0;
  25184. };
  25185. /** @hidden */
  25186. Scene.prototype.getRenderDuration = function () {
  25187. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25188. return 0;
  25189. };
  25190. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25191. /** @hidden */
  25192. get: function () {
  25193. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25194. return null;
  25195. },
  25196. enumerable: true,
  25197. configurable: true
  25198. });
  25199. /** @hidden */
  25200. Scene.prototype.getParticlesDuration = function () {
  25201. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25202. return 0;
  25203. };
  25204. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25205. /** @hidden */
  25206. get: function () {
  25207. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25208. return null;
  25209. },
  25210. enumerable: true,
  25211. configurable: true
  25212. });
  25213. /** @hidden */
  25214. Scene.prototype.getSpritesDuration = function () {
  25215. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25216. return 0;
  25217. };
  25218. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25219. /** @hidden */
  25220. get: function () {
  25221. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25222. return null;
  25223. },
  25224. enumerable: true,
  25225. configurable: true
  25226. });
  25227. /**
  25228. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25229. * @returns a number
  25230. */
  25231. Scene.prototype.getAnimationRatio = function () {
  25232. return this._animationRatio;
  25233. };
  25234. /**
  25235. * Gets an unique Id for the current frame
  25236. * @returns a number
  25237. */
  25238. Scene.prototype.getRenderId = function () {
  25239. return this._renderId;
  25240. };
  25241. /** Call this function if you want to manually increment the render Id*/
  25242. Scene.prototype.incrementRenderId = function () {
  25243. this._renderId++;
  25244. };
  25245. Scene.prototype._updatePointerPosition = function (evt) {
  25246. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25247. if (!canvasRect) {
  25248. return;
  25249. }
  25250. this._pointerX = evt.clientX - canvasRect.left;
  25251. this._pointerY = evt.clientY - canvasRect.top;
  25252. this._unTranslatedPointerX = this._pointerX;
  25253. this._unTranslatedPointerY = this._pointerY;
  25254. };
  25255. Scene.prototype._createUbo = function () {
  25256. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25257. this._sceneUbo.addUniform("viewProjection", 16);
  25258. this._sceneUbo.addUniform("view", 16);
  25259. };
  25260. Scene.prototype._createAlternateUbo = function () {
  25261. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25262. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25263. this._alternateSceneUbo.addUniform("view", 16);
  25264. };
  25265. // Pointers handling
  25266. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25267. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25268. if (result) {
  25269. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25270. }
  25271. return result;
  25272. };
  25273. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25274. if (pointerInfo.pickInfo) {
  25275. if (!pointerInfo.pickInfo.ray) {
  25276. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25277. }
  25278. }
  25279. };
  25280. /**
  25281. * Use this method to simulate a pointer move on a mesh
  25282. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25283. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25284. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25285. * @returns the current scene
  25286. */
  25287. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25288. var evt = new PointerEvent("pointermove", pointerEventInit);
  25289. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25290. return this;
  25291. }
  25292. return this._processPointerMove(pickResult, evt);
  25293. };
  25294. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25295. var canvas = this._engine.getRenderingCanvas();
  25296. if (!canvas) {
  25297. return this;
  25298. }
  25299. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25300. this.setPointerOverSprite(null);
  25301. this.setPointerOverMesh(pickResult.pickedMesh);
  25302. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25303. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25304. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25305. }
  25306. else {
  25307. canvas.style.cursor = this.hoverCursor;
  25308. }
  25309. }
  25310. else {
  25311. canvas.style.cursor = this.defaultCursor;
  25312. }
  25313. }
  25314. else {
  25315. this.setPointerOverMesh(null);
  25316. // Sprites
  25317. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25318. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25319. this.setPointerOverSprite(pickResult.pickedSprite);
  25320. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25321. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25322. }
  25323. else {
  25324. canvas.style.cursor = this.hoverCursor;
  25325. }
  25326. }
  25327. else {
  25328. this.setPointerOverSprite(null);
  25329. // Restore pointer
  25330. canvas.style.cursor = this.defaultCursor;
  25331. }
  25332. }
  25333. if (pickResult) {
  25334. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25335. if (this.onPointerMove) {
  25336. this.onPointerMove(evt, pickResult, type);
  25337. }
  25338. if (this.onPointerObservable.hasObservers()) {
  25339. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25340. this._setRayOnPointerInfo(pi);
  25341. this.onPointerObservable.notifyObservers(pi, type);
  25342. }
  25343. }
  25344. return this;
  25345. };
  25346. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25347. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25348. if (pickResult) {
  25349. pi.ray = pickResult.ray;
  25350. }
  25351. this.onPrePointerObservable.notifyObservers(pi, type);
  25352. if (pi.skipOnPointerObservable) {
  25353. return true;
  25354. }
  25355. else {
  25356. return false;
  25357. }
  25358. };
  25359. /**
  25360. * Use this method to simulate a pointer down on a mesh
  25361. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25362. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25363. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25364. * @returns the current scene
  25365. */
  25366. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25367. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25368. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25369. return this;
  25370. }
  25371. return this._processPointerDown(pickResult, evt);
  25372. };
  25373. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25374. var _this = this;
  25375. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25376. this._pickedDownMesh = pickResult.pickedMesh;
  25377. var actionManager = pickResult.pickedMesh.actionManager;
  25378. if (actionManager) {
  25379. if (actionManager.hasPickTriggers) {
  25380. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25381. switch (evt.button) {
  25382. case 0:
  25383. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25384. break;
  25385. case 1:
  25386. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25387. break;
  25388. case 2:
  25389. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25390. break;
  25391. }
  25392. }
  25393. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25394. window.setTimeout(function () {
  25395. 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);
  25396. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25397. if (_this._totalPointersPressed !== 0 &&
  25398. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25399. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25400. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25401. _this._startingPointerTime = 0;
  25402. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25403. }
  25404. }
  25405. }, Scene.LongPressDelay);
  25406. }
  25407. }
  25408. }
  25409. if (pickResult) {
  25410. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25411. if (this.onPointerDown) {
  25412. this.onPointerDown(evt, pickResult, type);
  25413. }
  25414. if (this.onPointerObservable.hasObservers()) {
  25415. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25416. this._setRayOnPointerInfo(pi);
  25417. this.onPointerObservable.notifyObservers(pi, type);
  25418. }
  25419. }
  25420. return this;
  25421. };
  25422. /**
  25423. * Use this method to simulate a pointer up on a mesh
  25424. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25425. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25426. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25427. * @returns the current scene
  25428. */
  25429. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25430. var evt = new PointerEvent("pointerup", pointerEventInit);
  25431. var clickInfo = new ClickInfo();
  25432. clickInfo.singleClick = true;
  25433. clickInfo.ignore = true;
  25434. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25435. return this;
  25436. }
  25437. return this._processPointerUp(pickResult, evt, clickInfo);
  25438. };
  25439. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25440. if (pickResult && pickResult && pickResult.pickedMesh) {
  25441. this._pickedUpMesh = pickResult.pickedMesh;
  25442. if (this._pickedDownMesh === this._pickedUpMesh) {
  25443. if (this.onPointerPick) {
  25444. this.onPointerPick(evt, pickResult);
  25445. }
  25446. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25447. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25448. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25449. this._setRayOnPointerInfo(pi);
  25450. this.onPointerObservable.notifyObservers(pi, type_1);
  25451. }
  25452. }
  25453. if (pickResult.pickedMesh.actionManager) {
  25454. if (clickInfo.ignore) {
  25455. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25456. }
  25457. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25458. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25459. }
  25460. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25461. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25462. }
  25463. }
  25464. }
  25465. if (this._pickedDownMesh &&
  25466. this._pickedDownMesh.actionManager &&
  25467. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25468. this._pickedDownMesh !== this._pickedUpMesh) {
  25469. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25470. }
  25471. var type = BABYLON.PointerEventTypes.POINTERUP;
  25472. if (this.onPointerObservable.hasObservers()) {
  25473. if (!clickInfo.ignore) {
  25474. if (!clickInfo.hasSwiped) {
  25475. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25476. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25477. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25478. this._setRayOnPointerInfo(pi);
  25479. this.onPointerObservable.notifyObservers(pi, type_2);
  25480. }
  25481. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25482. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25483. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25484. this._setRayOnPointerInfo(pi);
  25485. this.onPointerObservable.notifyObservers(pi, type_3);
  25486. }
  25487. }
  25488. }
  25489. else {
  25490. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25491. this._setRayOnPointerInfo(pi);
  25492. this.onPointerObservable.notifyObservers(pi, type);
  25493. }
  25494. }
  25495. if (this.onPointerUp) {
  25496. this.onPointerUp(evt, pickResult, type);
  25497. }
  25498. return this;
  25499. };
  25500. /**
  25501. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25502. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25503. * @returns true if the pointer was captured
  25504. */
  25505. Scene.prototype.isPointerCaptured = function (pointerId) {
  25506. if (pointerId === void 0) { pointerId = 0; }
  25507. return this._pointerCaptures[pointerId];
  25508. };
  25509. /**
  25510. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25511. * @param attachUp defines if you want to attach events to pointerup
  25512. * @param attachDown defines if you want to attach events to pointerdown
  25513. * @param attachMove defines if you want to attach events to pointermove
  25514. */
  25515. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25516. var _this = this;
  25517. if (attachUp === void 0) { attachUp = true; }
  25518. if (attachDown === void 0) { attachDown = true; }
  25519. if (attachMove === void 0) { attachMove = true; }
  25520. this._initActionManager = function (act, clickInfo) {
  25521. if (!_this._meshPickProceed) {
  25522. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25523. _this._currentPickResult = pickResult;
  25524. if (pickResult) {
  25525. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25526. }
  25527. _this._meshPickProceed = true;
  25528. }
  25529. return act;
  25530. };
  25531. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25532. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25533. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25534. btn !== _this._previousButtonPressed) {
  25535. _this._doubleClickOccured = false;
  25536. clickInfo.singleClick = true;
  25537. clickInfo.ignore = false;
  25538. cb(clickInfo, _this._currentPickResult);
  25539. }
  25540. };
  25541. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25542. var clickInfo = new ClickInfo();
  25543. _this._currentPickResult = null;
  25544. var act = null;
  25545. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25546. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25547. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25548. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25549. act = _this._initActionManager(act, clickInfo);
  25550. if (act)
  25551. checkPicking = act.hasPickTriggers;
  25552. }
  25553. if (checkPicking) {
  25554. var btn = evt.button;
  25555. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25556. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25557. if (!clickInfo.hasSwiped) {
  25558. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25559. if (!checkSingleClickImmediately) {
  25560. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25561. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25562. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25563. act = _this._initActionManager(act, clickInfo);
  25564. if (act)
  25565. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25566. }
  25567. }
  25568. if (checkSingleClickImmediately) {
  25569. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25570. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25571. btn !== _this._previousButtonPressed) {
  25572. clickInfo.singleClick = true;
  25573. cb(clickInfo, _this._currentPickResult);
  25574. }
  25575. }
  25576. // at least one double click is required to be check and exclusive double click is enabled
  25577. else {
  25578. // wait that no double click has been raised during the double click delay
  25579. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25580. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25581. }
  25582. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25583. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25584. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25585. act = _this._initActionManager(act, clickInfo);
  25586. if (act)
  25587. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25588. }
  25589. if (checkDoubleClick) {
  25590. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25591. if (btn === _this._previousButtonPressed &&
  25592. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25593. !_this._doubleClickOccured) {
  25594. // pointer has not moved for 2 clicks, it's a double click
  25595. if (!clickInfo.hasSwiped &&
  25596. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25597. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25598. _this._previousStartingPointerTime = 0;
  25599. _this._doubleClickOccured = true;
  25600. clickInfo.doubleClick = true;
  25601. clickInfo.ignore = false;
  25602. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25603. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25604. }
  25605. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25606. cb(clickInfo, _this._currentPickResult);
  25607. }
  25608. // if the two successive clicks are too far, it's just two simple clicks
  25609. else {
  25610. _this._doubleClickOccured = false;
  25611. _this._previousStartingPointerTime = _this._startingPointerTime;
  25612. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25613. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25614. _this._previousButtonPressed = btn;
  25615. if (Scene.ExclusiveDoubleClickMode) {
  25616. if (_this._previousDelayedSimpleClickTimeout) {
  25617. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25618. }
  25619. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25620. cb(clickInfo, _this._previousPickResult);
  25621. }
  25622. else {
  25623. cb(clickInfo, _this._currentPickResult);
  25624. }
  25625. }
  25626. }
  25627. // just the first click of the double has been raised
  25628. else {
  25629. _this._doubleClickOccured = false;
  25630. _this._previousStartingPointerTime = _this._startingPointerTime;
  25631. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25632. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25633. _this._previousButtonPressed = btn;
  25634. }
  25635. }
  25636. }
  25637. }
  25638. clickInfo.ignore = true;
  25639. cb(clickInfo, _this._currentPickResult);
  25640. };
  25641. this._spritePredicate = function (sprite) {
  25642. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25643. };
  25644. this._onPointerMove = function (evt) {
  25645. _this._updatePointerPosition(evt);
  25646. // PreObservable support
  25647. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25648. return;
  25649. }
  25650. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25651. return;
  25652. }
  25653. if (!_this.pointerMovePredicate) {
  25654. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25655. }
  25656. // Meshes
  25657. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25658. _this._processPointerMove(pickResult, evt);
  25659. };
  25660. this._onPointerDown = function (evt) {
  25661. _this._totalPointersPressed++;
  25662. _this._pickedDownMesh = null;
  25663. _this._meshPickProceed = false;
  25664. _this._updatePointerPosition(evt);
  25665. if (_this.preventDefaultOnPointerDown && canvas) {
  25666. evt.preventDefault();
  25667. canvas.focus();
  25668. }
  25669. // PreObservable support
  25670. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25671. return;
  25672. }
  25673. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25674. return;
  25675. }
  25676. _this._pointerCaptures[evt.pointerId] = true;
  25677. _this._startingPointerPosition.x = _this._pointerX;
  25678. _this._startingPointerPosition.y = _this._pointerY;
  25679. _this._startingPointerTime = Date.now();
  25680. if (!_this.pointerDownPredicate) {
  25681. _this.pointerDownPredicate = function (mesh) {
  25682. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25683. };
  25684. }
  25685. // Meshes
  25686. _this._pickedDownMesh = null;
  25687. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25688. _this._processPointerDown(pickResult, evt);
  25689. // Sprites
  25690. _this._pickedDownSprite = null;
  25691. if (_this.spriteManagers.length > 0) {
  25692. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25693. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25694. if (pickResult.pickedSprite.actionManager) {
  25695. _this._pickedDownSprite = pickResult.pickedSprite;
  25696. switch (evt.button) {
  25697. case 0:
  25698. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25699. break;
  25700. case 1:
  25701. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25702. break;
  25703. case 2:
  25704. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25705. break;
  25706. }
  25707. if (pickResult.pickedSprite.actionManager) {
  25708. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25709. }
  25710. }
  25711. }
  25712. }
  25713. };
  25714. this._onPointerUp = function (evt) {
  25715. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25716. return; // So we need to test it the pointer down was pressed before.
  25717. }
  25718. _this._totalPointersPressed--;
  25719. _this._pickedUpMesh = null;
  25720. _this._meshPickProceed = false;
  25721. _this._updatePointerPosition(evt);
  25722. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25723. // PreObservable support
  25724. if (_this.onPrePointerObservable.hasObservers()) {
  25725. if (!clickInfo.ignore) {
  25726. if (!clickInfo.hasSwiped) {
  25727. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25728. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25729. return;
  25730. }
  25731. }
  25732. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25733. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25734. return;
  25735. }
  25736. }
  25737. }
  25738. }
  25739. else {
  25740. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25741. return;
  25742. }
  25743. }
  25744. }
  25745. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25746. return;
  25747. }
  25748. _this._pointerCaptures[evt.pointerId] = false;
  25749. if (!_this.pointerUpPredicate) {
  25750. _this.pointerUpPredicate = function (mesh) {
  25751. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25752. };
  25753. }
  25754. // Meshes
  25755. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25756. _this._initActionManager(null, clickInfo);
  25757. }
  25758. if (!pickResult) {
  25759. pickResult = _this._currentPickResult;
  25760. }
  25761. _this._processPointerUp(pickResult, evt, clickInfo);
  25762. // Sprites
  25763. if (!clickInfo.ignore) {
  25764. if (_this.spriteManagers.length > 0) {
  25765. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25766. if (spritePickResult) {
  25767. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25768. if (spritePickResult.pickedSprite.actionManager) {
  25769. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25770. if (spritePickResult.pickedSprite.actionManager) {
  25771. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25772. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25773. }
  25774. }
  25775. }
  25776. }
  25777. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25778. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25779. }
  25780. }
  25781. }
  25782. }
  25783. _this._previousPickResult = _this._currentPickResult;
  25784. });
  25785. };
  25786. this._onKeyDown = function (evt) {
  25787. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25788. if (_this.onPreKeyboardObservable.hasObservers()) {
  25789. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25790. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25791. if (pi.skipOnPointerObservable) {
  25792. return;
  25793. }
  25794. }
  25795. if (_this.onKeyboardObservable.hasObservers()) {
  25796. var pi = new BABYLON.KeyboardInfo(type, evt);
  25797. _this.onKeyboardObservable.notifyObservers(pi, type);
  25798. }
  25799. if (_this.actionManager) {
  25800. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25801. }
  25802. };
  25803. this._onKeyUp = function (evt) {
  25804. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25805. if (_this.onPreKeyboardObservable.hasObservers()) {
  25806. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25807. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25808. if (pi.skipOnPointerObservable) {
  25809. return;
  25810. }
  25811. }
  25812. if (_this.onKeyboardObservable.hasObservers()) {
  25813. var pi = new BABYLON.KeyboardInfo(type, evt);
  25814. _this.onKeyboardObservable.notifyObservers(pi, type);
  25815. }
  25816. if (_this.actionManager) {
  25817. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25818. }
  25819. };
  25820. var engine = this.getEngine();
  25821. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25822. if (!canvas) {
  25823. return;
  25824. }
  25825. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25826. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25827. });
  25828. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25829. if (!canvas) {
  25830. return;
  25831. }
  25832. canvas.removeEventListener("keydown", _this._onKeyDown);
  25833. canvas.removeEventListener("keyup", _this._onKeyUp);
  25834. });
  25835. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25836. var canvas = this._engine.getRenderingCanvas();
  25837. if (!canvas) {
  25838. return;
  25839. }
  25840. if (attachMove) {
  25841. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25842. // Wheel
  25843. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25844. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25845. }
  25846. if (attachDown) {
  25847. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25848. }
  25849. if (attachUp) {
  25850. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25851. }
  25852. canvas.tabIndex = 1;
  25853. };
  25854. /** Detaches all event handlers*/
  25855. Scene.prototype.detachControl = function () {
  25856. var engine = this.getEngine();
  25857. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25858. var canvas = engine.getRenderingCanvas();
  25859. if (!canvas) {
  25860. return;
  25861. }
  25862. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25863. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25864. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25865. if (this._onCanvasBlurObserver) {
  25866. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25867. }
  25868. if (this._onCanvasFocusObserver) {
  25869. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25870. }
  25871. // Wheel
  25872. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25873. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25874. // Keyboard
  25875. canvas.removeEventListener("keydown", this._onKeyDown);
  25876. canvas.removeEventListener("keyup", this._onKeyUp);
  25877. // Observables
  25878. this.onKeyboardObservable.clear();
  25879. this.onPreKeyboardObservable.clear();
  25880. this.onPointerObservable.clear();
  25881. this.onPrePointerObservable.clear();
  25882. };
  25883. /**
  25884. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25885. * Delay loaded resources are not taking in account
  25886. * @return true if all required resources are ready
  25887. */
  25888. Scene.prototype.isReady = function () {
  25889. if (this._isDisposed) {
  25890. return false;
  25891. }
  25892. if (this._pendingData.length > 0) {
  25893. return false;
  25894. }
  25895. var index;
  25896. var engine = this.getEngine();
  25897. // Geometries
  25898. for (index = 0; index < this._geometries.length; index++) {
  25899. var geometry = this._geometries[index];
  25900. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25901. return false;
  25902. }
  25903. }
  25904. // Meshes
  25905. for (index = 0; index < this.meshes.length; index++) {
  25906. var mesh = this.meshes[index];
  25907. if (!mesh.isEnabled()) {
  25908. continue;
  25909. }
  25910. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25911. continue;
  25912. }
  25913. if (!mesh.isReady(true)) {
  25914. return false;
  25915. }
  25916. // Effect layers
  25917. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25918. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25919. var layer = _a[_i];
  25920. if (!layer.hasMesh(mesh)) {
  25921. continue;
  25922. }
  25923. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25924. var subMesh = _c[_b];
  25925. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25926. return false;
  25927. }
  25928. }
  25929. }
  25930. }
  25931. // Post-processes
  25932. if (this.activeCameras && this.activeCameras.length > 0) {
  25933. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25934. var camera = _e[_d];
  25935. if (!camera.isReady(true)) {
  25936. return false;
  25937. }
  25938. }
  25939. }
  25940. else if (this.activeCamera) {
  25941. if (!this.activeCamera.isReady(true)) {
  25942. return false;
  25943. }
  25944. }
  25945. // Particles
  25946. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25947. var particleSystem = _g[_f];
  25948. if (!particleSystem.isReady()) {
  25949. return false;
  25950. }
  25951. }
  25952. return true;
  25953. };
  25954. /** Resets all cached information relative to material (including effect and visibility) */
  25955. Scene.prototype.resetCachedMaterial = function () {
  25956. this._cachedMaterial = null;
  25957. this._cachedEffect = null;
  25958. this._cachedVisibility = null;
  25959. };
  25960. /**
  25961. * Registers a function to be called before every frame render
  25962. * @param func defines the function to register
  25963. */
  25964. Scene.prototype.registerBeforeRender = function (func) {
  25965. this.onBeforeRenderObservable.add(func);
  25966. };
  25967. /**
  25968. * Unregisters a function called before every frame render
  25969. * @param func defines the function to unregister
  25970. */
  25971. Scene.prototype.unregisterBeforeRender = function (func) {
  25972. this.onBeforeRenderObservable.removeCallback(func);
  25973. };
  25974. /**
  25975. * Registers a function to be called after every frame render
  25976. * @param func defines the function to register
  25977. */
  25978. Scene.prototype.registerAfterRender = function (func) {
  25979. this.onAfterRenderObservable.add(func);
  25980. };
  25981. /**
  25982. * Unregisters a function called after every frame render
  25983. * @param func defines the function to unregister
  25984. */
  25985. Scene.prototype.unregisterAfterRender = function (func) {
  25986. this.onAfterRenderObservable.removeCallback(func);
  25987. };
  25988. Scene.prototype._executeOnceBeforeRender = function (func) {
  25989. var _this = this;
  25990. var execFunc = function () {
  25991. func();
  25992. setTimeout(function () {
  25993. _this.unregisterBeforeRender(execFunc);
  25994. });
  25995. };
  25996. this.registerBeforeRender(execFunc);
  25997. };
  25998. /**
  25999. * The provided function will run before render once and will be disposed afterwards.
  26000. * A timeout delay can be provided so that the function will be executed in N ms.
  26001. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26002. * @param func The function to be executed.
  26003. * @param timeout optional delay in ms
  26004. */
  26005. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26006. var _this = this;
  26007. if (timeout !== undefined) {
  26008. setTimeout(function () {
  26009. _this._executeOnceBeforeRender(func);
  26010. }, timeout);
  26011. }
  26012. else {
  26013. this._executeOnceBeforeRender(func);
  26014. }
  26015. };
  26016. /** @hidden */
  26017. Scene.prototype._addPendingData = function (data) {
  26018. this._pendingData.push(data);
  26019. };
  26020. /** @hidden */
  26021. Scene.prototype._removePendingData = function (data) {
  26022. var wasLoading = this.isLoading;
  26023. var index = this._pendingData.indexOf(data);
  26024. if (index !== -1) {
  26025. this._pendingData.splice(index, 1);
  26026. }
  26027. if (wasLoading && !this.isLoading) {
  26028. this.onDataLoadedObservable.notifyObservers(this);
  26029. }
  26030. };
  26031. /**
  26032. * Returns the number of items waiting to be loaded
  26033. * @returns the number of items waiting to be loaded
  26034. */
  26035. Scene.prototype.getWaitingItemsCount = function () {
  26036. return this._pendingData.length;
  26037. };
  26038. Object.defineProperty(Scene.prototype, "isLoading", {
  26039. /**
  26040. * Returns a boolean indicating if the scene is still loading data
  26041. */
  26042. get: function () {
  26043. return this._pendingData.length > 0;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. /**
  26049. * Registers a function to be executed when the scene is ready
  26050. * @param {Function} func - the function to be executed
  26051. */
  26052. Scene.prototype.executeWhenReady = function (func) {
  26053. var _this = this;
  26054. this.onReadyObservable.add(func);
  26055. if (this._executeWhenReadyTimeoutId !== -1) {
  26056. return;
  26057. }
  26058. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26059. _this._checkIsReady();
  26060. }, 150);
  26061. };
  26062. /**
  26063. * Returns a promise that resolves when the scene is ready
  26064. * @returns A promise that resolves when the scene is ready
  26065. */
  26066. Scene.prototype.whenReadyAsync = function () {
  26067. var _this = this;
  26068. return new Promise(function (resolve) {
  26069. _this.executeWhenReady(function () {
  26070. resolve();
  26071. });
  26072. });
  26073. };
  26074. /** @hidden */
  26075. Scene.prototype._checkIsReady = function () {
  26076. var _this = this;
  26077. if (this.isReady()) {
  26078. this.onReadyObservable.notifyObservers(this);
  26079. this.onReadyObservable.clear();
  26080. this._executeWhenReadyTimeoutId = -1;
  26081. return;
  26082. }
  26083. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26084. _this._checkIsReady();
  26085. }, 150);
  26086. };
  26087. // Animations
  26088. /**
  26089. * Will start the animation sequence of a given target
  26090. * @param target defines the target
  26091. * @param from defines from which frame should animation start
  26092. * @param to defines until which frame should animation run.
  26093. * @param weight defines the weight to apply to the animation (1.0 by default)
  26094. * @param loop defines if the animation loops
  26095. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26096. * @param onAnimationEnd defines the function to be executed when the animation ends
  26097. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26098. * @returns the animatable object created for this animation
  26099. */
  26100. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26101. if (weight === void 0) { weight = 1.0; }
  26102. if (speedRatio === void 0) { speedRatio = 1.0; }
  26103. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26104. returnedAnimatable.weight = weight;
  26105. return returnedAnimatable;
  26106. };
  26107. /**
  26108. * Will start the animation sequence of a given target
  26109. * @param target defines the target
  26110. * @param from defines from which frame should animation start
  26111. * @param to defines until which frame should animation run.
  26112. * @param loop defines if the animation loops
  26113. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26114. * @param onAnimationEnd defines the function to be executed when the animation ends
  26115. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26116. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26117. * @returns the animatable object created for this animation
  26118. */
  26119. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26120. if (speedRatio === void 0) { speedRatio = 1.0; }
  26121. if (stopCurrent === void 0) { stopCurrent = true; }
  26122. if (from > to && speedRatio > 0) {
  26123. speedRatio *= -1;
  26124. }
  26125. if (stopCurrent) {
  26126. this.stopAnimation(target);
  26127. }
  26128. if (!animatable) {
  26129. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26130. }
  26131. // Local animations
  26132. if (target.animations) {
  26133. animatable.appendAnimations(target, target.animations);
  26134. }
  26135. // Children animations
  26136. if (target.getAnimatables) {
  26137. var animatables = target.getAnimatables();
  26138. for (var index = 0; index < animatables.length; index++) {
  26139. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26140. }
  26141. }
  26142. animatable.reset();
  26143. return animatable;
  26144. };
  26145. /**
  26146. * Begin a new animation on a given node
  26147. * @param target defines the target where the animation will take place
  26148. * @param animations defines the list of animations to start
  26149. * @param from defines the initial value
  26150. * @param to defines the final value
  26151. * @param loop defines if you want animation to loop (off by default)
  26152. * @param speedRatio defines the speed ratio to apply to all animations
  26153. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26154. * @returns the list of created animatables
  26155. */
  26156. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26157. if (speedRatio === undefined) {
  26158. speedRatio = 1.0;
  26159. }
  26160. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26161. return animatable;
  26162. };
  26163. /**
  26164. * Begin a new animation on a given node and its hierarchy
  26165. * @param target defines the root node where the animation will take place
  26166. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  26167. * @param animations defines the list of animations to start
  26168. * @param from defines the initial value
  26169. * @param to defines the final value
  26170. * @param loop defines if you want animation to loop (off by default)
  26171. * @param speedRatio defines the speed ratio to apply to all animations
  26172. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26173. * @returns the list of animatables created for all nodes
  26174. */
  26175. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26176. var children = target.getDescendants(directDescendantsOnly);
  26177. var result = [];
  26178. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26179. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26180. var child = children_1[_i];
  26181. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26182. }
  26183. return result;
  26184. };
  26185. /**
  26186. * Gets the animatable associated with a specific target
  26187. * @param target defines the target of the animatable
  26188. * @returns the required animatable if found
  26189. */
  26190. Scene.prototype.getAnimatableByTarget = function (target) {
  26191. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26192. if (this._activeAnimatables[index].target === target) {
  26193. return this._activeAnimatables[index];
  26194. }
  26195. }
  26196. return null;
  26197. };
  26198. /**
  26199. * Gets all animatables associated with a given target
  26200. * @param target defines the target to look animatables for
  26201. * @returns an array of Animatables
  26202. */
  26203. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26204. var result = [];
  26205. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26206. if (this._activeAnimatables[index].target === target) {
  26207. result.push(this._activeAnimatables[index]);
  26208. }
  26209. }
  26210. return result;
  26211. };
  26212. Object.defineProperty(Scene.prototype, "animatables", {
  26213. /**
  26214. * Gets all animatable attached to the scene
  26215. */
  26216. get: function () {
  26217. return this._activeAnimatables;
  26218. },
  26219. enumerable: true,
  26220. configurable: true
  26221. });
  26222. /**
  26223. * Will stop the animation of the given target
  26224. * @param target - the target
  26225. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26226. */
  26227. Scene.prototype.stopAnimation = function (target, animationName) {
  26228. var animatables = this.getAllAnimatablesByTarget(target);
  26229. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26230. var animatable = animatables_1[_i];
  26231. animatable.stop(animationName);
  26232. }
  26233. };
  26234. /**
  26235. * Stops and removes all animations that have been applied to the scene
  26236. */
  26237. Scene.prototype.stopAllAnimations = function () {
  26238. if (this._activeAnimatables) {
  26239. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26240. this._activeAnimatables[i].stop();
  26241. }
  26242. this._activeAnimatables = [];
  26243. }
  26244. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26245. var group = _a[_i];
  26246. group.stop();
  26247. }
  26248. };
  26249. Scene.prototype._animate = function () {
  26250. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26251. return;
  26252. }
  26253. // Getting time
  26254. var now = BABYLON.Tools.Now;
  26255. if (!this._animationTimeLast) {
  26256. if (this._pendingData.length > 0) {
  26257. return;
  26258. }
  26259. this._animationTimeLast = now;
  26260. }
  26261. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26262. this._animationTime += deltaTime;
  26263. this._animationTimeLast = now;
  26264. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26265. this._activeAnimatables[index]._animate(this._animationTime);
  26266. }
  26267. // Late animation bindings
  26268. this._processLateAnimationBindings();
  26269. };
  26270. /** @hidden */
  26271. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26272. var target = runtimeAnimation.target;
  26273. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26274. if (!target._lateAnimationHolders) {
  26275. target._lateAnimationHolders = {};
  26276. }
  26277. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26278. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26279. totalWeight: 0,
  26280. animations: [],
  26281. originalValue: originalValue
  26282. };
  26283. }
  26284. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26285. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26286. };
  26287. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26288. var normalizer = 1.0;
  26289. var finalPosition = BABYLON.Tmp.Vector3[0];
  26290. var finalScaling = BABYLON.Tmp.Vector3[1];
  26291. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26292. var startIndex = 0;
  26293. var originalAnimation = holder.animations[0];
  26294. var originalValue = holder.originalValue;
  26295. var scale = 1;
  26296. if (holder.totalWeight < 1.0) {
  26297. // We need to mix the original value in
  26298. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26299. scale = 1.0 - holder.totalWeight;
  26300. }
  26301. else {
  26302. startIndex = 1;
  26303. // We need to normalize the weights
  26304. normalizer = holder.totalWeight;
  26305. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26306. scale = originalAnimation.weight / normalizer;
  26307. if (scale == 1) {
  26308. return originalAnimation.currentValue;
  26309. }
  26310. }
  26311. finalScaling.scaleInPlace(scale);
  26312. finalPosition.scaleInPlace(scale);
  26313. finalQuaternion.scaleInPlace(scale);
  26314. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26315. var runtimeAnimation = holder.animations[animIndex];
  26316. var scale = runtimeAnimation.weight / normalizer;
  26317. var currentPosition = BABYLON.Tmp.Vector3[2];
  26318. var currentScaling = BABYLON.Tmp.Vector3[3];
  26319. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26320. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26321. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26322. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26323. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26324. }
  26325. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26326. return originalAnimation._workValue;
  26327. };
  26328. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26329. var originalAnimation = holder.animations[0];
  26330. var originalValue = holder.originalValue;
  26331. if (holder.animations.length === 1) {
  26332. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26333. }
  26334. var normalizer = 1.0;
  26335. var quaternions;
  26336. var weights;
  26337. if (holder.totalWeight < 1.0) {
  26338. var scale = 1.0 - holder.totalWeight;
  26339. quaternions = [];
  26340. weights = [];
  26341. quaternions.push(originalValue);
  26342. weights.push(scale);
  26343. }
  26344. else {
  26345. if (holder.animations.length === 2) { // Slerp as soon as we can
  26346. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26347. }
  26348. quaternions = [];
  26349. weights = [];
  26350. normalizer = holder.totalWeight;
  26351. }
  26352. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26353. var runtimeAnimation = holder.animations[animIndex];
  26354. quaternions.push(runtimeAnimation.currentValue);
  26355. weights.push(runtimeAnimation.weight / normalizer);
  26356. }
  26357. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26358. var cumulativeAmount = 0;
  26359. var cumulativeQuaternion = null;
  26360. for (var index = 0; index < quaternions.length;) {
  26361. if (!cumulativeQuaternion) {
  26362. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26363. cumulativeAmount = weights[index] + weights[index + 1];
  26364. index += 2;
  26365. continue;
  26366. }
  26367. cumulativeAmount += weights[index];
  26368. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26369. index++;
  26370. }
  26371. return cumulativeQuaternion;
  26372. };
  26373. Scene.prototype._processLateAnimationBindings = function () {
  26374. if (!this._registeredForLateAnimationBindings.length) {
  26375. return;
  26376. }
  26377. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26378. var target = this._registeredForLateAnimationBindings.data[index];
  26379. for (var path in target._lateAnimationHolders) {
  26380. var holder = target._lateAnimationHolders[path];
  26381. var originalAnimation = holder.animations[0];
  26382. var originalValue = holder.originalValue;
  26383. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26384. var finalValue = void 0;
  26385. if (matrixDecomposeMode) {
  26386. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26387. }
  26388. else {
  26389. var quaternionMode = originalValue.w !== undefined;
  26390. if (quaternionMode) {
  26391. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26392. }
  26393. else {
  26394. var startIndex = 0;
  26395. var normalizer = 1.0;
  26396. if (holder.totalWeight < 1.0) {
  26397. // We need to mix the original value in
  26398. if (originalValue.scale) {
  26399. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26400. }
  26401. else {
  26402. finalValue = originalValue * (1.0 - holder.totalWeight);
  26403. }
  26404. }
  26405. else {
  26406. // We need to normalize the weights
  26407. normalizer = holder.totalWeight;
  26408. var scale_1 = originalAnimation.weight / normalizer;
  26409. if (scale_1 !== 1) {
  26410. if (originalAnimation.currentValue.scale) {
  26411. finalValue = originalAnimation.currentValue.scale(scale_1);
  26412. }
  26413. else {
  26414. finalValue = originalAnimation.currentValue * scale_1;
  26415. }
  26416. }
  26417. else {
  26418. finalValue = originalAnimation.currentValue;
  26419. }
  26420. startIndex = 1;
  26421. }
  26422. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26423. var runtimeAnimation = holder.animations[animIndex];
  26424. var scale = runtimeAnimation.weight / normalizer;
  26425. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26426. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26427. }
  26428. else {
  26429. finalValue += runtimeAnimation.currentValue * scale;
  26430. }
  26431. }
  26432. }
  26433. }
  26434. target[path] = finalValue;
  26435. }
  26436. target._lateAnimationHolders = {};
  26437. }
  26438. this._registeredForLateAnimationBindings.reset();
  26439. };
  26440. // Matrix
  26441. /** @hidden */
  26442. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26443. this._useAlternateCameraConfiguration = active;
  26444. };
  26445. /**
  26446. * Gets the current view matrix
  26447. * @returns a Matrix
  26448. */
  26449. Scene.prototype.getViewMatrix = function () {
  26450. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26451. };
  26452. /**
  26453. * Gets the current projection matrix
  26454. * @returns a Matrix
  26455. */
  26456. Scene.prototype.getProjectionMatrix = function () {
  26457. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26458. };
  26459. /**
  26460. * Gets the current transform matrix
  26461. * @returns a Matrix made of View * Projection
  26462. */
  26463. Scene.prototype.getTransformMatrix = function () {
  26464. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26465. };
  26466. /**
  26467. * Sets the current transform matrix
  26468. * @param view defines the View matrix to use
  26469. * @param projection defines the Projection matrix to use
  26470. */
  26471. Scene.prototype.setTransformMatrix = function (view, projection) {
  26472. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26473. return;
  26474. }
  26475. this._viewUpdateFlag = view.updateFlag;
  26476. this._projectionUpdateFlag = projection.updateFlag;
  26477. this._viewMatrix = view;
  26478. this._projectionMatrix = projection;
  26479. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26480. // Update frustum
  26481. if (!this._frustumPlanes) {
  26482. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26483. }
  26484. else {
  26485. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26486. }
  26487. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26488. var otherCamera = this.activeCamera._alternateCamera;
  26489. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26490. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26491. }
  26492. if (this._sceneUbo.useUbo) {
  26493. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26494. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26495. this._sceneUbo.update();
  26496. }
  26497. };
  26498. /** @hidden */
  26499. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26500. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26501. return;
  26502. }
  26503. this._alternateViewUpdateFlag = view.updateFlag;
  26504. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26505. this._alternateViewMatrix = view;
  26506. this._alternateProjectionMatrix = projection;
  26507. if (!this._alternateTransformMatrix) {
  26508. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26509. }
  26510. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26511. if (!this._alternateSceneUbo) {
  26512. this._createAlternateUbo();
  26513. }
  26514. if (this._alternateSceneUbo.useUbo) {
  26515. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26516. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26517. this._alternateSceneUbo.update();
  26518. }
  26519. };
  26520. /**
  26521. * Gets the uniform buffer used to store scene data
  26522. * @returns a UniformBuffer
  26523. */
  26524. Scene.prototype.getSceneUniformBuffer = function () {
  26525. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26526. };
  26527. /**
  26528. * Gets an unique (relatively to the current scene) Id
  26529. * @returns an unique number for the scene
  26530. */
  26531. Scene.prototype.getUniqueId = function () {
  26532. var result = Scene._uniqueIdCounter;
  26533. Scene._uniqueIdCounter++;
  26534. return result;
  26535. };
  26536. /**
  26537. * Add a mesh to the list of scene's meshes
  26538. * @param newMesh defines the mesh to add
  26539. * @param recursive if all child meshes should also be added to the scene
  26540. */
  26541. Scene.prototype.addMesh = function (newMesh, recursive) {
  26542. var _this = this;
  26543. if (recursive === void 0) { recursive = false; }
  26544. this.meshes.push(newMesh);
  26545. //notify the collision coordinator
  26546. if (this.collisionCoordinator) {
  26547. this.collisionCoordinator.onMeshAdded(newMesh);
  26548. }
  26549. newMesh._resyncLightSources();
  26550. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26551. if (recursive) {
  26552. newMesh.getChildMeshes().forEach(function (m) {
  26553. _this.addMesh(m);
  26554. });
  26555. }
  26556. };
  26557. /**
  26558. * Remove a mesh for the list of scene's meshes
  26559. * @param toRemove defines the mesh to remove
  26560. * @param recursive if all child meshes should also be removed from the scene
  26561. * @returns the index where the mesh was in the mesh list
  26562. */
  26563. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26564. var _this = this;
  26565. if (recursive === void 0) { recursive = false; }
  26566. var index = this.meshes.indexOf(toRemove);
  26567. if (index !== -1) {
  26568. // Remove from the scene if mesh found
  26569. this.meshes.splice(index, 1);
  26570. }
  26571. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26572. if (recursive) {
  26573. toRemove.getChildMeshes().forEach(function (m) {
  26574. _this.removeMesh(m);
  26575. });
  26576. }
  26577. return index;
  26578. };
  26579. /**
  26580. * Add a transform node to the list of scene's transform nodes
  26581. * @param newTransformNode defines the transform node to add
  26582. */
  26583. Scene.prototype.addTransformNode = function (newTransformNode) {
  26584. this.transformNodes.push(newTransformNode);
  26585. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26586. };
  26587. /**
  26588. * Remove a transform node for the list of scene's transform nodes
  26589. * @param toRemove defines the transform node to remove
  26590. * @returns the index where the transform node was in the transform node list
  26591. */
  26592. Scene.prototype.removeTransformNode = function (toRemove) {
  26593. var index = this.transformNodes.indexOf(toRemove);
  26594. if (index !== -1) {
  26595. // Remove from the scene if found
  26596. this.transformNodes.splice(index, 1);
  26597. }
  26598. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26599. return index;
  26600. };
  26601. /**
  26602. * Remove a skeleton for the list of scene's skeletons
  26603. * @param toRemove defines the skeleton to remove
  26604. * @returns the index where the skeleton was in the skeleton list
  26605. */
  26606. Scene.prototype.removeSkeleton = function (toRemove) {
  26607. var index = this.skeletons.indexOf(toRemove);
  26608. if (index !== -1) {
  26609. // Remove from the scene if found
  26610. this.skeletons.splice(index, 1);
  26611. }
  26612. return index;
  26613. };
  26614. /**
  26615. * Remove a morph target for the list of scene's morph targets
  26616. * @param toRemove defines the morph target to remove
  26617. * @returns the index where the morph target was in the morph target list
  26618. */
  26619. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26620. var index = this.morphTargetManagers.indexOf(toRemove);
  26621. if (index !== -1) {
  26622. // Remove from the scene if found
  26623. this.morphTargetManagers.splice(index, 1);
  26624. }
  26625. return index;
  26626. };
  26627. /**
  26628. * Remove a light for the list of scene's lights
  26629. * @param toRemove defines the light to remove
  26630. * @returns the index where the light was in the light list
  26631. */
  26632. Scene.prototype.removeLight = function (toRemove) {
  26633. var index = this.lights.indexOf(toRemove);
  26634. if (index !== -1) {
  26635. // Remove from meshes
  26636. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26637. var mesh = _a[_i];
  26638. mesh._removeLightSource(toRemove);
  26639. }
  26640. // Remove from the scene if mesh found
  26641. this.lights.splice(index, 1);
  26642. this.sortLightsByPriority();
  26643. }
  26644. this.onLightRemovedObservable.notifyObservers(toRemove);
  26645. return index;
  26646. };
  26647. /**
  26648. * Remove a camera for the list of scene's cameras
  26649. * @param toRemove defines the camera to remove
  26650. * @returns the index where the camera was in the camera list
  26651. */
  26652. Scene.prototype.removeCamera = function (toRemove) {
  26653. var index = this.cameras.indexOf(toRemove);
  26654. if (index !== -1) {
  26655. // Remove from the scene if mesh found
  26656. this.cameras.splice(index, 1);
  26657. }
  26658. // Remove from activeCameras
  26659. var index2 = this.activeCameras.indexOf(toRemove);
  26660. if (index2 !== -1) {
  26661. // Remove from the scene if mesh found
  26662. this.activeCameras.splice(index2, 1);
  26663. }
  26664. // Reset the activeCamera
  26665. if (this.activeCamera === toRemove) {
  26666. if (this.cameras.length > 0) {
  26667. this.activeCamera = this.cameras[0];
  26668. }
  26669. else {
  26670. this.activeCamera = null;
  26671. }
  26672. }
  26673. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26674. return index;
  26675. };
  26676. /**
  26677. * Remove a particle system for the list of scene's particle systems
  26678. * @param toRemove defines the particle system to remove
  26679. * @returns the index where the particle system was in the particle system list
  26680. */
  26681. Scene.prototype.removeParticleSystem = function (toRemove) {
  26682. var index = this.particleSystems.indexOf(toRemove);
  26683. if (index !== -1) {
  26684. this.particleSystems.splice(index, 1);
  26685. }
  26686. return index;
  26687. };
  26688. /**
  26689. * Remove a animation for the list of scene's animations
  26690. * @param toRemove defines the animation to remove
  26691. * @returns the index where the animation was in the animation list
  26692. */
  26693. Scene.prototype.removeAnimation = function (toRemove) {
  26694. var index = this.animations.indexOf(toRemove);
  26695. if (index !== -1) {
  26696. this.animations.splice(index, 1);
  26697. }
  26698. return index;
  26699. };
  26700. /**
  26701. * Removes the given animation group from this scene.
  26702. * @param toRemove The animation group to remove
  26703. * @returns The index of the removed animation group
  26704. */
  26705. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26706. var index = this.animationGroups.indexOf(toRemove);
  26707. if (index !== -1) {
  26708. this.animationGroups.splice(index, 1);
  26709. }
  26710. return index;
  26711. };
  26712. /**
  26713. * Removes the given multi-material from this scene.
  26714. * @param toRemove The multi-material to remove
  26715. * @returns The index of the removed multi-material
  26716. */
  26717. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26718. var index = this.multiMaterials.indexOf(toRemove);
  26719. if (index !== -1) {
  26720. this.multiMaterials.splice(index, 1);
  26721. }
  26722. return index;
  26723. };
  26724. /**
  26725. * Removes the given material from this scene.
  26726. * @param toRemove The material to remove
  26727. * @returns The index of the removed material
  26728. */
  26729. Scene.prototype.removeMaterial = function (toRemove) {
  26730. var index = this.materials.indexOf(toRemove);
  26731. if (index !== -1) {
  26732. this.materials.splice(index, 1);
  26733. }
  26734. return index;
  26735. };
  26736. /**
  26737. * Removes the given lens flare system from this scene.
  26738. * @param toRemove The lens flare system to remove
  26739. * @returns The index of the removed lens flare system
  26740. */
  26741. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26742. var index = this.lensFlareSystems.indexOf(toRemove);
  26743. if (index !== -1) {
  26744. this.lensFlareSystems.splice(index, 1);
  26745. }
  26746. return index;
  26747. };
  26748. /**
  26749. * Removes the given action manager from this scene.
  26750. * @param toRemove The action manager to remove
  26751. * @returns The index of the removed action manager
  26752. */
  26753. Scene.prototype.removeActionManager = function (toRemove) {
  26754. var index = this._actionManagers.indexOf(toRemove);
  26755. if (index !== -1) {
  26756. this._actionManagers.splice(index, 1);
  26757. }
  26758. return index;
  26759. };
  26760. /**
  26761. * Removes the given effect layer from this scene.
  26762. * @param toRemove defines the effect layer to remove
  26763. * @returns the index of the removed effect layer
  26764. */
  26765. Scene.prototype.removeEffectLayer = function (toRemove) {
  26766. var index = this.effectLayers.indexOf(toRemove);
  26767. if (index !== -1) {
  26768. this.effectLayers.splice(index, 1);
  26769. }
  26770. return index;
  26771. };
  26772. /**
  26773. * Removes the given texture from this scene.
  26774. * @param toRemove The texture to remove
  26775. * @returns The index of the removed texture
  26776. */
  26777. Scene.prototype.removeTexture = function (toRemove) {
  26778. var index = this.textures.indexOf(toRemove);
  26779. if (index !== -1) {
  26780. this.textures.splice(index, 1);
  26781. }
  26782. return index;
  26783. };
  26784. /**
  26785. * Adds the given light to this scene
  26786. * @param newLight The light to add
  26787. */
  26788. Scene.prototype.addLight = function (newLight) {
  26789. this.lights.push(newLight);
  26790. this.sortLightsByPriority();
  26791. // Add light to all meshes (To support if the light is removed and then readded)
  26792. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26793. var mesh = _a[_i];
  26794. if (mesh._lightSources.indexOf(newLight) === -1) {
  26795. mesh._lightSources.push(newLight);
  26796. mesh._resyncLightSources();
  26797. }
  26798. }
  26799. this.onNewLightAddedObservable.notifyObservers(newLight);
  26800. };
  26801. /**
  26802. * Sorts the list list based on light priorities
  26803. */
  26804. Scene.prototype.sortLightsByPriority = function () {
  26805. if (this.requireLightSorting) {
  26806. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26807. }
  26808. };
  26809. /**
  26810. * Adds the given camera to this scene
  26811. * @param newCamera The camera to add
  26812. */
  26813. Scene.prototype.addCamera = function (newCamera) {
  26814. this.cameras.push(newCamera);
  26815. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26816. };
  26817. /**
  26818. * Adds the given skeleton to this scene
  26819. * @param newSkeleton The skeleton to add
  26820. */
  26821. Scene.prototype.addSkeleton = function (newSkeleton) {
  26822. this.skeletons.push(newSkeleton);
  26823. };
  26824. /**
  26825. * Adds the given particle system to this scene
  26826. * @param newParticleSystem The particle system to add
  26827. */
  26828. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26829. this.particleSystems.push(newParticleSystem);
  26830. };
  26831. /**
  26832. * Adds the given animation to this scene
  26833. * @param newAnimation The animation to add
  26834. */
  26835. Scene.prototype.addAnimation = function (newAnimation) {
  26836. this.animations.push(newAnimation);
  26837. };
  26838. /**
  26839. * Adds the given animation group to this scene.
  26840. * @param newAnimationGroup The animation group to add
  26841. */
  26842. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26843. this.animationGroups.push(newAnimationGroup);
  26844. };
  26845. /**
  26846. * Adds the given multi-material to this scene
  26847. * @param newMultiMaterial The multi-material to add
  26848. */
  26849. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26850. this.multiMaterials.push(newMultiMaterial);
  26851. };
  26852. /**
  26853. * Adds the given material to this scene
  26854. * @param newMaterial The material to add
  26855. */
  26856. Scene.prototype.addMaterial = function (newMaterial) {
  26857. this.materials.push(newMaterial);
  26858. };
  26859. /**
  26860. * Adds the given morph target to this scene
  26861. * @param newMorphTargetManager The morph target to add
  26862. */
  26863. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26864. this.morphTargetManagers.push(newMorphTargetManager);
  26865. };
  26866. /**
  26867. * Adds the given geometry to this scene
  26868. * @param newGeometry The geometry to add
  26869. */
  26870. Scene.prototype.addGeometry = function (newGeometry) {
  26871. this._geometries.push(newGeometry);
  26872. };
  26873. /**
  26874. * Adds the given lens flare system to this scene
  26875. * @param newLensFlareSystem The lens flare system to add
  26876. */
  26877. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26878. this.lensFlareSystems.push(newLensFlareSystem);
  26879. };
  26880. /**
  26881. * Adds the given effect layer to this scene
  26882. * @param newEffectLayer defines the effect layer to add
  26883. */
  26884. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26885. this.effectLayers.push(newEffectLayer);
  26886. };
  26887. /**
  26888. * Adds the given action manager to this scene
  26889. * @param newActionManager The action manager to add
  26890. */
  26891. Scene.prototype.addActionManager = function (newActionManager) {
  26892. this._actionManagers.push(newActionManager);
  26893. };
  26894. /**
  26895. * Adds the given texture to this scene.
  26896. * @param newTexture The texture to add
  26897. */
  26898. Scene.prototype.addTexture = function (newTexture) {
  26899. this.textures.push(newTexture);
  26900. };
  26901. /**
  26902. * Switch active camera
  26903. * @param newCamera defines the new active camera
  26904. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26905. */
  26906. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26907. if (attachControl === void 0) { attachControl = true; }
  26908. var canvas = this._engine.getRenderingCanvas();
  26909. if (!canvas) {
  26910. return;
  26911. }
  26912. if (this.activeCamera) {
  26913. this.activeCamera.detachControl(canvas);
  26914. }
  26915. this.activeCamera = newCamera;
  26916. if (attachControl) {
  26917. newCamera.attachControl(canvas);
  26918. }
  26919. };
  26920. /**
  26921. * sets the active camera of the scene using its ID
  26922. * @param id defines the camera's ID
  26923. * @return the new active camera or null if none found.
  26924. */
  26925. Scene.prototype.setActiveCameraByID = function (id) {
  26926. var camera = this.getCameraByID(id);
  26927. if (camera) {
  26928. this.activeCamera = camera;
  26929. return camera;
  26930. }
  26931. return null;
  26932. };
  26933. /**
  26934. * sets the active camera of the scene using its name
  26935. * @param name defines the camera's name
  26936. * @returns the new active camera or null if none found.
  26937. */
  26938. Scene.prototype.setActiveCameraByName = function (name) {
  26939. var camera = this.getCameraByName(name);
  26940. if (camera) {
  26941. this.activeCamera = camera;
  26942. return camera;
  26943. }
  26944. return null;
  26945. };
  26946. /**
  26947. * get an animation group using its name
  26948. * @param name defines the material's name
  26949. * @return the animation group or null if none found.
  26950. */
  26951. Scene.prototype.getAnimationGroupByName = function (name) {
  26952. for (var index = 0; index < this.animationGroups.length; index++) {
  26953. if (this.animationGroups[index].name === name) {
  26954. return this.animationGroups[index];
  26955. }
  26956. }
  26957. return null;
  26958. };
  26959. /**
  26960. * get a material using its id
  26961. * @param id defines the material's ID
  26962. * @return the material or null if none found.
  26963. */
  26964. Scene.prototype.getMaterialByID = function (id) {
  26965. for (var index = 0; index < this.materials.length; index++) {
  26966. if (this.materials[index].id === id) {
  26967. return this.materials[index];
  26968. }
  26969. }
  26970. return null;
  26971. };
  26972. /**
  26973. * Gets a material using its name
  26974. * @param name defines the material's name
  26975. * @return the material or null if none found.
  26976. */
  26977. Scene.prototype.getMaterialByName = function (name) {
  26978. for (var index = 0; index < this.materials.length; index++) {
  26979. if (this.materials[index].name === name) {
  26980. return this.materials[index];
  26981. }
  26982. }
  26983. return null;
  26984. };
  26985. /**
  26986. * Gets a lens flare system using its name
  26987. * @param name defines the name to look for
  26988. * @returns the lens flare system or null if not found
  26989. */
  26990. Scene.prototype.getLensFlareSystemByName = function (name) {
  26991. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26992. if (this.lensFlareSystems[index].name === name) {
  26993. return this.lensFlareSystems[index];
  26994. }
  26995. }
  26996. return null;
  26997. };
  26998. /**
  26999. * Gets a lens flare system using its id
  27000. * @param id defines the id to look for
  27001. * @returns the lens flare system or null if not found
  27002. */
  27003. Scene.prototype.getLensFlareSystemByID = function (id) {
  27004. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  27005. if (this.lensFlareSystems[index].id === id) {
  27006. return this.lensFlareSystems[index];
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a camera using its id
  27013. * @param id defines the id to look for
  27014. * @returns the camera or null if not found
  27015. */
  27016. Scene.prototype.getCameraByID = function (id) {
  27017. for (var index = 0; index < this.cameras.length; index++) {
  27018. if (this.cameras[index].id === id) {
  27019. return this.cameras[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a camera using its unique id
  27026. * @param uniqueId defines the unique id to look for
  27027. * @returns the camera or null if not found
  27028. */
  27029. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27030. for (var index = 0; index < this.cameras.length; index++) {
  27031. if (this.cameras[index].uniqueId === uniqueId) {
  27032. return this.cameras[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a camera using its name
  27039. * @param name defines the camera's name
  27040. * @return the camera or null if none found.
  27041. */
  27042. Scene.prototype.getCameraByName = function (name) {
  27043. for (var index = 0; index < this.cameras.length; index++) {
  27044. if (this.cameras[index].name === name) {
  27045. return this.cameras[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a bone using its id
  27052. * @param id defines the bone's id
  27053. * @return the bone or null if not found
  27054. */
  27055. Scene.prototype.getBoneByID = function (id) {
  27056. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27057. var skeleton = this.skeletons[skeletonIndex];
  27058. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27059. if (skeleton.bones[boneIndex].id === id) {
  27060. return skeleton.bones[boneIndex];
  27061. }
  27062. }
  27063. }
  27064. return null;
  27065. };
  27066. /**
  27067. * Gets a bone using its id
  27068. * @param name defines the bone's name
  27069. * @return the bone or null if not found
  27070. */
  27071. Scene.prototype.getBoneByName = function (name) {
  27072. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27073. var skeleton = this.skeletons[skeletonIndex];
  27074. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27075. if (skeleton.bones[boneIndex].name === name) {
  27076. return skeleton.bones[boneIndex];
  27077. }
  27078. }
  27079. }
  27080. return null;
  27081. };
  27082. /**
  27083. * Gets a light node using its name
  27084. * @param name defines the the light's name
  27085. * @return the light or null if none found.
  27086. */
  27087. Scene.prototype.getLightByName = function (name) {
  27088. for (var index = 0; index < this.lights.length; index++) {
  27089. if (this.lights[index].name === name) {
  27090. return this.lights[index];
  27091. }
  27092. }
  27093. return null;
  27094. };
  27095. /**
  27096. * Gets a light node using its id
  27097. * @param id defines the light's id
  27098. * @return the light or null if none found.
  27099. */
  27100. Scene.prototype.getLightByID = function (id) {
  27101. for (var index = 0; index < this.lights.length; index++) {
  27102. if (this.lights[index].id === id) {
  27103. return this.lights[index];
  27104. }
  27105. }
  27106. return null;
  27107. };
  27108. /**
  27109. * Gets a light node using its scene-generated unique ID
  27110. * @param uniqueId defines the light's unique id
  27111. * @return the light or null if none found.
  27112. */
  27113. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27114. for (var index = 0; index < this.lights.length; index++) {
  27115. if (this.lights[index].uniqueId === uniqueId) {
  27116. return this.lights[index];
  27117. }
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * Gets a particle system by id
  27123. * @param id defines the particle system id
  27124. * @return the corresponding system or null if none found
  27125. */
  27126. Scene.prototype.getParticleSystemByID = function (id) {
  27127. for (var index = 0; index < this.particleSystems.length; index++) {
  27128. if (this.particleSystems[index].id === id) {
  27129. return this.particleSystems[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a geometry using its ID
  27136. * @param id defines the geometry's id
  27137. * @return the geometry or null if none found.
  27138. */
  27139. Scene.prototype.getGeometryByID = function (id) {
  27140. for (var index = 0; index < this._geometries.length; index++) {
  27141. if (this._geometries[index].id === id) {
  27142. return this._geometries[index];
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Add a new geometry to this scene
  27149. * @param geometry defines the geometry to be added to the scene.
  27150. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27151. * @return a boolean defining if the geometry was added or not
  27152. */
  27153. Scene.prototype.pushGeometry = function (geometry, force) {
  27154. if (!force && this.getGeometryByID(geometry.id)) {
  27155. return false;
  27156. }
  27157. this._geometries.push(geometry);
  27158. //notify the collision coordinator
  27159. if (this.collisionCoordinator) {
  27160. this.collisionCoordinator.onGeometryAdded(geometry);
  27161. }
  27162. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27163. return true;
  27164. };
  27165. /**
  27166. * Removes an existing geometry
  27167. * @param geometry defines the geometry to be removed from the scene
  27168. * @return a boolean defining if the geometry was removed or not
  27169. */
  27170. Scene.prototype.removeGeometry = function (geometry) {
  27171. var index = this._geometries.indexOf(geometry);
  27172. if (index > -1) {
  27173. this._geometries.splice(index, 1);
  27174. //notify the collision coordinator
  27175. if (this.collisionCoordinator) {
  27176. this.collisionCoordinator.onGeometryDeleted(geometry);
  27177. }
  27178. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27179. return true;
  27180. }
  27181. return false;
  27182. };
  27183. /**
  27184. * Gets the list of geometries attached to the scene
  27185. * @returns an array of Geometry
  27186. */
  27187. Scene.prototype.getGeometries = function () {
  27188. return this._geometries;
  27189. };
  27190. /**
  27191. * Gets the first added mesh found of a given ID
  27192. * @param id defines the id to search for
  27193. * @return the mesh found or null if not found at all
  27194. */
  27195. Scene.prototype.getMeshByID = function (id) {
  27196. for (var index = 0; index < this.meshes.length; index++) {
  27197. if (this.meshes[index].id === id) {
  27198. return this.meshes[index];
  27199. }
  27200. }
  27201. return null;
  27202. };
  27203. /**
  27204. * Gets a list of meshes using their id
  27205. * @param id defines the id to search for
  27206. * @returns a list of meshes
  27207. */
  27208. Scene.prototype.getMeshesByID = function (id) {
  27209. return this.meshes.filter(function (m) {
  27210. return m.id === id;
  27211. });
  27212. };
  27213. /**
  27214. * Gets the first added transform node found of a given ID
  27215. * @param id defines the id to search for
  27216. * @return the found transform node or null if not found at all.
  27217. */
  27218. Scene.prototype.getTransformNodeByID = function (id) {
  27219. for (var index = 0; index < this.transformNodes.length; index++) {
  27220. if (this.transformNodes[index].id === id) {
  27221. return this.transformNodes[index];
  27222. }
  27223. }
  27224. return null;
  27225. };
  27226. /**
  27227. * Gets a list of transform nodes using their id
  27228. * @param id defines the id to search for
  27229. * @returns a list of transform nodes
  27230. */
  27231. Scene.prototype.getTransformNodesByID = function (id) {
  27232. return this.transformNodes.filter(function (m) {
  27233. return m.id === id;
  27234. });
  27235. };
  27236. /**
  27237. * Gets a mesh with its auto-generated unique id
  27238. * @param uniqueId defines the unique id to search for
  27239. * @return the found mesh or null if not found at all.
  27240. */
  27241. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27242. for (var index = 0; index < this.meshes.length; index++) {
  27243. if (this.meshes[index].uniqueId === uniqueId) {
  27244. return this.meshes[index];
  27245. }
  27246. }
  27247. return null;
  27248. };
  27249. /**
  27250. * Gets a the last added mesh using a given id
  27251. * @param id defines the id to search for
  27252. * @return the found mesh or null if not found at all.
  27253. */
  27254. Scene.prototype.getLastMeshByID = function (id) {
  27255. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27256. if (this.meshes[index].id === id) {
  27257. return this.meshes[index];
  27258. }
  27259. }
  27260. return null;
  27261. };
  27262. /**
  27263. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27264. * @param id defines the id to search for
  27265. * @return the found node or null if not found at all
  27266. */
  27267. Scene.prototype.getLastEntryByID = function (id) {
  27268. var index;
  27269. for (index = this.meshes.length - 1; index >= 0; index--) {
  27270. if (this.meshes[index].id === id) {
  27271. return this.meshes[index];
  27272. }
  27273. }
  27274. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27275. if (this.transformNodes[index].id === id) {
  27276. return this.transformNodes[index];
  27277. }
  27278. }
  27279. for (index = this.cameras.length - 1; index >= 0; index--) {
  27280. if (this.cameras[index].id === id) {
  27281. return this.cameras[index];
  27282. }
  27283. }
  27284. for (index = this.lights.length - 1; index >= 0; index--) {
  27285. if (this.lights[index].id === id) {
  27286. return this.lights[index];
  27287. }
  27288. }
  27289. return null;
  27290. };
  27291. /**
  27292. * Gets a node (Mesh, Camera, Light) using a given id
  27293. * @param id defines the id to search for
  27294. * @return the found node or null if not found at all
  27295. */
  27296. Scene.prototype.getNodeByID = function (id) {
  27297. var mesh = this.getMeshByID(id);
  27298. if (mesh) {
  27299. return mesh;
  27300. }
  27301. var light = this.getLightByID(id);
  27302. if (light) {
  27303. return light;
  27304. }
  27305. var camera = this.getCameraByID(id);
  27306. if (camera) {
  27307. return camera;
  27308. }
  27309. var bone = this.getBoneByID(id);
  27310. return bone;
  27311. };
  27312. /**
  27313. * Gets a node (Mesh, Camera, Light) using a given name
  27314. * @param name defines the name to search for
  27315. * @return the found node or null if not found at all.
  27316. */
  27317. Scene.prototype.getNodeByName = function (name) {
  27318. var mesh = this.getMeshByName(name);
  27319. if (mesh) {
  27320. return mesh;
  27321. }
  27322. var light = this.getLightByName(name);
  27323. if (light) {
  27324. return light;
  27325. }
  27326. var camera = this.getCameraByName(name);
  27327. if (camera) {
  27328. return camera;
  27329. }
  27330. var bone = this.getBoneByName(name);
  27331. return bone;
  27332. };
  27333. /**
  27334. * Gets a mesh using a given name
  27335. * @param name defines the name to search for
  27336. * @return the found mesh or null if not found at all.
  27337. */
  27338. Scene.prototype.getMeshByName = function (name) {
  27339. for (var index = 0; index < this.meshes.length; index++) {
  27340. if (this.meshes[index].name === name) {
  27341. return this.meshes[index];
  27342. }
  27343. }
  27344. return null;
  27345. };
  27346. /**
  27347. * Gets a transform node using a given name
  27348. * @param name defines the name to search for
  27349. * @return the found transform node or null if not found at all.
  27350. */
  27351. Scene.prototype.getTransformNodeByName = function (name) {
  27352. for (var index = 0; index < this.transformNodes.length; index++) {
  27353. if (this.transformNodes[index].name === name) {
  27354. return this.transformNodes[index];
  27355. }
  27356. }
  27357. return null;
  27358. };
  27359. /**
  27360. * Gets a sound using a given name
  27361. * @param name defines the name to search for
  27362. * @return the found sound or null if not found at all.
  27363. */
  27364. Scene.prototype.getSoundByName = function (name) {
  27365. var index;
  27366. if (BABYLON.AudioEngine) {
  27367. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27368. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27369. return this.mainSoundTrack.soundCollection[index];
  27370. }
  27371. }
  27372. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27373. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27374. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27375. return this.soundTracks[sdIndex].soundCollection[index];
  27376. }
  27377. }
  27378. }
  27379. }
  27380. return null;
  27381. };
  27382. /**
  27383. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27384. * @param id defines the id to search for
  27385. * @return the found skeleton or null if not found at all.
  27386. */
  27387. Scene.prototype.getLastSkeletonByID = function (id) {
  27388. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27389. if (this.skeletons[index].id === id) {
  27390. return this.skeletons[index];
  27391. }
  27392. }
  27393. return null;
  27394. };
  27395. /**
  27396. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27397. * @param id defines the id to search for
  27398. * @return the found skeleton or null if not found at all.
  27399. */
  27400. Scene.prototype.getSkeletonById = function (id) {
  27401. for (var index = 0; index < this.skeletons.length; index++) {
  27402. if (this.skeletons[index].id === id) {
  27403. return this.skeletons[index];
  27404. }
  27405. }
  27406. return null;
  27407. };
  27408. /**
  27409. * Gets a skeleton using a given name
  27410. * @param name defines the name to search for
  27411. * @return the found skeleton or null if not found at all.
  27412. */
  27413. Scene.prototype.getSkeletonByName = function (name) {
  27414. for (var index = 0; index < this.skeletons.length; index++) {
  27415. if (this.skeletons[index].name === name) {
  27416. return this.skeletons[index];
  27417. }
  27418. }
  27419. return null;
  27420. };
  27421. /**
  27422. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27423. * @param id defines the id to search for
  27424. * @return the found morph target manager or null if not found at all.
  27425. */
  27426. Scene.prototype.getMorphTargetManagerById = function (id) {
  27427. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27428. if (this.morphTargetManagers[index].uniqueId === id) {
  27429. return this.morphTargetManagers[index];
  27430. }
  27431. }
  27432. return null;
  27433. };
  27434. /**
  27435. * Gets a boolean indicating if the given mesh is active
  27436. * @param mesh defines the mesh to look for
  27437. * @returns true if the mesh is in the active list
  27438. */
  27439. Scene.prototype.isActiveMesh = function (mesh) {
  27440. return (this._activeMeshes.indexOf(mesh) !== -1);
  27441. };
  27442. /**
  27443. * Return a the first highlight layer of the scene with a given name.
  27444. * @param name The name of the highlight layer to look for.
  27445. * @return The highlight layer if found otherwise null.
  27446. */
  27447. Scene.prototype.getHighlightLayerByName = function (name) {
  27448. for (var index = 0; index < this.effectLayers.length; index++) {
  27449. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27450. return this.effectLayers[index];
  27451. }
  27452. }
  27453. return null;
  27454. };
  27455. /**
  27456. * Return a the first highlight layer of the scene with a given name.
  27457. * @param name The name of the highlight layer to look for.
  27458. * @return The highlight layer if found otherwise null.
  27459. */
  27460. Scene.prototype.getGlowLayerByName = function (name) {
  27461. for (var index = 0; index < this.effectLayers.length; index++) {
  27462. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27463. return this.effectLayers[index];
  27464. }
  27465. }
  27466. return null;
  27467. };
  27468. Object.defineProperty(Scene.prototype, "uid", {
  27469. /**
  27470. * Return a unique id as a string which can serve as an identifier for the scene
  27471. */
  27472. get: function () {
  27473. if (!this._uid) {
  27474. this._uid = BABYLON.Tools.RandomId();
  27475. }
  27476. return this._uid;
  27477. },
  27478. enumerable: true,
  27479. configurable: true
  27480. });
  27481. /**
  27482. * Add an externaly attached data from its key.
  27483. * This method call will fail and return false, if such key already exists.
  27484. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27485. * @param key the unique key that identifies the data
  27486. * @param data the data object to associate to the key for this Engine instance
  27487. * @return true if no such key were already present and the data was added successfully, false otherwise
  27488. */
  27489. Scene.prototype.addExternalData = function (key, data) {
  27490. if (!this._externalData) {
  27491. this._externalData = new BABYLON.StringDictionary();
  27492. }
  27493. return this._externalData.add(key, data);
  27494. };
  27495. /**
  27496. * Get an externaly attached data from its key
  27497. * @param key the unique key that identifies the data
  27498. * @return the associated data, if present (can be null), or undefined if not present
  27499. */
  27500. Scene.prototype.getExternalData = function (key) {
  27501. if (!this._externalData) {
  27502. return null;
  27503. }
  27504. return this._externalData.get(key);
  27505. };
  27506. /**
  27507. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27508. * @param key the unique key that identifies the data
  27509. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27510. * @return the associated data, can be null if the factory returned null.
  27511. */
  27512. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27513. if (!this._externalData) {
  27514. this._externalData = new BABYLON.StringDictionary();
  27515. }
  27516. return this._externalData.getOrAddWithFactory(key, factory);
  27517. };
  27518. /**
  27519. * Remove an externaly attached data from the Engine instance
  27520. * @param key the unique key that identifies the data
  27521. * @return true if the data was successfully removed, false if it doesn't exist
  27522. */
  27523. Scene.prototype.removeExternalData = function (key) {
  27524. return this._externalData.remove(key);
  27525. };
  27526. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27527. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27528. if (mesh.showSubMeshesBoundingBox) {
  27529. var boundingInfo = subMesh.getBoundingInfo();
  27530. if (boundingInfo !== null && boundingInfo !== undefined) {
  27531. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27532. }
  27533. }
  27534. var material = subMesh.getMaterial();
  27535. if (material !== null && material !== undefined) {
  27536. // Render targets
  27537. if (material.getRenderTargetTextures !== undefined) {
  27538. if (this._processedMaterials.indexOf(material) === -1) {
  27539. this._processedMaterials.push(material);
  27540. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27541. }
  27542. }
  27543. // Dispatch
  27544. this._activeIndices.addCount(subMesh.indexCount, false);
  27545. this._renderingManager.dispatch(subMesh, mesh, material);
  27546. }
  27547. }
  27548. };
  27549. /**
  27550. * Clear the processed materials smart array preventing retention point in material dispose.
  27551. */
  27552. Scene.prototype.freeProcessedMaterials = function () {
  27553. this._processedMaterials.dispose();
  27554. };
  27555. /**
  27556. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27557. */
  27558. Scene.prototype.freeActiveMeshes = function () {
  27559. this._activeMeshes.dispose();
  27560. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27561. this.activeCamera._activeMeshes.dispose();
  27562. }
  27563. if (this.activeCameras) {
  27564. for (var i = 0; i < this.activeCameras.length; i++) {
  27565. var activeCamera = this.activeCameras[i];
  27566. if (activeCamera && activeCamera._activeMeshes) {
  27567. activeCamera._activeMeshes.dispose();
  27568. }
  27569. }
  27570. }
  27571. };
  27572. /**
  27573. * Clear the info related to rendering groups preventing retention points during dispose.
  27574. */
  27575. Scene.prototype.freeRenderingGroups = function () {
  27576. if (this._renderingManager) {
  27577. this._renderingManager.freeRenderingGroups();
  27578. }
  27579. if (this.textures) {
  27580. for (var i = 0; i < this.textures.length; i++) {
  27581. var texture = this.textures[i];
  27582. if (texture && texture.renderList) {
  27583. texture.freeRenderingGroups();
  27584. }
  27585. }
  27586. }
  27587. };
  27588. /** @hidden */
  27589. Scene.prototype._isInIntermediateRendering = function () {
  27590. return this._intermediateRendering;
  27591. };
  27592. /**
  27593. * Defines the current active mesh candidate provider
  27594. * @param provider defines the provider to use
  27595. */
  27596. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27597. this._activeMeshCandidateProvider = provider;
  27598. };
  27599. /**
  27600. * Gets the current active mesh candidate provider
  27601. * @returns the current active mesh candidate provider
  27602. */
  27603. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27604. return this._activeMeshCandidateProvider;
  27605. };
  27606. /**
  27607. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27608. * @returns the current scene
  27609. */
  27610. Scene.prototype.freezeActiveMeshes = function () {
  27611. if (!this.activeCamera) {
  27612. return this;
  27613. }
  27614. if (!this._frustumPlanes) {
  27615. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27616. }
  27617. this._evaluateActiveMeshes();
  27618. this._activeMeshesFrozen = true;
  27619. return this;
  27620. };
  27621. /**
  27622. * Use this function to restart evaluating active meshes on every frame
  27623. * @returns the current scene
  27624. */
  27625. Scene.prototype.unfreezeActiveMeshes = function () {
  27626. this._activeMeshesFrozen = false;
  27627. return this;
  27628. };
  27629. Scene.prototype._evaluateActiveMeshes = function () {
  27630. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27631. return;
  27632. }
  27633. if (!this.activeCamera) {
  27634. return;
  27635. }
  27636. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27637. this.activeCamera._activeMeshes.reset();
  27638. this._activeMeshes.reset();
  27639. this._renderingManager.reset();
  27640. this._processedMaterials.reset();
  27641. this._activeParticleSystems.reset();
  27642. this._activeSkeletons.reset();
  27643. this._softwareSkinnedMeshes.reset();
  27644. if (this._boundingBoxRenderer) {
  27645. this._boundingBoxRenderer.reset();
  27646. }
  27647. // Meshes
  27648. var meshes;
  27649. var len;
  27650. var checkIsEnabled = true;
  27651. // Determine mesh candidates
  27652. if (this._activeMeshCandidateProvider !== undefined) {
  27653. // Use _activeMeshCandidateProvider
  27654. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27655. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27656. if (meshes !== undefined) {
  27657. len = meshes.length;
  27658. }
  27659. else {
  27660. len = 0;
  27661. }
  27662. }
  27663. else if (this._selectionOctree !== undefined) {
  27664. // Octree
  27665. var selection = this._selectionOctree.select(this._frustumPlanes);
  27666. meshes = selection.data;
  27667. len = selection.length;
  27668. }
  27669. else {
  27670. // Full scene traversal
  27671. len = this.meshes.length;
  27672. meshes = this.meshes;
  27673. }
  27674. // Check each mesh
  27675. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27676. mesh = meshes[meshIndex];
  27677. if (mesh.isBlocked) {
  27678. continue;
  27679. }
  27680. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27681. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27682. continue;
  27683. }
  27684. mesh.computeWorldMatrix();
  27685. // Intersections
  27686. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27687. this._meshesForIntersections.pushNoDuplicate(mesh);
  27688. }
  27689. // Switch to current LOD
  27690. meshLOD = mesh.getLOD(this.activeCamera);
  27691. if (meshLOD === undefined || meshLOD === null) {
  27692. continue;
  27693. }
  27694. mesh._preActivate();
  27695. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27696. this._activeMeshes.push(mesh);
  27697. this.activeCamera._activeMeshes.push(mesh);
  27698. mesh._activate(this._renderId);
  27699. if (meshLOD !== mesh) {
  27700. meshLOD._activate(this._renderId);
  27701. }
  27702. this._activeMesh(mesh, meshLOD);
  27703. }
  27704. }
  27705. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27706. // Particle systems
  27707. if (this.particlesEnabled) {
  27708. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27709. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27710. var particleSystem = this.particleSystems[particleIndex];
  27711. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27712. continue;
  27713. }
  27714. var emitter = particleSystem.emitter;
  27715. if (!emitter.position || emitter.isEnabled()) {
  27716. this._activeParticleSystems.push(particleSystem);
  27717. particleSystem.animate();
  27718. this._renderingManager.dispatchParticles(particleSystem);
  27719. }
  27720. }
  27721. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27722. }
  27723. };
  27724. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27725. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27726. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27727. mesh.skeleton.prepare();
  27728. }
  27729. if (!mesh.computeBonesUsingShaders) {
  27730. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27731. }
  27732. }
  27733. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27734. var boundingInfo = sourceMesh.getBoundingInfo();
  27735. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27736. }
  27737. if (mesh !== undefined && mesh !== null
  27738. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27739. // Submeshes Octrees
  27740. var len;
  27741. var subMeshes;
  27742. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27743. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27744. len = intersections.length;
  27745. subMeshes = intersections.data;
  27746. }
  27747. else {
  27748. subMeshes = mesh.subMeshes;
  27749. len = subMeshes.length;
  27750. }
  27751. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27752. subMesh = subMeshes[subIndex];
  27753. this._evaluateSubMesh(subMesh, mesh);
  27754. }
  27755. }
  27756. };
  27757. /**
  27758. * Update the transform matrix to update from the current active camera
  27759. * @param force defines a boolean used to force the update even if cache is up to date
  27760. */
  27761. Scene.prototype.updateTransformMatrix = function (force) {
  27762. if (!this.activeCamera) {
  27763. return;
  27764. }
  27765. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27766. };
  27767. /**
  27768. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27769. * @param alternateCamera defines the camera to use
  27770. */
  27771. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27772. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27773. };
  27774. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27775. if (camera && camera._skipRendering) {
  27776. return;
  27777. }
  27778. var engine = this._engine;
  27779. this.activeCamera = camera;
  27780. if (!this.activeCamera)
  27781. throw new Error("Active camera not set");
  27782. // Viewport
  27783. engine.setViewport(this.activeCamera.viewport);
  27784. // Camera
  27785. this.resetCachedMaterial();
  27786. this._renderId++;
  27787. this.updateTransformMatrix();
  27788. if (camera._alternateCamera) {
  27789. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27790. this._alternateRendering = true;
  27791. }
  27792. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27793. // Meshes
  27794. this._evaluateActiveMeshes();
  27795. // Software skinning
  27796. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27797. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27798. mesh.applySkeleton(mesh.skeleton);
  27799. }
  27800. // Render targets
  27801. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27802. var needsRestoreFrameBuffer = false;
  27803. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27804. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27805. }
  27806. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27807. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27808. }
  27809. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27810. this._intermediateRendering = true;
  27811. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27812. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27813. var renderTarget = this._renderTargets.data[renderIndex];
  27814. if (renderTarget._shouldRender()) {
  27815. this._renderId++;
  27816. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27817. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27818. }
  27819. }
  27820. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27821. this._intermediateRendering = false;
  27822. this._renderId++;
  27823. needsRestoreFrameBuffer = true; // Restore back buffer
  27824. }
  27825. // Render EffectLayer Texture
  27826. var stencilState = this._engine.getStencilBuffer();
  27827. var renderEffects = false;
  27828. var needStencil = false;
  27829. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27830. this._intermediateRendering = true;
  27831. for (var i = 0; i < this.effectLayers.length; i++) {
  27832. var effectLayer = this.effectLayers[i];
  27833. if (effectLayer.shouldRender() &&
  27834. (!effectLayer.camera ||
  27835. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27836. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27837. renderEffects = true;
  27838. needStencil = needStencil || effectLayer.needStencil();
  27839. var renderTarget = effectLayer._mainTexture;
  27840. if (renderTarget._shouldRender()) {
  27841. this._renderId++;
  27842. renderTarget.render(false, false);
  27843. needsRestoreFrameBuffer = true;
  27844. }
  27845. }
  27846. }
  27847. this._intermediateRendering = false;
  27848. this._renderId++;
  27849. }
  27850. if (needsRestoreFrameBuffer) {
  27851. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27852. }
  27853. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27854. // Prepare Frame
  27855. if (this.postProcessManager) {
  27856. this.postProcessManager._prepareFrame();
  27857. }
  27858. // Backgrounds
  27859. var layerIndex;
  27860. var layer;
  27861. if (this.layers.length) {
  27862. engine.setDepthBuffer(false);
  27863. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27864. layer = this.layers[layerIndex];
  27865. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27866. layer.render();
  27867. }
  27868. }
  27869. engine.setDepthBuffer(true);
  27870. }
  27871. // Activate effect Layer stencil
  27872. if (needStencil) {
  27873. this._engine.setStencilBuffer(true);
  27874. }
  27875. // Render
  27876. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27877. this._renderingManager.render(null, null, true, true);
  27878. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27879. // Restore effect Layer stencil
  27880. if (needStencil) {
  27881. this._engine.setStencilBuffer(stencilState);
  27882. }
  27883. // Bounding boxes
  27884. if (this._boundingBoxRenderer) {
  27885. this._boundingBoxRenderer.render();
  27886. }
  27887. // Lens flares
  27888. if (this.lensFlaresEnabled) {
  27889. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27890. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27891. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27892. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27893. lensFlareSystem.render();
  27894. }
  27895. }
  27896. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27897. }
  27898. // Effect Layer
  27899. if (renderEffects) {
  27900. engine.setDepthBuffer(false);
  27901. for (var i = 0; i < this.effectLayers.length; i++) {
  27902. if (this.effectLayers[i].shouldRender()) {
  27903. this.effectLayers[i].render();
  27904. }
  27905. }
  27906. engine.setDepthBuffer(true);
  27907. }
  27908. // Foregrounds
  27909. if (this.layers.length) {
  27910. engine.setDepthBuffer(false);
  27911. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27912. layer = this.layers[layerIndex];
  27913. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27914. layer.render();
  27915. }
  27916. }
  27917. engine.setDepthBuffer(true);
  27918. }
  27919. // Finalize frame
  27920. if (this.postProcessManager) {
  27921. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27922. }
  27923. // Reset some special arrays
  27924. this._renderTargets.reset();
  27925. this._alternateRendering = false;
  27926. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27927. };
  27928. Scene.prototype._processSubCameras = function (camera) {
  27929. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27930. this._renderForCamera(camera);
  27931. return;
  27932. }
  27933. // rig cameras
  27934. for (var index = 0; index < camera._rigCameras.length; index++) {
  27935. this._renderForCamera(camera._rigCameras[index], camera);
  27936. }
  27937. this.activeCamera = camera;
  27938. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27939. };
  27940. Scene.prototype._checkIntersections = function () {
  27941. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27942. var sourceMesh = this._meshesForIntersections.data[index];
  27943. if (!sourceMesh.actionManager) {
  27944. continue;
  27945. }
  27946. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27947. var action = sourceMesh.actionManager.actions[actionIndex];
  27948. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27949. var parameters = action.getTriggerParameter();
  27950. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27951. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27952. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27953. if (areIntersecting && currentIntersectionInProgress === -1) {
  27954. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27955. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27956. sourceMesh._intersectionsInProgress.push(otherMesh);
  27957. }
  27958. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27959. sourceMesh._intersectionsInProgress.push(otherMesh);
  27960. }
  27961. }
  27962. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27963. //They intersected, and now they don't.
  27964. //is this trigger an exit trigger? execute an event.
  27965. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27966. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27967. }
  27968. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27969. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27970. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27971. return otherMesh === parameterMesh;
  27972. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27973. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27974. }
  27975. }
  27976. }
  27977. }
  27978. }
  27979. };
  27980. /**
  27981. * Render the scene
  27982. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27983. */
  27984. Scene.prototype.render = function (updateCameras) {
  27985. if (updateCameras === void 0) { updateCameras = true; }
  27986. if (this.isDisposed) {
  27987. return;
  27988. }
  27989. this._activeParticles.fetchNewFrame();
  27990. this._totalVertices.fetchNewFrame();
  27991. this._activeIndices.fetchNewFrame();
  27992. this._activeBones.fetchNewFrame();
  27993. this._meshesForIntersections.reset();
  27994. this.resetCachedMaterial();
  27995. this.onBeforeAnimationsObservable.notifyObservers(this);
  27996. // Actions
  27997. if (this.actionManager) {
  27998. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27999. }
  28000. //Simplification Queue
  28001. if (this.simplificationQueue && !this.simplificationQueue.running) {
  28002. this.simplificationQueue.executeNext();
  28003. }
  28004. if (this._engine.isDeterministicLockStep()) {
  28005. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28006. var defaultFPS = (60.0 / 1000.0);
  28007. var defaultFrameTime = 1000 / 60; // frame time in MS
  28008. if (this._physicsEngine) {
  28009. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  28010. }
  28011. var stepsTaken = 0;
  28012. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28013. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28014. internalSteps = Math.min(internalSteps, maxSubSteps);
  28015. do {
  28016. this.onBeforeStepObservable.notifyObservers(this);
  28017. // Animations
  28018. this._animationRatio = defaultFrameTime * defaultFPS;
  28019. this._animate();
  28020. this.onAfterAnimationsObservable.notifyObservers(this);
  28021. // Physics
  28022. if (this._physicsEngine) {
  28023. this.onBeforePhysicsObservable.notifyObservers(this);
  28024. this._physicsEngine._step(defaultFrameTime / 1000);
  28025. this.onAfterPhysicsObservable.notifyObservers(this);
  28026. }
  28027. this.onAfterStepObservable.notifyObservers(this);
  28028. this._currentStepId++;
  28029. stepsTaken++;
  28030. deltaTime -= defaultFrameTime;
  28031. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28032. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28033. }
  28034. else {
  28035. // Animations
  28036. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28037. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28038. this._animate();
  28039. this.onAfterAnimationsObservable.notifyObservers(this);
  28040. // Physics
  28041. if (this._physicsEngine) {
  28042. this.onBeforePhysicsObservable.notifyObservers(this);
  28043. this._physicsEngine._step(deltaTime / 1000.0);
  28044. this.onAfterPhysicsObservable.notifyObservers(this);
  28045. }
  28046. }
  28047. // update gamepad manager
  28048. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28049. this._gamepadManager._checkGamepadsStatus();
  28050. }
  28051. // Update Cameras
  28052. if (updateCameras) {
  28053. if (this.activeCameras.length > 0) {
  28054. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28055. var camera = this.activeCameras[cameraIndex];
  28056. camera.update();
  28057. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28058. // rig cameras
  28059. for (var index = 0; index < camera._rigCameras.length; index++) {
  28060. camera._rigCameras[index].update();
  28061. }
  28062. }
  28063. }
  28064. }
  28065. else if (this.activeCamera) {
  28066. this.activeCamera.update();
  28067. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28068. // rig cameras
  28069. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28070. this.activeCamera._rigCameras[index].update();
  28071. }
  28072. }
  28073. }
  28074. }
  28075. // Before render
  28076. this.onBeforeRenderObservable.notifyObservers(this);
  28077. // Customs render targets
  28078. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28079. var engine = this.getEngine();
  28080. var currentActiveCamera = this.activeCamera;
  28081. if (this.renderTargetsEnabled) {
  28082. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28083. this._intermediateRendering = true;
  28084. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28085. var renderTarget = this.customRenderTargets[customIndex];
  28086. if (renderTarget._shouldRender()) {
  28087. this._renderId++;
  28088. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28089. if (!this.activeCamera)
  28090. throw new Error("Active camera not set");
  28091. // Viewport
  28092. engine.setViewport(this.activeCamera.viewport);
  28093. // Camera
  28094. this.updateTransformMatrix();
  28095. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28096. }
  28097. }
  28098. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28099. this._intermediateRendering = false;
  28100. this._renderId++;
  28101. }
  28102. // Restore back buffer
  28103. if (this.customRenderTargets.length > 0) {
  28104. engine.restoreDefaultFramebuffer();
  28105. }
  28106. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28107. this.activeCamera = currentActiveCamera;
  28108. // Procedural textures
  28109. if (this.proceduralTexturesEnabled) {
  28110. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28111. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28112. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28113. if (proceduralTexture._shouldRender()) {
  28114. proceduralTexture.render();
  28115. }
  28116. }
  28117. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28118. }
  28119. // Clear
  28120. if (this.autoClearDepthAndStencil || this.autoClear) {
  28121. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28122. }
  28123. // Shadows
  28124. if (this.shadowsEnabled) {
  28125. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28126. var light = this.lights[lightIndex];
  28127. var shadowGenerator = light.getShadowGenerator();
  28128. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28129. var shadowMap = (shadowGenerator.getShadowMap());
  28130. if (this.textures.indexOf(shadowMap) !== -1) {
  28131. this._renderTargets.push(shadowMap);
  28132. }
  28133. }
  28134. }
  28135. }
  28136. // Depth renderer
  28137. for (var key in this._depthRenderer) {
  28138. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28139. }
  28140. // Geometry renderer
  28141. if (this._geometryBufferRenderer) {
  28142. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28143. }
  28144. // RenderPipeline
  28145. if (this._postProcessRenderPipelineManager) {
  28146. this._postProcessRenderPipelineManager.update();
  28147. }
  28148. // Multi-cameras?
  28149. if (this.activeCameras.length > 0) {
  28150. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28151. if (cameraIndex > 0) {
  28152. this._engine.clear(null, false, true, true);
  28153. }
  28154. this._processSubCameras(this.activeCameras[cameraIndex]);
  28155. }
  28156. }
  28157. else {
  28158. if (!this.activeCamera) {
  28159. throw new Error("No camera defined");
  28160. }
  28161. this._processSubCameras(this.activeCamera);
  28162. }
  28163. // Intersection checks
  28164. this._checkIntersections();
  28165. // Update the audio listener attached to the camera
  28166. if (BABYLON.AudioEngine) {
  28167. this._updateAudioParameters();
  28168. }
  28169. // After render
  28170. if (this.afterRender) {
  28171. this.afterRender();
  28172. }
  28173. this.onAfterRenderObservable.notifyObservers(this);
  28174. // Cleaning
  28175. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28176. var data = this._toBeDisposed.data[index];
  28177. if (data) {
  28178. data.dispose();
  28179. }
  28180. this._toBeDisposed[index] = null;
  28181. }
  28182. this._toBeDisposed.reset();
  28183. if (this.dumpNextRenderTargets) {
  28184. this.dumpNextRenderTargets = false;
  28185. }
  28186. this._activeBones.addCount(0, true);
  28187. this._activeIndices.addCount(0, true);
  28188. this._activeParticles.addCount(0, true);
  28189. };
  28190. Scene.prototype._updateAudioParameters = function () {
  28191. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28192. return;
  28193. }
  28194. var listeningCamera;
  28195. var audioEngine = BABYLON.Engine.audioEngine;
  28196. if (this.activeCameras.length > 0) {
  28197. listeningCamera = this.activeCameras[0];
  28198. }
  28199. else {
  28200. listeningCamera = this.activeCamera;
  28201. }
  28202. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28203. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28204. // for VR cameras
  28205. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28206. listeningCamera = listeningCamera.rigCameras[0];
  28207. }
  28208. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28209. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28210. cameraDirection.normalize();
  28211. // To avoid some errors on GearVR
  28212. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28213. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28214. }
  28215. var i;
  28216. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28217. var sound = this.mainSoundTrack.soundCollection[i];
  28218. if (sound.useCustomAttenuation) {
  28219. sound.updateDistanceFromListener();
  28220. }
  28221. }
  28222. for (i = 0; i < this.soundTracks.length; i++) {
  28223. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28224. sound = this.soundTracks[i].soundCollection[j];
  28225. if (sound.useCustomAttenuation) {
  28226. sound.updateDistanceFromListener();
  28227. }
  28228. }
  28229. }
  28230. }
  28231. };
  28232. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28233. // Audio
  28234. /**
  28235. * Gets or sets if audio support is enabled
  28236. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28237. */
  28238. get: function () {
  28239. return this._audioEnabled;
  28240. },
  28241. set: function (value) {
  28242. this._audioEnabled = value;
  28243. if (BABYLON.AudioEngine) {
  28244. if (this._audioEnabled) {
  28245. this._enableAudio();
  28246. }
  28247. else {
  28248. this._disableAudio();
  28249. }
  28250. }
  28251. },
  28252. enumerable: true,
  28253. configurable: true
  28254. });
  28255. Scene.prototype._disableAudio = function () {
  28256. var i;
  28257. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28258. this.mainSoundTrack.soundCollection[i].pause();
  28259. }
  28260. for (i = 0; i < this.soundTracks.length; i++) {
  28261. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28262. this.soundTracks[i].soundCollection[j].pause();
  28263. }
  28264. }
  28265. };
  28266. Scene.prototype._enableAudio = function () {
  28267. var i;
  28268. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28269. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28270. this.mainSoundTrack.soundCollection[i].play();
  28271. }
  28272. }
  28273. for (i = 0; i < this.soundTracks.length; i++) {
  28274. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28275. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28276. this.soundTracks[i].soundCollection[j].play();
  28277. }
  28278. }
  28279. }
  28280. };
  28281. Object.defineProperty(Scene.prototype, "headphone", {
  28282. /**
  28283. * Gets or sets if audio will be output to headphones
  28284. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28285. */
  28286. get: function () {
  28287. return this._headphone;
  28288. },
  28289. set: function (value) {
  28290. this._headphone = value;
  28291. if (BABYLON.AudioEngine) {
  28292. if (this._headphone) {
  28293. this._switchAudioModeForHeadphones();
  28294. }
  28295. else {
  28296. this._switchAudioModeForNormalSpeakers();
  28297. }
  28298. }
  28299. },
  28300. enumerable: true,
  28301. configurable: true
  28302. });
  28303. Scene.prototype._switchAudioModeForHeadphones = function () {
  28304. this.mainSoundTrack.switchPanningModelToHRTF();
  28305. for (var i = 0; i < this.soundTracks.length; i++) {
  28306. this.soundTracks[i].switchPanningModelToHRTF();
  28307. }
  28308. };
  28309. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28310. this.mainSoundTrack.switchPanningModelToEqualPower();
  28311. for (var i = 0; i < this.soundTracks.length; i++) {
  28312. this.soundTracks[i].switchPanningModelToEqualPower();
  28313. }
  28314. };
  28315. /**
  28316. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28317. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28318. * @returns the created depth renderer
  28319. */
  28320. Scene.prototype.enableDepthRenderer = function (camera) {
  28321. camera = camera || this.activeCamera;
  28322. if (!camera) {
  28323. throw "No camera available to enable depth renderer";
  28324. }
  28325. if (!this._depthRenderer[camera.id]) {
  28326. var textureType = 0;
  28327. if (this._engine.getCaps().textureHalfFloatRender) {
  28328. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28329. }
  28330. else if (this._engine.getCaps().textureFloatRender) {
  28331. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28332. }
  28333. else {
  28334. throw "Depth renderer does not support int texture type";
  28335. }
  28336. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28337. }
  28338. return this._depthRenderer[camera.id];
  28339. };
  28340. /**
  28341. * Disables a depth renderer for a given camera
  28342. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28343. */
  28344. Scene.prototype.disableDepthRenderer = function (camera) {
  28345. camera = camera || this.activeCamera;
  28346. if (!camera || !this._depthRenderer[camera.id]) {
  28347. return;
  28348. }
  28349. this._depthRenderer[camera.id].dispose();
  28350. delete this._depthRenderer[camera.id];
  28351. };
  28352. /**
  28353. * Enables a GeometryBufferRender and associates it with the scene
  28354. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28355. * @returns the GeometryBufferRenderer
  28356. */
  28357. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28358. if (ratio === void 0) { ratio = 1; }
  28359. if (this._geometryBufferRenderer) {
  28360. return this._geometryBufferRenderer;
  28361. }
  28362. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28363. if (!this._geometryBufferRenderer.isSupported) {
  28364. this._geometryBufferRenderer = null;
  28365. }
  28366. return this._geometryBufferRenderer;
  28367. };
  28368. /**
  28369. * Disables the GeometryBufferRender associated with the scene
  28370. */
  28371. Scene.prototype.disableGeometryBufferRenderer = function () {
  28372. if (!this._geometryBufferRenderer) {
  28373. return;
  28374. }
  28375. this._geometryBufferRenderer.dispose();
  28376. this._geometryBufferRenderer = null;
  28377. };
  28378. /**
  28379. * Freeze all materials
  28380. * A frozen material will not be updatable but should be faster to render
  28381. */
  28382. Scene.prototype.freezeMaterials = function () {
  28383. for (var i = 0; i < this.materials.length; i++) {
  28384. this.materials[i].freeze();
  28385. }
  28386. };
  28387. /**
  28388. * Unfreeze all materials
  28389. * A frozen material will not be updatable but should be faster to render
  28390. */
  28391. Scene.prototype.unfreezeMaterials = function () {
  28392. for (var i = 0; i < this.materials.length; i++) {
  28393. this.materials[i].unfreeze();
  28394. }
  28395. };
  28396. /**
  28397. * Releases all held ressources
  28398. */
  28399. Scene.prototype.dispose = function () {
  28400. this.beforeRender = null;
  28401. this.afterRender = null;
  28402. this.skeletons = [];
  28403. this.morphTargetManagers = [];
  28404. this.importedMeshesFiles = new Array();
  28405. this.stopAllAnimations();
  28406. this.resetCachedMaterial();
  28407. for (var key in this._depthRenderer) {
  28408. this._depthRenderer[key].dispose();
  28409. }
  28410. if (this._gamepadManager) {
  28411. this._gamepadManager.dispose();
  28412. this._gamepadManager = null;
  28413. }
  28414. // Smart arrays
  28415. if (this.activeCamera) {
  28416. this.activeCamera._activeMeshes.dispose();
  28417. this.activeCamera = null;
  28418. }
  28419. this._activeMeshes.dispose();
  28420. this._renderingManager.dispose();
  28421. this._processedMaterials.dispose();
  28422. this._activeParticleSystems.dispose();
  28423. this._activeSkeletons.dispose();
  28424. this._softwareSkinnedMeshes.dispose();
  28425. this._renderTargets.dispose();
  28426. this._registeredForLateAnimationBindings.dispose();
  28427. if (this._boundingBoxRenderer) {
  28428. this._boundingBoxRenderer.dispose();
  28429. }
  28430. this._meshesForIntersections.dispose();
  28431. this._toBeDisposed.dispose();
  28432. // Abort active requests
  28433. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28434. var request = _a[_i];
  28435. request.abort();
  28436. }
  28437. // Debug layer
  28438. if (this._debugLayer) {
  28439. this._debugLayer.hide();
  28440. }
  28441. // Events
  28442. this.onDisposeObservable.notifyObservers(this);
  28443. this.onDisposeObservable.clear();
  28444. this.onBeforeRenderObservable.clear();
  28445. this.onAfterRenderObservable.clear();
  28446. this.onBeforeRenderTargetsRenderObservable.clear();
  28447. this.onAfterRenderTargetsRenderObservable.clear();
  28448. this.onAfterStepObservable.clear();
  28449. this.onBeforeStepObservable.clear();
  28450. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28451. this.onAfterActiveMeshesEvaluationObservable.clear();
  28452. this.onBeforeParticlesRenderingObservable.clear();
  28453. this.onAfterParticlesRenderingObservable.clear();
  28454. this.onBeforeSpritesRenderingObservable.clear();
  28455. this.onAfterSpritesRenderingObservable.clear();
  28456. this.onBeforeDrawPhaseObservable.clear();
  28457. this.onAfterDrawPhaseObservable.clear();
  28458. this.onBeforePhysicsObservable.clear();
  28459. this.onAfterPhysicsObservable.clear();
  28460. this.onBeforeAnimationsObservable.clear();
  28461. this.onAfterAnimationsObservable.clear();
  28462. this.onDataLoadedObservable.clear();
  28463. this.detachControl();
  28464. // Release sounds & sounds tracks
  28465. if (BABYLON.AudioEngine) {
  28466. this.disposeSounds();
  28467. }
  28468. // VR Helper
  28469. if (this.VRHelper) {
  28470. this.VRHelper.dispose();
  28471. }
  28472. // Detach cameras
  28473. var canvas = this._engine.getRenderingCanvas();
  28474. if (canvas) {
  28475. var index;
  28476. for (index = 0; index < this.cameras.length; index++) {
  28477. this.cameras[index].detachControl(canvas);
  28478. }
  28479. }
  28480. // Release animation groups
  28481. while (this.animationGroups.length) {
  28482. this.animationGroups[0].dispose();
  28483. }
  28484. // Release lights
  28485. while (this.lights.length) {
  28486. this.lights[0].dispose();
  28487. }
  28488. // Release meshes
  28489. while (this.meshes.length) {
  28490. this.meshes[0].dispose(true);
  28491. }
  28492. while (this.transformNodes.length) {
  28493. this.removeTransformNode(this.transformNodes[0]);
  28494. }
  28495. // Release cameras
  28496. while (this.cameras.length) {
  28497. this.cameras[0].dispose();
  28498. }
  28499. // Release materials
  28500. if (this.defaultMaterial) {
  28501. this.defaultMaterial.dispose();
  28502. }
  28503. while (this.multiMaterials.length) {
  28504. this.multiMaterials[0].dispose();
  28505. }
  28506. while (this.materials.length) {
  28507. this.materials[0].dispose();
  28508. }
  28509. // Release particles
  28510. while (this.particleSystems.length) {
  28511. this.particleSystems[0].dispose();
  28512. }
  28513. // Release sprites
  28514. while (this.spriteManagers.length) {
  28515. this.spriteManagers[0].dispose();
  28516. }
  28517. // Release postProcesses
  28518. while (this.postProcesses.length) {
  28519. this.postProcesses[0].dispose();
  28520. }
  28521. // Release layers
  28522. while (this.layers.length) {
  28523. this.layers[0].dispose();
  28524. }
  28525. while (this.effectLayers.length) {
  28526. this.effectLayers[0].dispose();
  28527. }
  28528. // Release textures
  28529. while (this.textures.length) {
  28530. this.textures[0].dispose();
  28531. }
  28532. // Release UBO
  28533. this._sceneUbo.dispose();
  28534. if (this._alternateSceneUbo) {
  28535. this._alternateSceneUbo.dispose();
  28536. }
  28537. // Post-processes
  28538. this.postProcessManager.dispose();
  28539. if (this._postProcessRenderPipelineManager) {
  28540. this._postProcessRenderPipelineManager.dispose();
  28541. }
  28542. // Physics
  28543. if (this._physicsEngine) {
  28544. this.disablePhysicsEngine();
  28545. }
  28546. // Remove from engine
  28547. index = this._engine.scenes.indexOf(this);
  28548. if (index > -1) {
  28549. this._engine.scenes.splice(index, 1);
  28550. }
  28551. this._engine.wipeCaches(true);
  28552. this._isDisposed = true;
  28553. };
  28554. Object.defineProperty(Scene.prototype, "isDisposed", {
  28555. /**
  28556. * Gets if the scene is already disposed
  28557. */
  28558. get: function () {
  28559. return this._isDisposed;
  28560. },
  28561. enumerable: true,
  28562. configurable: true
  28563. });
  28564. /**
  28565. * Releases sounds & soundtracks
  28566. */
  28567. Scene.prototype.disposeSounds = function () {
  28568. if (!this._mainSoundTrack) {
  28569. return;
  28570. }
  28571. this.mainSoundTrack.dispose();
  28572. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28573. this.soundTracks[scIndex].dispose();
  28574. }
  28575. };
  28576. /**
  28577. * Call this function to reduce memory footprint of the scene.
  28578. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28579. */
  28580. Scene.prototype.clearCachedVertexData = function () {
  28581. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28582. var mesh = this.meshes[meshIndex];
  28583. var geometry = mesh.geometry;
  28584. if (geometry) {
  28585. geometry._indices = [];
  28586. for (var vbName in geometry._vertexBuffers) {
  28587. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28588. continue;
  28589. }
  28590. geometry._vertexBuffers[vbName]._buffer._data = null;
  28591. }
  28592. }
  28593. }
  28594. };
  28595. /**
  28596. * This function will remove the local cached buffer data from texture.
  28597. * It will save memory but will prevent the texture from being rebuilt
  28598. */
  28599. Scene.prototype.cleanCachedTextureBuffer = function () {
  28600. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28601. var baseTexture = _a[_i];
  28602. var buffer = baseTexture._buffer;
  28603. if (buffer) {
  28604. baseTexture._buffer = null;
  28605. }
  28606. }
  28607. };
  28608. // Octrees
  28609. /**
  28610. * Get the world extend vectors with an optional filter
  28611. *
  28612. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28613. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28614. */
  28615. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28616. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28617. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28618. filterPredicate = filterPredicate || (function () { return true; });
  28619. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28620. mesh.computeWorldMatrix(true);
  28621. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28622. return;
  28623. }
  28624. var boundingInfo = mesh.getBoundingInfo();
  28625. var minBox = boundingInfo.boundingBox.minimumWorld;
  28626. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28627. BABYLON.Tools.CheckExtends(minBox, min, max);
  28628. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28629. });
  28630. return {
  28631. min: min,
  28632. max: max
  28633. };
  28634. };
  28635. /**
  28636. * Creates or updates the octree used to boost selection (picking)
  28637. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28638. * @param maxCapacity defines the maximum capacity per leaf
  28639. * @param maxDepth defines the maximum depth of the octree
  28640. * @returns an octree of AbstractMesh
  28641. */
  28642. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28643. if (maxCapacity === void 0) { maxCapacity = 64; }
  28644. if (maxDepth === void 0) { maxDepth = 2; }
  28645. if (!this._selectionOctree) {
  28646. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28647. }
  28648. var worldExtends = this.getWorldExtends();
  28649. // Update octree
  28650. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28651. return this._selectionOctree;
  28652. };
  28653. // Picking
  28654. /**
  28655. * Creates a ray that can be used to pick in the scene
  28656. * @param x defines the x coordinate of the origin (on-screen)
  28657. * @param y defines the y coordinate of the origin (on-screen)
  28658. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28659. * @param camera defines the camera to use for the picking
  28660. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28661. * @returns a Ray
  28662. */
  28663. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28664. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28665. var result = BABYLON.Ray.Zero();
  28666. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28667. return result;
  28668. };
  28669. /**
  28670. * Creates a ray that can be used to pick in the scene
  28671. * @param x defines the x coordinate of the origin (on-screen)
  28672. * @param y defines the y coordinate of the origin (on-screen)
  28673. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28674. * @param result defines the ray where to store the picking ray
  28675. * @param camera defines the camera to use for the picking
  28676. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28677. * @returns the current scene
  28678. */
  28679. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28680. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28681. var engine = this._engine;
  28682. if (!camera) {
  28683. if (!this.activeCamera)
  28684. throw new Error("Active camera not set");
  28685. camera = this.activeCamera;
  28686. }
  28687. var cameraViewport = camera.viewport;
  28688. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28689. // Moving coordinates to local viewport world
  28690. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28691. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28692. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28693. return this;
  28694. };
  28695. /**
  28696. * Creates a ray that can be used to pick in the scene
  28697. * @param x defines the x coordinate of the origin (on-screen)
  28698. * @param y defines the y coordinate of the origin (on-screen)
  28699. * @param camera defines the camera to use for the picking
  28700. * @returns a Ray
  28701. */
  28702. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28703. var result = BABYLON.Ray.Zero();
  28704. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28705. return result;
  28706. };
  28707. /**
  28708. * Creates a ray that can be used to pick in the scene
  28709. * @param x defines the x coordinate of the origin (on-screen)
  28710. * @param y defines the y coordinate of the origin (on-screen)
  28711. * @param result defines the ray where to store the picking ray
  28712. * @param camera defines the camera to use for the picking
  28713. * @returns the current scene
  28714. */
  28715. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28716. if (!BABYLON.PickingInfo) {
  28717. return this;
  28718. }
  28719. var engine = this._engine;
  28720. if (!camera) {
  28721. if (!this.activeCamera)
  28722. throw new Error("Active camera not set");
  28723. camera = this.activeCamera;
  28724. }
  28725. var cameraViewport = camera.viewport;
  28726. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28727. var identity = BABYLON.Matrix.Identity();
  28728. // Moving coordinates to local viewport world
  28729. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28730. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28731. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28732. return this;
  28733. };
  28734. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28735. if (!BABYLON.PickingInfo) {
  28736. return null;
  28737. }
  28738. var pickingInfo = null;
  28739. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28740. var mesh = this.meshes[meshIndex];
  28741. if (predicate) {
  28742. if (!predicate(mesh)) {
  28743. continue;
  28744. }
  28745. }
  28746. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28747. continue;
  28748. }
  28749. var world = mesh.getWorldMatrix();
  28750. var ray = rayFunction(world);
  28751. var result = mesh.intersects(ray, fastCheck);
  28752. if (!result || !result.hit)
  28753. continue;
  28754. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28755. continue;
  28756. pickingInfo = result;
  28757. if (fastCheck) {
  28758. break;
  28759. }
  28760. }
  28761. return pickingInfo || new BABYLON.PickingInfo();
  28762. };
  28763. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28764. if (!BABYLON.PickingInfo) {
  28765. return null;
  28766. }
  28767. var pickingInfos = new Array();
  28768. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28769. var mesh = this.meshes[meshIndex];
  28770. if (predicate) {
  28771. if (!predicate(mesh)) {
  28772. continue;
  28773. }
  28774. }
  28775. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28776. continue;
  28777. }
  28778. var world = mesh.getWorldMatrix();
  28779. var ray = rayFunction(world);
  28780. var result = mesh.intersects(ray, false);
  28781. if (!result || !result.hit)
  28782. continue;
  28783. pickingInfos.push(result);
  28784. }
  28785. return pickingInfos;
  28786. };
  28787. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28788. if (!BABYLON.PickingInfo) {
  28789. return null;
  28790. }
  28791. var pickingInfo = null;
  28792. if (!camera) {
  28793. if (!this.activeCamera) {
  28794. return null;
  28795. }
  28796. camera = this.activeCamera;
  28797. }
  28798. if (this.spriteManagers.length > 0) {
  28799. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28800. var spriteManager = this.spriteManagers[spriteIndex];
  28801. if (!spriteManager.isPickable) {
  28802. continue;
  28803. }
  28804. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28805. if (!result || !result.hit)
  28806. continue;
  28807. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28808. continue;
  28809. pickingInfo = result;
  28810. if (fastCheck) {
  28811. break;
  28812. }
  28813. }
  28814. }
  28815. return pickingInfo || new BABYLON.PickingInfo();
  28816. };
  28817. /** Launch a ray to try to pick a mesh in the scene
  28818. * @param x position on screen
  28819. * @param y position on screen
  28820. * @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
  28821. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28822. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28823. * @returns a PickingInfo
  28824. */
  28825. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28826. var _this = this;
  28827. if (!BABYLON.PickingInfo) {
  28828. return null;
  28829. }
  28830. var result = this._internalPick(function (world) {
  28831. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28832. return _this._tempPickingRay;
  28833. }, predicate, fastCheck);
  28834. if (result) {
  28835. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28836. }
  28837. return result;
  28838. };
  28839. /** Launch a ray to try to pick a sprite in the scene
  28840. * @param x position on screen
  28841. * @param y position on screen
  28842. * @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
  28843. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28844. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28845. * @returns a PickingInfo
  28846. */
  28847. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28848. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28849. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28850. };
  28851. /** Use the given ray to pick a mesh in the scene
  28852. * @param ray The ray to use to pick meshes
  28853. * @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
  28854. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28855. * @returns a PickingInfo
  28856. */
  28857. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28858. var _this = this;
  28859. var result = this._internalPick(function (world) {
  28860. if (!_this._pickWithRayInverseMatrix) {
  28861. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28862. }
  28863. world.invertToRef(_this._pickWithRayInverseMatrix);
  28864. if (!_this._cachedRayForTransform) {
  28865. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28866. }
  28867. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28868. return _this._cachedRayForTransform;
  28869. }, predicate, fastCheck);
  28870. if (result) {
  28871. result.ray = ray;
  28872. }
  28873. return result;
  28874. };
  28875. /**
  28876. * Launch a ray to try to pick a mesh in the scene
  28877. * @param x X position on screen
  28878. * @param y Y position on screen
  28879. * @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
  28880. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28881. * @returns an array of PickingInfo
  28882. */
  28883. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28884. var _this = this;
  28885. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28886. };
  28887. /**
  28888. * Launch a ray to try to pick a mesh in the scene
  28889. * @param ray Ray to use
  28890. * @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
  28891. * @returns an array of PickingInfo
  28892. */
  28893. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28894. var _this = this;
  28895. return this._internalMultiPick(function (world) {
  28896. if (!_this._pickWithRayInverseMatrix) {
  28897. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28898. }
  28899. world.invertToRef(_this._pickWithRayInverseMatrix);
  28900. if (!_this._cachedRayForTransform) {
  28901. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28902. }
  28903. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28904. return _this._cachedRayForTransform;
  28905. }, predicate);
  28906. };
  28907. /**
  28908. * Force the value of meshUnderPointer
  28909. * @param mesh defines the mesh to use
  28910. */
  28911. Scene.prototype.setPointerOverMesh = function (mesh) {
  28912. if (this._pointerOverMesh === mesh) {
  28913. return;
  28914. }
  28915. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28916. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28917. }
  28918. this._pointerOverMesh = mesh;
  28919. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28920. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28921. }
  28922. };
  28923. /**
  28924. * Gets the mesh under the pointer
  28925. * @returns a Mesh or null if no mesh is under the pointer
  28926. */
  28927. Scene.prototype.getPointerOverMesh = function () {
  28928. return this._pointerOverMesh;
  28929. };
  28930. /**
  28931. * Force the sprite under the pointer
  28932. * @param sprite defines the sprite to use
  28933. */
  28934. Scene.prototype.setPointerOverSprite = function (sprite) {
  28935. if (this._pointerOverSprite === sprite) {
  28936. return;
  28937. }
  28938. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28939. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28940. }
  28941. this._pointerOverSprite = sprite;
  28942. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28943. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28944. }
  28945. };
  28946. /**
  28947. * Gets the sprite under the pointer
  28948. * @returns a Sprite or null if no sprite is under the pointer
  28949. */
  28950. Scene.prototype.getPointerOverSprite = function () {
  28951. return this._pointerOverSprite;
  28952. };
  28953. // Physics
  28954. /**
  28955. * Gets the current physics engine
  28956. * @returns a PhysicsEngine or null if none attached
  28957. */
  28958. Scene.prototype.getPhysicsEngine = function () {
  28959. return this._physicsEngine;
  28960. };
  28961. /**
  28962. * Enables physics to the current scene
  28963. * @param gravity defines the scene's gravity for the physics engine
  28964. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28965. * @return a boolean indicating if the physics engine was initialized
  28966. */
  28967. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28968. if (gravity === void 0) { gravity = null; }
  28969. if (this._physicsEngine) {
  28970. return true;
  28971. }
  28972. try {
  28973. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28974. return true;
  28975. }
  28976. catch (e) {
  28977. BABYLON.Tools.Error(e.message);
  28978. return false;
  28979. }
  28980. };
  28981. /**
  28982. * Disables and disposes the physics engine associated with the scene
  28983. */
  28984. Scene.prototype.disablePhysicsEngine = function () {
  28985. if (!this._physicsEngine) {
  28986. return;
  28987. }
  28988. this._physicsEngine.dispose();
  28989. this._physicsEngine = null;
  28990. };
  28991. /**
  28992. * Gets a boolean indicating if there is an active physics engine
  28993. * @returns a boolean indicating if there is an active physics engine
  28994. */
  28995. Scene.prototype.isPhysicsEnabled = function () {
  28996. return this._physicsEngine !== undefined;
  28997. };
  28998. /**
  28999. * Deletes a physics compound impostor
  29000. * @param compound defines the compound to delete
  29001. */
  29002. Scene.prototype.deleteCompoundImpostor = function (compound) {
  29003. var mesh = compound.parts[0].mesh;
  29004. if (mesh.physicsImpostor) {
  29005. mesh.physicsImpostor.dispose( /*true*/);
  29006. mesh.physicsImpostor = null;
  29007. }
  29008. };
  29009. // Misc.
  29010. /** @hidden */
  29011. Scene.prototype._rebuildGeometries = function () {
  29012. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  29013. var geometry = _a[_i];
  29014. geometry._rebuild();
  29015. }
  29016. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29017. var mesh = _c[_b];
  29018. mesh._rebuild();
  29019. }
  29020. if (this.postProcessManager) {
  29021. this.postProcessManager._rebuild();
  29022. }
  29023. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  29024. var layer = _e[_d];
  29025. layer._rebuild();
  29026. }
  29027. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  29028. var effectLayer = _g[_f];
  29029. effectLayer._rebuild();
  29030. }
  29031. if (this._boundingBoxRenderer) {
  29032. this._boundingBoxRenderer._rebuild();
  29033. }
  29034. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  29035. var system = _j[_h];
  29036. system.rebuild();
  29037. }
  29038. if (this._postProcessRenderPipelineManager) {
  29039. this._postProcessRenderPipelineManager._rebuild();
  29040. }
  29041. };
  29042. /** @hidden */
  29043. Scene.prototype._rebuildTextures = function () {
  29044. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29045. var texture = _a[_i];
  29046. texture._rebuild();
  29047. }
  29048. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29049. };
  29050. /**
  29051. * Creates a default light for the scene.
  29052. * @param replace Whether to replace the existing lights in the scene.
  29053. */
  29054. Scene.prototype.createDefaultLight = function (replace) {
  29055. if (replace === void 0) { replace = false; }
  29056. // Dispose existing light in replace mode.
  29057. if (replace) {
  29058. if (this.lights) {
  29059. for (var i = 0; i < this.lights.length; i++) {
  29060. this.lights[i].dispose();
  29061. }
  29062. }
  29063. }
  29064. // Light
  29065. if (this.lights.length === 0) {
  29066. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29067. }
  29068. };
  29069. /**
  29070. * Creates a default camera for the scene.
  29071. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29072. * @param replace Whether to replace the existing active camera in the scene.
  29073. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29074. */
  29075. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29076. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29077. if (replace === void 0) { replace = false; }
  29078. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29079. // Dispose existing camera in replace mode.
  29080. if (replace) {
  29081. if (this.activeCamera) {
  29082. this.activeCamera.dispose();
  29083. this.activeCamera = null;
  29084. }
  29085. }
  29086. // Camera
  29087. if (!this.activeCamera) {
  29088. var worldExtends = this.getWorldExtends();
  29089. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29090. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29091. var camera;
  29092. var radius = worldSize.length() * 1.5;
  29093. // empty scene scenario!
  29094. if (!isFinite(radius)) {
  29095. radius = 1;
  29096. worldCenter.copyFromFloats(0, 0, 0);
  29097. }
  29098. if (createArcRotateCamera) {
  29099. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29100. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29101. arcRotateCamera.wheelPrecision = 100 / radius;
  29102. camera = arcRotateCamera;
  29103. }
  29104. else {
  29105. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29106. freeCamera.setTarget(worldCenter);
  29107. camera = freeCamera;
  29108. }
  29109. camera.minZ = radius * 0.01;
  29110. camera.maxZ = radius * 1000;
  29111. camera.speed = radius * 0.2;
  29112. this.activeCamera = camera;
  29113. var canvas = this.getEngine().getRenderingCanvas();
  29114. if (attachCameraControls && canvas) {
  29115. camera.attachControl(canvas);
  29116. }
  29117. }
  29118. };
  29119. /**
  29120. * Creates a default camera and a default light
  29121. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29122. * @param replace defines if the camera and/or light will replace the existing ones
  29123. * @param attachCameraControls defines if attachControl will be called on the new camera
  29124. */
  29125. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29126. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29127. if (replace === void 0) { replace = false; }
  29128. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29129. this.createDefaultLight(replace);
  29130. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29131. };
  29132. /**
  29133. * Creates a new sky box
  29134. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29135. * @param environmentTexture defines the texture to use as environment texture
  29136. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29137. * @param scale defines the overall scale of the skybox
  29138. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29139. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29140. * @returns a new mesh holding the sky box
  29141. */
  29142. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29143. if (pbr === void 0) { pbr = false; }
  29144. if (scale === void 0) { scale = 1000; }
  29145. if (blur === void 0) { blur = 0; }
  29146. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29147. if (!environmentTexture) {
  29148. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29149. return null;
  29150. }
  29151. if (setGlobalEnvTexture) {
  29152. if (environmentTexture) {
  29153. this.environmentTexture = environmentTexture;
  29154. }
  29155. }
  29156. // Skybox
  29157. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29158. if (pbr) {
  29159. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29160. hdrSkyboxMaterial.backFaceCulling = false;
  29161. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29162. if (hdrSkyboxMaterial.reflectionTexture) {
  29163. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29164. }
  29165. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29166. hdrSkyboxMaterial.disableLighting = true;
  29167. hdrSkyboxMaterial.twoSidedLighting = true;
  29168. hdrSkybox.infiniteDistance = true;
  29169. hdrSkybox.material = hdrSkyboxMaterial;
  29170. }
  29171. else {
  29172. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29173. skyboxMaterial.backFaceCulling = false;
  29174. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29175. if (skyboxMaterial.reflectionTexture) {
  29176. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29177. }
  29178. skyboxMaterial.disableLighting = true;
  29179. hdrSkybox.infiniteDistance = true;
  29180. hdrSkybox.material = skyboxMaterial;
  29181. }
  29182. return hdrSkybox;
  29183. };
  29184. /**
  29185. * Creates a new environment
  29186. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29187. * @param options defines the options you can use to configure the environment
  29188. * @returns the new EnvironmentHelper
  29189. */
  29190. Scene.prototype.createDefaultEnvironment = function (options) {
  29191. if (BABYLON.EnvironmentHelper) {
  29192. return new BABYLON.EnvironmentHelper(options, this);
  29193. }
  29194. return null;
  29195. };
  29196. /**
  29197. * Creates a new VREXperienceHelper
  29198. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29199. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29200. * @returns a new VREXperienceHelper
  29201. */
  29202. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29203. if (webVROptions === void 0) { webVROptions = {}; }
  29204. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29205. };
  29206. // Tags
  29207. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29208. if (tagsQuery === undefined) {
  29209. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29210. return list;
  29211. }
  29212. var listByTags = [];
  29213. forEach = forEach || (function (item) { return; });
  29214. for (var i in list) {
  29215. var item = list[i];
  29216. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29217. listByTags.push(item);
  29218. forEach(item);
  29219. }
  29220. }
  29221. return listByTags;
  29222. };
  29223. /**
  29224. * Get a list of meshes by tags
  29225. * @param tagsQuery defines the tags query to use
  29226. * @param forEach defines a predicate used to filter results
  29227. * @returns an array of Mesh
  29228. */
  29229. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29230. return this._getByTags(this.meshes, tagsQuery, forEach);
  29231. };
  29232. /**
  29233. * Get a list of cameras by tags
  29234. * @param tagsQuery defines the tags query to use
  29235. * @param forEach defines a predicate used to filter results
  29236. * @returns an array of Camera
  29237. */
  29238. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29239. return this._getByTags(this.cameras, tagsQuery, forEach);
  29240. };
  29241. /**
  29242. * Get a list of lights by tags
  29243. * @param tagsQuery defines the tags query to use
  29244. * @param forEach defines a predicate used to filter results
  29245. * @returns an array of Light
  29246. */
  29247. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29248. return this._getByTags(this.lights, tagsQuery, forEach);
  29249. };
  29250. /**
  29251. * Get a list of materials by tags
  29252. * @param tagsQuery defines the tags query to use
  29253. * @param forEach defines a predicate used to filter results
  29254. * @returns an array of Material
  29255. */
  29256. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29257. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29258. };
  29259. /**
  29260. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29261. * This allowed control for front to back rendering or reversly depending of the special needs.
  29262. *
  29263. * @param renderingGroupId The rendering group id corresponding to its index
  29264. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29265. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29266. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29267. */
  29268. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29269. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29270. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29271. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29272. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29273. };
  29274. /**
  29275. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29276. *
  29277. * @param renderingGroupId The rendering group id corresponding to its index
  29278. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29279. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29280. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29281. */
  29282. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29283. if (depth === void 0) { depth = true; }
  29284. if (stencil === void 0) { stencil = true; }
  29285. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29286. };
  29287. /**
  29288. * Will flag all materials as dirty to trigger new shader compilation
  29289. * @param flag defines the flag used to specify which material part must be marked as dirty
  29290. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29291. */
  29292. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29293. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29294. var material = _a[_i];
  29295. if (predicate && !predicate(material)) {
  29296. continue;
  29297. }
  29298. material.markAsDirty(flag);
  29299. }
  29300. };
  29301. /** @hidden */
  29302. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29303. var _this = this;
  29304. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29305. this._activeRequests.push(request);
  29306. request.onCompleteObservable.add(function (request) {
  29307. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29308. });
  29309. return request;
  29310. };
  29311. /** @hidden */
  29312. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29313. var _this = this;
  29314. return new Promise(function (resolve, reject) {
  29315. _this._loadFile(url, function (data) {
  29316. resolve(data);
  29317. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29318. reject(exception);
  29319. });
  29320. });
  29321. };
  29322. // Statics
  29323. Scene._FOGMODE_NONE = 0;
  29324. Scene._FOGMODE_EXP = 1;
  29325. Scene._FOGMODE_EXP2 = 2;
  29326. Scene._FOGMODE_LINEAR = 3;
  29327. Scene._uniqueIdCounter = 0;
  29328. /**
  29329. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29330. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29331. */
  29332. Scene.MinDeltaTime = 1.0;
  29333. /**
  29334. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29335. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29336. */
  29337. Scene.MaxDeltaTime = 1000.0;
  29338. /** The distance in pixel that you have to move to prevent some events */
  29339. Scene.DragMovementThreshold = 10; // in pixels
  29340. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29341. Scene.LongPressDelay = 500; // in milliseconds
  29342. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29343. Scene.DoubleClickDelay = 300; // in milliseconds
  29344. /** If you need to check double click without raising a single click at first click, enable this flag */
  29345. Scene.ExclusiveDoubleClickMode = false;
  29346. return Scene;
  29347. }());
  29348. BABYLON.Scene = Scene;
  29349. })(BABYLON || (BABYLON = {}));
  29350. //# sourceMappingURL=babylon.scene.js.map
  29351. var BABYLON;
  29352. (function (BABYLON) {
  29353. /**
  29354. * Set of assets to keep when moving a scene into an asset container.
  29355. */
  29356. var KeepAssets = /** @class */ (function () {
  29357. function KeepAssets() {
  29358. /**
  29359. * Cameras to keep.
  29360. */
  29361. this.cameras = new Array();
  29362. /**
  29363. * Lights to keep.
  29364. */
  29365. this.lights = new Array();
  29366. /**
  29367. * Meshes to keep.
  29368. */
  29369. this.meshes = new Array();
  29370. /**
  29371. * Skeletons to keep.
  29372. */
  29373. this.skeletons = new Array();
  29374. /**
  29375. * ParticleSystems to keep.
  29376. */
  29377. this.particleSystems = new Array();
  29378. /**
  29379. * Animations to keep.
  29380. */
  29381. this.animations = new Array();
  29382. /**
  29383. * AnimationGroups to keep.
  29384. */
  29385. this.animationGroups = new Array();
  29386. /**
  29387. * MultiMaterials to keep.
  29388. */
  29389. this.multiMaterials = new Array();
  29390. /**
  29391. * Materials to keep.
  29392. */
  29393. this.materials = new Array();
  29394. /**
  29395. * MorphTargetManagers to keep.
  29396. */
  29397. this.morphTargetManagers = new Array();
  29398. /**
  29399. * Geometries to keep.
  29400. */
  29401. this.geometries = new Array();
  29402. /**
  29403. * TransformNodes to keep.
  29404. */
  29405. this.transformNodes = new Array();
  29406. /**
  29407. * LensFlareSystems to keep.
  29408. */
  29409. this.lensFlareSystems = new Array();
  29410. /**
  29411. * ShadowGenerators to keep.
  29412. */
  29413. this.shadowGenerators = new Array();
  29414. /**
  29415. * ActionManagers to keep.
  29416. */
  29417. this.actionManagers = new Array();
  29418. /**
  29419. * Sounds to keep.
  29420. */
  29421. this.sounds = new Array();
  29422. /**
  29423. * Textures to keep.
  29424. */
  29425. this.textures = new Array();
  29426. /**
  29427. * Effect layers to keep.
  29428. */
  29429. this.effectLayers = new Array();
  29430. }
  29431. return KeepAssets;
  29432. }());
  29433. BABYLON.KeepAssets = KeepAssets;
  29434. /**
  29435. * Container with a set of assets that can be added or removed from a scene.
  29436. */
  29437. var AssetContainer = /** @class */ (function () {
  29438. /**
  29439. * Instantiates an AssetContainer.
  29440. * @param scene The scene the AssetContainer belongs to.
  29441. */
  29442. function AssetContainer(scene) {
  29443. // Objects
  29444. /**
  29445. * Cameras populated in the container.
  29446. */
  29447. this.cameras = new Array();
  29448. /**
  29449. * Lights populated in the container.
  29450. */
  29451. this.lights = new Array();
  29452. /**
  29453. * Meshes populated in the container.
  29454. */
  29455. this.meshes = new Array();
  29456. /**
  29457. * Skeletons populated in the container.
  29458. */
  29459. this.skeletons = new Array();
  29460. /**
  29461. * ParticleSystems populated in the container.
  29462. */
  29463. this.particleSystems = new Array();
  29464. /**
  29465. * Animations populated in the container.
  29466. */
  29467. this.animations = new Array();
  29468. /**
  29469. * AnimationGroups populated in the container.
  29470. */
  29471. this.animationGroups = new Array();
  29472. /**
  29473. * MultiMaterials populated in the container.
  29474. */
  29475. this.multiMaterials = new Array();
  29476. /**
  29477. * Materials populated in the container.
  29478. */
  29479. this.materials = new Array();
  29480. /**
  29481. * MorphTargetManagers populated in the container.
  29482. */
  29483. this.morphTargetManagers = new Array();
  29484. /**
  29485. * Geometries populated in the container.
  29486. */
  29487. this.geometries = new Array();
  29488. /**
  29489. * TransformNodes populated in the container.
  29490. */
  29491. this.transformNodes = new Array();
  29492. /**
  29493. * LensFlareSystems populated in the container.
  29494. */
  29495. this.lensFlareSystems = new Array();
  29496. /**
  29497. * ShadowGenerators populated in the container.
  29498. */
  29499. this.shadowGenerators = new Array();
  29500. /**
  29501. * ActionManagers populated in the container.
  29502. */
  29503. this.actionManagers = new Array();
  29504. /**
  29505. * Sounds populated in the container.
  29506. */
  29507. this.sounds = new Array();
  29508. /**
  29509. * Textures populated in the container.
  29510. */
  29511. this.textures = new Array();
  29512. /**
  29513. * Effect layers populated in the container.
  29514. */
  29515. this.effectLayers = new Array();
  29516. this.scene = scene;
  29517. }
  29518. /**
  29519. * Adds all the assets from the container to the scene.
  29520. */
  29521. AssetContainer.prototype.addAllToScene = function () {
  29522. var _this = this;
  29523. this.cameras.forEach(function (o) {
  29524. _this.scene.addCamera(o);
  29525. });
  29526. this.lights.forEach(function (o) {
  29527. _this.scene.addLight(o);
  29528. });
  29529. this.meshes.forEach(function (o) {
  29530. _this.scene.addMesh(o);
  29531. });
  29532. this.skeletons.forEach(function (o) {
  29533. _this.scene.addSkeleton(o);
  29534. });
  29535. this.particleSystems.forEach(function (o) {
  29536. _this.scene.addParticleSystem(o);
  29537. });
  29538. this.animations.forEach(function (o) {
  29539. _this.scene.addAnimation(o);
  29540. });
  29541. this.animationGroups.forEach(function (o) {
  29542. _this.scene.addAnimationGroup(o);
  29543. });
  29544. this.multiMaterials.forEach(function (o) {
  29545. _this.scene.addMultiMaterial(o);
  29546. });
  29547. this.materials.forEach(function (o) {
  29548. _this.scene.addMaterial(o);
  29549. });
  29550. this.morphTargetManagers.forEach(function (o) {
  29551. _this.scene.addMorphTargetManager(o);
  29552. });
  29553. this.geometries.forEach(function (o) {
  29554. _this.scene.addGeometry(o);
  29555. });
  29556. this.transformNodes.forEach(function (o) {
  29557. _this.scene.addTransformNode(o);
  29558. });
  29559. this.lensFlareSystems.forEach(function (o) {
  29560. _this.scene.addLensFlareSystem(o);
  29561. });
  29562. this.actionManagers.forEach(function (o) {
  29563. _this.scene.addActionManager(o);
  29564. });
  29565. this.sounds.forEach(function (o) {
  29566. o.play();
  29567. o.autoplay = true;
  29568. _this.scene.mainSoundTrack.AddSound(o);
  29569. });
  29570. this.textures.forEach(function (o) {
  29571. _this.scene.addTexture(o);
  29572. });
  29573. this.effectLayers.forEach(function (o) {
  29574. _this.scene.addEffectLayer(o);
  29575. });
  29576. };
  29577. /**
  29578. * Removes all the assets in the container from the scene
  29579. */
  29580. AssetContainer.prototype.removeAllFromScene = function () {
  29581. var _this = this;
  29582. this.cameras.forEach(function (o) {
  29583. _this.scene.removeCamera(o);
  29584. });
  29585. this.lights.forEach(function (o) {
  29586. _this.scene.removeLight(o);
  29587. });
  29588. this.meshes.forEach(function (o) {
  29589. _this.scene.removeMesh(o);
  29590. });
  29591. this.skeletons.forEach(function (o) {
  29592. _this.scene.removeSkeleton(o);
  29593. });
  29594. this.particleSystems.forEach(function (o) {
  29595. _this.scene.removeParticleSystem(o);
  29596. });
  29597. this.animations.forEach(function (o) {
  29598. _this.scene.removeAnimation(o);
  29599. });
  29600. this.animationGroups.forEach(function (o) {
  29601. _this.scene.removeAnimationGroup(o);
  29602. });
  29603. this.multiMaterials.forEach(function (o) {
  29604. _this.scene.removeMultiMaterial(o);
  29605. });
  29606. this.materials.forEach(function (o) {
  29607. _this.scene.removeMaterial(o);
  29608. });
  29609. this.morphTargetManagers.forEach(function (o) {
  29610. _this.scene.removeMorphTargetManager(o);
  29611. });
  29612. this.geometries.forEach(function (o) {
  29613. _this.scene.removeGeometry(o);
  29614. });
  29615. this.transformNodes.forEach(function (o) {
  29616. _this.scene.removeTransformNode(o);
  29617. });
  29618. this.lensFlareSystems.forEach(function (o) {
  29619. _this.scene.removeLensFlareSystem(o);
  29620. });
  29621. this.actionManagers.forEach(function (o) {
  29622. _this.scene.removeActionManager(o);
  29623. });
  29624. this.sounds.forEach(function (o) {
  29625. o.stop();
  29626. o.autoplay = false;
  29627. _this.scene.mainSoundTrack.RemoveSound(o);
  29628. });
  29629. this.textures.forEach(function (o) {
  29630. _this.scene.removeTexture(o);
  29631. });
  29632. this.effectLayers.forEach(function (o) {
  29633. _this.scene.removeEffectLayer(o);
  29634. });
  29635. };
  29636. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29637. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29638. var asset = sourceAssets_1[_i];
  29639. var move = true;
  29640. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29641. var keepAsset = keepAssets_1[_a];
  29642. if (asset === keepAsset) {
  29643. move = false;
  29644. break;
  29645. }
  29646. }
  29647. if (move) {
  29648. targetAssets.push(asset);
  29649. }
  29650. }
  29651. };
  29652. /**
  29653. * Removes all the assets contained in the scene and adds them to the container.
  29654. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29655. */
  29656. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29657. if (keepAssets === undefined) {
  29658. keepAssets = new KeepAssets();
  29659. }
  29660. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29661. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29662. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29663. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29664. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29665. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29666. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29667. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29668. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29669. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29670. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29671. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29672. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29673. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29674. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29675. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29676. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29677. this.removeAllFromScene();
  29678. };
  29679. /**
  29680. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29681. * @returns the root mesh
  29682. */
  29683. AssetContainer.prototype.createRootMesh = function () {
  29684. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29685. this.meshes.forEach(function (m) {
  29686. if (!m.parent) {
  29687. rootMesh.addChild(m);
  29688. }
  29689. });
  29690. this.meshes.unshift(rootMesh);
  29691. return rootMesh;
  29692. };
  29693. return AssetContainer;
  29694. }());
  29695. BABYLON.AssetContainer = AssetContainer;
  29696. })(BABYLON || (BABYLON = {}));
  29697. //# sourceMappingURL=babylon.assetContainer.js.map
  29698. var BABYLON;
  29699. (function (BABYLON) {
  29700. var Buffer = /** @class */ (function () {
  29701. /**
  29702. * Constructor
  29703. * @param engine the engine
  29704. * @param data the data to use for this buffer
  29705. * @param updatable whether the data is updatable
  29706. * @param stride the stride (optional)
  29707. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29708. * @param instanced whether the buffer is instanced (optional)
  29709. * @param useBytes set to true if the stride in in bytes (optional)
  29710. */
  29711. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29712. if (stride === void 0) { stride = 0; }
  29713. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29714. if (instanced === void 0) { instanced = false; }
  29715. if (useBytes === void 0) { useBytes = false; }
  29716. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29717. this._engine = engine.getScene().getEngine();
  29718. }
  29719. else {
  29720. this._engine = engine;
  29721. }
  29722. this._updatable = updatable;
  29723. this._instanced = instanced;
  29724. this._data = data;
  29725. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29726. if (!postponeInternalCreation) { // by default
  29727. this.create();
  29728. }
  29729. }
  29730. /**
  29731. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29732. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29733. * @param offset defines offset in the buffer (0 by default)
  29734. * @param size defines the size in floats of attributes (position is 3 for instance)
  29735. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29736. * @param instanced defines if the vertex buffer contains indexed data
  29737. * @param useBytes defines if the offset and stride are in bytes
  29738. * @returns the new vertex buffer
  29739. */
  29740. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29741. if (useBytes === void 0) { useBytes = false; }
  29742. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29743. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29744. // a lot of these parameters are ignored as they are overriden by the buffer
  29745. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29746. };
  29747. // Properties
  29748. Buffer.prototype.isUpdatable = function () {
  29749. return this._updatable;
  29750. };
  29751. Buffer.prototype.getData = function () {
  29752. return this._data;
  29753. };
  29754. Buffer.prototype.getBuffer = function () {
  29755. return this._buffer;
  29756. };
  29757. /**
  29758. * Gets the stride in float32 units (i.e. byte stride / 4).
  29759. * May not be an integer if the byte stride is not divisible by 4.
  29760. * DEPRECATED. Use byteStride instead.
  29761. * @returns the stride in float32 units
  29762. */
  29763. Buffer.prototype.getStrideSize = function () {
  29764. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29765. };
  29766. // Methods
  29767. Buffer.prototype.create = function (data) {
  29768. if (data === void 0) { data = null; }
  29769. if (!data && this._buffer) {
  29770. return; // nothing to do
  29771. }
  29772. data = data || this._data;
  29773. if (!data) {
  29774. return;
  29775. }
  29776. if (!this._buffer) { // create buffer
  29777. if (this._updatable) {
  29778. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29779. this._data = data;
  29780. }
  29781. else {
  29782. this._buffer = this._engine.createVertexBuffer(data);
  29783. }
  29784. }
  29785. else if (this._updatable) { // update buffer
  29786. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29787. this._data = data;
  29788. }
  29789. };
  29790. Buffer.prototype._rebuild = function () {
  29791. this._buffer = null;
  29792. this.create(this._data);
  29793. };
  29794. Buffer.prototype.update = function (data) {
  29795. this.create(data);
  29796. };
  29797. /**
  29798. * Updates the data directly.
  29799. * @param data the new data
  29800. * @param offset the new offset
  29801. * @param vertexCount the vertex count (optional)
  29802. * @param useBytes set to true if the offset is in bytes
  29803. */
  29804. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29805. if (useBytes === void 0) { useBytes = false; }
  29806. if (!this._buffer) {
  29807. return;
  29808. }
  29809. if (this._updatable) { // update buffer
  29810. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29811. this._data = null;
  29812. }
  29813. };
  29814. Buffer.prototype.dispose = function () {
  29815. if (!this._buffer) {
  29816. return;
  29817. }
  29818. if (this._engine._releaseBuffer(this._buffer)) {
  29819. this._buffer = null;
  29820. }
  29821. };
  29822. return Buffer;
  29823. }());
  29824. BABYLON.Buffer = Buffer;
  29825. })(BABYLON || (BABYLON = {}));
  29826. //# sourceMappingURL=babylon.buffer.js.map
  29827. var BABYLON;
  29828. (function (BABYLON) {
  29829. var VertexBuffer = /** @class */ (function () {
  29830. /**
  29831. * Constructor
  29832. * @param engine the engine
  29833. * @param data the data to use for this vertex buffer
  29834. * @param kind the vertex buffer kind
  29835. * @param updatable whether the data is updatable
  29836. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29837. * @param stride the stride (optional)
  29838. * @param instanced whether the buffer is instanced (optional)
  29839. * @param offset the offset of the data (optional)
  29840. * @param size the number of components (optional)
  29841. * @param type the type of the component (optional)
  29842. * @param normalized whether the data contains normalized data (optional)
  29843. * @param useBytes set to true if stride and offset are in bytes (optional)
  29844. */
  29845. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29846. if (normalized === void 0) { normalized = false; }
  29847. if (useBytes === void 0) { useBytes = false; }
  29848. if (data instanceof BABYLON.Buffer) {
  29849. this._buffer = data;
  29850. this._ownsBuffer = false;
  29851. }
  29852. else {
  29853. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29854. this._ownsBuffer = true;
  29855. }
  29856. this._kind = kind;
  29857. if (type == undefined) {
  29858. var data_1 = this.getData();
  29859. this.type = VertexBuffer.FLOAT;
  29860. if (data_1 instanceof Int8Array)
  29861. this.type = VertexBuffer.BYTE;
  29862. else if (data_1 instanceof Uint8Array)
  29863. this.type = VertexBuffer.UNSIGNED_BYTE;
  29864. else if (data_1 instanceof Int16Array)
  29865. this.type = VertexBuffer.SHORT;
  29866. else if (data_1 instanceof Uint16Array)
  29867. this.type = VertexBuffer.UNSIGNED_SHORT;
  29868. else if (data_1 instanceof Int32Array)
  29869. this.type = VertexBuffer.INT;
  29870. else if (data_1 instanceof Uint32Array)
  29871. this.type = VertexBuffer.UNSIGNED_INT;
  29872. }
  29873. else {
  29874. this.type = type;
  29875. }
  29876. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29877. if (useBytes) {
  29878. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29879. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29880. this.byteOffset = offset || 0;
  29881. }
  29882. else {
  29883. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29884. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29885. this.byteOffset = (offset || 0) * typeByteLength;
  29886. }
  29887. this.normalized = normalized;
  29888. this._instanced = instanced !== undefined ? instanced : false;
  29889. this._instanceDivisor = instanced ? 1 : 0;
  29890. }
  29891. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29892. /**
  29893. * Gets or sets the instance divisor when in instanced mode
  29894. */
  29895. get: function () {
  29896. return this._instanceDivisor;
  29897. },
  29898. set: function (value) {
  29899. this._instanceDivisor = value;
  29900. if (value == 0) {
  29901. this._instanced = false;
  29902. }
  29903. else {
  29904. this._instanced = true;
  29905. }
  29906. },
  29907. enumerable: true,
  29908. configurable: true
  29909. });
  29910. VertexBuffer.prototype._rebuild = function () {
  29911. if (!this._buffer) {
  29912. return;
  29913. }
  29914. this._buffer._rebuild();
  29915. };
  29916. /**
  29917. * Returns the kind of the VertexBuffer (string).
  29918. */
  29919. VertexBuffer.prototype.getKind = function () {
  29920. return this._kind;
  29921. };
  29922. // Properties
  29923. /**
  29924. * Boolean : is the VertexBuffer updatable ?
  29925. */
  29926. VertexBuffer.prototype.isUpdatable = function () {
  29927. return this._buffer.isUpdatable();
  29928. };
  29929. /**
  29930. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29931. */
  29932. VertexBuffer.prototype.getData = function () {
  29933. return this._buffer.getData();
  29934. };
  29935. /**
  29936. * Returns the WebGLBuffer associated to the VertexBuffer.
  29937. */
  29938. VertexBuffer.prototype.getBuffer = function () {
  29939. return this._buffer.getBuffer();
  29940. };
  29941. /**
  29942. * Returns the stride as a multiple of the type byte length.
  29943. * DEPRECATED. Use byteStride instead.
  29944. */
  29945. VertexBuffer.prototype.getStrideSize = function () {
  29946. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29947. };
  29948. /**
  29949. * Returns the offset as a multiple of the type byte length.
  29950. * DEPRECATED. Use byteOffset instead.
  29951. */
  29952. VertexBuffer.prototype.getOffset = function () {
  29953. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29954. };
  29955. /**
  29956. * Returns the number of components per vertex attribute (integer).
  29957. */
  29958. VertexBuffer.prototype.getSize = function () {
  29959. return this._size;
  29960. };
  29961. /**
  29962. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29963. */
  29964. VertexBuffer.prototype.getIsInstanced = function () {
  29965. return this._instanced;
  29966. };
  29967. /**
  29968. * Returns the instancing divisor, zero for non-instanced (integer).
  29969. */
  29970. VertexBuffer.prototype.getInstanceDivisor = function () {
  29971. return this._instanceDivisor;
  29972. };
  29973. // Methods
  29974. /**
  29975. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29976. * Returns the created WebGLBuffer.
  29977. */
  29978. VertexBuffer.prototype.create = function (data) {
  29979. return this._buffer.create(data);
  29980. };
  29981. /**
  29982. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29983. * This function will create a new buffer if the current one is not updatable
  29984. * Returns the updated WebGLBuffer.
  29985. */
  29986. VertexBuffer.prototype.update = function (data) {
  29987. return this._buffer.update(data);
  29988. };
  29989. /**
  29990. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29991. * Returns the directly updated WebGLBuffer.
  29992. * @param data the new data
  29993. * @param offset the new offset
  29994. * @param useBytes set to true if the offset is in bytes
  29995. */
  29996. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29997. if (useBytes === void 0) { useBytes = false; }
  29998. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29999. };
  30000. /**
  30001. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30002. */
  30003. VertexBuffer.prototype.dispose = function () {
  30004. if (this._ownsBuffer) {
  30005. this._buffer.dispose();
  30006. }
  30007. };
  30008. /**
  30009. * Enumerates each value of this vertex buffer as numbers.
  30010. * @param count the number of values to enumerate
  30011. * @param callback the callback function called for each value
  30012. */
  30013. VertexBuffer.prototype.forEach = function (count, callback) {
  30014. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30015. };
  30016. Object.defineProperty(VertexBuffer, "PositionKind", {
  30017. get: function () {
  30018. return VertexBuffer._PositionKind;
  30019. },
  30020. enumerable: true,
  30021. configurable: true
  30022. });
  30023. Object.defineProperty(VertexBuffer, "NormalKind", {
  30024. get: function () {
  30025. return VertexBuffer._NormalKind;
  30026. },
  30027. enumerable: true,
  30028. configurable: true
  30029. });
  30030. Object.defineProperty(VertexBuffer, "TangentKind", {
  30031. get: function () {
  30032. return VertexBuffer._TangentKind;
  30033. },
  30034. enumerable: true,
  30035. configurable: true
  30036. });
  30037. Object.defineProperty(VertexBuffer, "UVKind", {
  30038. get: function () {
  30039. return VertexBuffer._UVKind;
  30040. },
  30041. enumerable: true,
  30042. configurable: true
  30043. });
  30044. Object.defineProperty(VertexBuffer, "UV2Kind", {
  30045. get: function () {
  30046. return VertexBuffer._UV2Kind;
  30047. },
  30048. enumerable: true,
  30049. configurable: true
  30050. });
  30051. Object.defineProperty(VertexBuffer, "UV3Kind", {
  30052. get: function () {
  30053. return VertexBuffer._UV3Kind;
  30054. },
  30055. enumerable: true,
  30056. configurable: true
  30057. });
  30058. Object.defineProperty(VertexBuffer, "UV4Kind", {
  30059. get: function () {
  30060. return VertexBuffer._UV4Kind;
  30061. },
  30062. enumerable: true,
  30063. configurable: true
  30064. });
  30065. Object.defineProperty(VertexBuffer, "UV5Kind", {
  30066. get: function () {
  30067. return VertexBuffer._UV5Kind;
  30068. },
  30069. enumerable: true,
  30070. configurable: true
  30071. });
  30072. Object.defineProperty(VertexBuffer, "UV6Kind", {
  30073. get: function () {
  30074. return VertexBuffer._UV6Kind;
  30075. },
  30076. enumerable: true,
  30077. configurable: true
  30078. });
  30079. Object.defineProperty(VertexBuffer, "ColorKind", {
  30080. get: function () {
  30081. return VertexBuffer._ColorKind;
  30082. },
  30083. enumerable: true,
  30084. configurable: true
  30085. });
  30086. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  30087. get: function () {
  30088. return VertexBuffer._MatricesIndicesKind;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30094. get: function () {
  30095. return VertexBuffer._MatricesWeightsKind;
  30096. },
  30097. enumerable: true,
  30098. configurable: true
  30099. });
  30100. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30101. get: function () {
  30102. return VertexBuffer._MatricesIndicesExtraKind;
  30103. },
  30104. enumerable: true,
  30105. configurable: true
  30106. });
  30107. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30108. get: function () {
  30109. return VertexBuffer._MatricesWeightsExtraKind;
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. /**
  30115. * Deduces the stride given a kind.
  30116. * @param kind The kind string to deduce
  30117. * @returns The deduced stride
  30118. */
  30119. VertexBuffer.DeduceStride = function (kind) {
  30120. switch (kind) {
  30121. case VertexBuffer.UVKind:
  30122. case VertexBuffer.UV2Kind:
  30123. case VertexBuffer.UV3Kind:
  30124. case VertexBuffer.UV4Kind:
  30125. case VertexBuffer.UV5Kind:
  30126. case VertexBuffer.UV6Kind:
  30127. return 2;
  30128. case VertexBuffer.NormalKind:
  30129. case VertexBuffer.PositionKind:
  30130. return 3;
  30131. case VertexBuffer.ColorKind:
  30132. case VertexBuffer.MatricesIndicesKind:
  30133. case VertexBuffer.MatricesIndicesExtraKind:
  30134. case VertexBuffer.MatricesWeightsKind:
  30135. case VertexBuffer.MatricesWeightsExtraKind:
  30136. case VertexBuffer.TangentKind:
  30137. return 4;
  30138. default:
  30139. throw new Error("Invalid kind '" + kind + "'");
  30140. }
  30141. };
  30142. /**
  30143. * Gets the byte length of the given type.
  30144. * @param type the type
  30145. * @returns the number of bytes
  30146. */
  30147. VertexBuffer.GetTypeByteLength = function (type) {
  30148. switch (type) {
  30149. case VertexBuffer.BYTE:
  30150. case VertexBuffer.UNSIGNED_BYTE:
  30151. return 1;
  30152. case VertexBuffer.SHORT:
  30153. case VertexBuffer.UNSIGNED_SHORT:
  30154. return 2;
  30155. case VertexBuffer.INT:
  30156. case VertexBuffer.FLOAT:
  30157. return 4;
  30158. default:
  30159. throw new Error("Invalid type '" + type + "'");
  30160. }
  30161. };
  30162. /**
  30163. * Enumerates each value of the given parameters as numbers.
  30164. * @param data the data to enumerate
  30165. * @param byteOffset the byte offset of the data
  30166. * @param byteStride the byte stride of the data
  30167. * @param componentCount the number of components per element
  30168. * @param componentType the type of the component
  30169. * @param count the total number of components
  30170. * @param normalized whether the data is normalized
  30171. * @param callback the callback function called for each value
  30172. */
  30173. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30174. if (data instanceof Array) {
  30175. var offset = byteOffset / 4;
  30176. var stride = byteStride / 4;
  30177. for (var index = 0; index < count; index += componentCount) {
  30178. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30179. callback(data[offset + componentIndex], index + componentIndex);
  30180. }
  30181. offset += stride;
  30182. }
  30183. }
  30184. else {
  30185. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30186. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30187. for (var index = 0; index < count; index += componentCount) {
  30188. var componentByteOffset = byteOffset;
  30189. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30190. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30191. callback(value, index + componentIndex);
  30192. componentByteOffset += componentByteLength;
  30193. }
  30194. byteOffset += byteStride;
  30195. }
  30196. }
  30197. };
  30198. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30199. switch (type) {
  30200. case VertexBuffer.BYTE: {
  30201. var value = dataView.getInt8(byteOffset);
  30202. if (normalized) {
  30203. value = Math.max(value / 127, -1);
  30204. }
  30205. return value;
  30206. }
  30207. case VertexBuffer.UNSIGNED_BYTE: {
  30208. var value = dataView.getUint8(byteOffset);
  30209. if (normalized) {
  30210. value = value / 255;
  30211. }
  30212. return value;
  30213. }
  30214. case VertexBuffer.SHORT: {
  30215. var value = dataView.getInt16(byteOffset, true);
  30216. if (normalized) {
  30217. value = Math.max(value / 16383, -1);
  30218. }
  30219. return value;
  30220. }
  30221. case VertexBuffer.UNSIGNED_SHORT: {
  30222. var value = dataView.getUint16(byteOffset, true);
  30223. if (normalized) {
  30224. value = value / 65535;
  30225. }
  30226. return value;
  30227. }
  30228. case VertexBuffer.FLOAT: {
  30229. return dataView.getFloat32(byteOffset, true);
  30230. }
  30231. default: {
  30232. throw new Error("Invalid component type " + type);
  30233. }
  30234. }
  30235. };
  30236. /**
  30237. * The byte type.
  30238. */
  30239. VertexBuffer.BYTE = 5120;
  30240. /**
  30241. * The unsigned byte type.
  30242. */
  30243. VertexBuffer.UNSIGNED_BYTE = 5121;
  30244. /**
  30245. * The short type.
  30246. */
  30247. VertexBuffer.SHORT = 5122;
  30248. /**
  30249. * The unsigned short type.
  30250. */
  30251. VertexBuffer.UNSIGNED_SHORT = 5123;
  30252. /**
  30253. * The integer type.
  30254. */
  30255. VertexBuffer.INT = 5124;
  30256. /**
  30257. * The unsigned integer type.
  30258. */
  30259. VertexBuffer.UNSIGNED_INT = 5125;
  30260. /**
  30261. * The float type.
  30262. */
  30263. VertexBuffer.FLOAT = 5126;
  30264. // Enums
  30265. VertexBuffer._PositionKind = "position";
  30266. VertexBuffer._NormalKind = "normal";
  30267. VertexBuffer._TangentKind = "tangent";
  30268. VertexBuffer._UVKind = "uv";
  30269. VertexBuffer._UV2Kind = "uv2";
  30270. VertexBuffer._UV3Kind = "uv3";
  30271. VertexBuffer._UV4Kind = "uv4";
  30272. VertexBuffer._UV5Kind = "uv5";
  30273. VertexBuffer._UV6Kind = "uv6";
  30274. VertexBuffer._ColorKind = "color";
  30275. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30276. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30277. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30278. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30279. return VertexBuffer;
  30280. }());
  30281. BABYLON.VertexBuffer = VertexBuffer;
  30282. })(BABYLON || (BABYLON = {}));
  30283. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30284. var BABYLON;
  30285. (function (BABYLON) {
  30286. /**
  30287. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30288. */
  30289. var DummyInternalTextureTracker = /** @class */ (function () {
  30290. function DummyInternalTextureTracker() {
  30291. /**
  30292. * Gets or set the previous tracker in the list
  30293. */
  30294. this.previous = null;
  30295. /**
  30296. * Gets or set the next tracker in the list
  30297. */
  30298. this.next = null;
  30299. }
  30300. return DummyInternalTextureTracker;
  30301. }());
  30302. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30303. })(BABYLON || (BABYLON = {}));
  30304. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30305. var BABYLON;
  30306. (function (BABYLON) {
  30307. /**
  30308. * Class used to store data associated with WebGL texture data for the engine
  30309. * This class should not be used directly
  30310. */
  30311. var InternalTexture = /** @class */ (function () {
  30312. /**
  30313. * Creates a new InternalTexture
  30314. * @param engine defines the engine to use
  30315. * @param dataSource defines the type of data that will be used
  30316. */
  30317. function InternalTexture(engine, dataSource) {
  30318. /**
  30319. * Observable called when the texture is loaded
  30320. */
  30321. this.onLoadedObservable = new BABYLON.Observable();
  30322. /**
  30323. * Gets or set the previous tracker in the list
  30324. */
  30325. this.previous = null;
  30326. /**
  30327. * Gets or set the next tracker in the list
  30328. */
  30329. this.next = null;
  30330. // Private
  30331. /** @hidden */
  30332. this._initialSlot = -1;
  30333. /** @hidden */
  30334. this._designatedSlot = -1;
  30335. /** @hidden */
  30336. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30337. /** @hidden */
  30338. this._comparisonFunction = 0;
  30339. /** @hidden */
  30340. this._lodGenerationScale = 0;
  30341. /** @hidden */
  30342. this._lodGenerationOffset = 0;
  30343. /** @hidden */
  30344. this._isRGBD = false;
  30345. /** @hidden */
  30346. this._references = 1;
  30347. this._engine = engine;
  30348. this._dataSource = dataSource;
  30349. this._webGLTexture = engine._createTexture();
  30350. }
  30351. /**
  30352. * Gets the Engine the texture belongs to.
  30353. * @returns The babylon engine
  30354. */
  30355. InternalTexture.prototype.getEngine = function () {
  30356. return this._engine;
  30357. };
  30358. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30359. /**
  30360. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30361. */
  30362. get: function () {
  30363. return this._dataSource;
  30364. },
  30365. enumerable: true,
  30366. configurable: true
  30367. });
  30368. /**
  30369. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30370. */
  30371. InternalTexture.prototype.incrementReferences = function () {
  30372. this._references++;
  30373. };
  30374. /**
  30375. * Change the size of the texture (not the size of the content)
  30376. * @param width defines the new width
  30377. * @param height defines the new height
  30378. * @param depth defines the new depth (1 by default)
  30379. */
  30380. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30381. if (depth === void 0) { depth = 1; }
  30382. this.width = width;
  30383. this.height = height;
  30384. this.depth = depth;
  30385. this.baseWidth = width;
  30386. this.baseHeight = height;
  30387. this.baseDepth = depth;
  30388. this._size = width * height * depth;
  30389. };
  30390. /** @hidden */
  30391. InternalTexture.prototype._rebuild = function () {
  30392. var _this = this;
  30393. var proxy;
  30394. this.isReady = false;
  30395. this._cachedCoordinatesMode = null;
  30396. this._cachedWrapU = null;
  30397. this._cachedWrapV = null;
  30398. this._cachedAnisotropicFilteringLevel = null;
  30399. switch (this._dataSource) {
  30400. case InternalTexture.DATASOURCE_TEMP:
  30401. return;
  30402. case InternalTexture.DATASOURCE_URL:
  30403. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30404. _this.isReady = true;
  30405. }, null, this._buffer, undefined, this.format);
  30406. proxy._swapAndDie(this);
  30407. return;
  30408. case InternalTexture.DATASOURCE_RAW:
  30409. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30410. proxy._swapAndDie(this);
  30411. this.isReady = true;
  30412. return;
  30413. case InternalTexture.DATASOURCE_RAW3D:
  30414. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30415. proxy._swapAndDie(this);
  30416. this.isReady = true;
  30417. return;
  30418. case InternalTexture.DATASOURCE_DYNAMIC:
  30419. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30420. proxy._swapAndDie(this);
  30421. // The engine will make sure to update content so no need to flag it as isReady = true
  30422. return;
  30423. case InternalTexture.DATASOURCE_RENDERTARGET:
  30424. var options = new BABYLON.RenderTargetCreationOptions();
  30425. options.generateDepthBuffer = this._generateDepthBuffer;
  30426. options.generateMipMaps = this.generateMipMaps;
  30427. options.generateStencilBuffer = this._generateStencilBuffer;
  30428. options.samplingMode = this.samplingMode;
  30429. options.type = this.type;
  30430. if (this.isCube) {
  30431. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30432. }
  30433. else {
  30434. var size = {
  30435. width: this.width,
  30436. height: this.height
  30437. };
  30438. proxy = this._engine.createRenderTargetTexture(size, options);
  30439. }
  30440. proxy._swapAndDie(this);
  30441. this.isReady = true;
  30442. return;
  30443. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30444. var depthTextureOptions = {
  30445. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30446. comparisonFunction: this._comparisonFunction,
  30447. generateStencil: this._generateStencilBuffer,
  30448. isCube: this.isCube
  30449. };
  30450. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30451. proxy._swapAndDie(this);
  30452. this.isReady = true;
  30453. return;
  30454. case InternalTexture.DATASOURCE_CUBE:
  30455. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30456. _this.isReady = true;
  30457. }, null, this.format, this._extension);
  30458. proxy._swapAndDie(this);
  30459. return;
  30460. case InternalTexture.DATASOURCE_CUBERAW:
  30461. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30462. proxy._swapAndDie(this);
  30463. this.isReady = true;
  30464. return;
  30465. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30466. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30467. if (proxy) {
  30468. proxy._swapAndDie(_this);
  30469. }
  30470. _this.isReady = true;
  30471. }, null, this.format, this._extension);
  30472. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30473. return;
  30474. }
  30475. };
  30476. InternalTexture.prototype._swapAndDie = function (target) {
  30477. target._webGLTexture = this._webGLTexture;
  30478. if (this._framebuffer) {
  30479. target._framebuffer = this._framebuffer;
  30480. }
  30481. if (this._depthStencilBuffer) {
  30482. target._depthStencilBuffer = this._depthStencilBuffer;
  30483. }
  30484. if (this._lodTextureHigh) {
  30485. if (target._lodTextureHigh) {
  30486. target._lodTextureHigh.dispose();
  30487. }
  30488. target._lodTextureHigh = this._lodTextureHigh;
  30489. }
  30490. if (this._lodTextureMid) {
  30491. if (target._lodTextureMid) {
  30492. target._lodTextureMid.dispose();
  30493. }
  30494. target._lodTextureMid = this._lodTextureMid;
  30495. }
  30496. if (this._lodTextureLow) {
  30497. if (target._lodTextureLow) {
  30498. target._lodTextureLow.dispose();
  30499. }
  30500. target._lodTextureLow = this._lodTextureLow;
  30501. }
  30502. var cache = this._engine.getLoadedTexturesCache();
  30503. var index = cache.indexOf(this);
  30504. if (index !== -1) {
  30505. cache.splice(index, 1);
  30506. }
  30507. };
  30508. /**
  30509. * Dispose the current allocated resources
  30510. */
  30511. InternalTexture.prototype.dispose = function () {
  30512. if (!this._webGLTexture) {
  30513. return;
  30514. }
  30515. this._references--;
  30516. if (this._references === 0) {
  30517. this._engine._releaseTexture(this);
  30518. this._webGLTexture = null;
  30519. this.previous = null;
  30520. this.next = null;
  30521. }
  30522. };
  30523. /**
  30524. * The source of the texture data is unknown
  30525. */
  30526. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30527. /**
  30528. * Texture data comes from an URL
  30529. */
  30530. InternalTexture.DATASOURCE_URL = 1;
  30531. /**
  30532. * Texture data is only used for temporary storage
  30533. */
  30534. InternalTexture.DATASOURCE_TEMP = 2;
  30535. /**
  30536. * Texture data comes from raw data (ArrayBuffer)
  30537. */
  30538. InternalTexture.DATASOURCE_RAW = 3;
  30539. /**
  30540. * Texture content is dynamic (video or dynamic texture)
  30541. */
  30542. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30543. /**
  30544. * Texture content is generated by rendering to it
  30545. */
  30546. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30547. /**
  30548. * Texture content is part of a multi render target process
  30549. */
  30550. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30551. /**
  30552. * Texture data comes from a cube data file
  30553. */
  30554. InternalTexture.DATASOURCE_CUBE = 7;
  30555. /**
  30556. * Texture data comes from a raw cube data
  30557. */
  30558. InternalTexture.DATASOURCE_CUBERAW = 8;
  30559. /**
  30560. * Texture data come from a prefiltered cube data file
  30561. */
  30562. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30563. /**
  30564. * Texture content is raw 3D data
  30565. */
  30566. InternalTexture.DATASOURCE_RAW3D = 10;
  30567. /**
  30568. * Texture content is a depth texture
  30569. */
  30570. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30571. return InternalTexture;
  30572. }());
  30573. BABYLON.InternalTexture = InternalTexture;
  30574. })(BABYLON || (BABYLON = {}));
  30575. //# sourceMappingURL=babylon.internalTexture.js.map
  30576. var BABYLON;
  30577. (function (BABYLON) {
  30578. var BaseTexture = /** @class */ (function () {
  30579. function BaseTexture(scene) {
  30580. this._hasAlpha = false;
  30581. this.getAlphaFromRGB = false;
  30582. this.level = 1;
  30583. this.coordinatesIndex = 0;
  30584. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30585. /**
  30586. * | Value | Type | Description |
  30587. * | ----- | ------------------ | ----------- |
  30588. * | 0 | CLAMP_ADDRESSMODE | |
  30589. * | 1 | WRAP_ADDRESSMODE | |
  30590. * | 2 | MIRROR_ADDRESSMODE | |
  30591. */
  30592. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30593. /**
  30594. * | Value | Type | Description |
  30595. * | ----- | ------------------ | ----------- |
  30596. * | 0 | CLAMP_ADDRESSMODE | |
  30597. * | 1 | WRAP_ADDRESSMODE | |
  30598. * | 2 | MIRROR_ADDRESSMODE | |
  30599. */
  30600. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30601. /**
  30602. * | Value | Type | Description |
  30603. * | ----- | ------------------ | ----------- |
  30604. * | 0 | CLAMP_ADDRESSMODE | |
  30605. * | 1 | WRAP_ADDRESSMODE | |
  30606. * | 2 | MIRROR_ADDRESSMODE | |
  30607. */
  30608. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30609. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30610. this.isCube = false;
  30611. this.is3D = false;
  30612. this.gammaSpace = true;
  30613. this.invertZ = false;
  30614. this.lodLevelInAlpha = false;
  30615. this.isRenderTarget = false;
  30616. this.animations = new Array();
  30617. /**
  30618. * An event triggered when the texture is disposed.
  30619. */
  30620. this.onDisposeObservable = new BABYLON.Observable();
  30621. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30622. this._cachedSize = BABYLON.Size.Zero();
  30623. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30624. if (this._scene) {
  30625. this._scene.textures.push(this);
  30626. }
  30627. this._uid = null;
  30628. }
  30629. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30630. get: function () {
  30631. return this._hasAlpha;
  30632. },
  30633. set: function (value) {
  30634. if (this._hasAlpha === value) {
  30635. return;
  30636. }
  30637. this._hasAlpha = value;
  30638. if (this._scene) {
  30639. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30640. }
  30641. },
  30642. enumerable: true,
  30643. configurable: true
  30644. });
  30645. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30646. get: function () {
  30647. return this._coordinatesMode;
  30648. },
  30649. /**
  30650. * How a texture is mapped.
  30651. *
  30652. * | Value | Type | Description |
  30653. * | ----- | ----------------------------------- | ----------- |
  30654. * | 0 | EXPLICIT_MODE | |
  30655. * | 1 | SPHERICAL_MODE | |
  30656. * | 2 | PLANAR_MODE | |
  30657. * | 3 | CUBIC_MODE | |
  30658. * | 4 | PROJECTION_MODE | |
  30659. * | 5 | SKYBOX_MODE | |
  30660. * | 6 | INVCUBIC_MODE | |
  30661. * | 7 | EQUIRECTANGULAR_MODE | |
  30662. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30663. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30664. */
  30665. set: function (value) {
  30666. if (this._coordinatesMode === value) {
  30667. return;
  30668. }
  30669. this._coordinatesMode = value;
  30670. if (this._scene) {
  30671. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30672. }
  30673. },
  30674. enumerable: true,
  30675. configurable: true
  30676. });
  30677. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30678. /**
  30679. * Gets whether or not the texture contains RGBD data.
  30680. */
  30681. get: function () {
  30682. return this._texture != null && this._texture._isRGBD;
  30683. },
  30684. enumerable: true,
  30685. configurable: true
  30686. });
  30687. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30688. get: function () {
  30689. if (this._texture)
  30690. return this._texture._lodGenerationOffset;
  30691. return 0.0;
  30692. },
  30693. set: function (value) {
  30694. if (this._texture)
  30695. this._texture._lodGenerationOffset = value;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30701. get: function () {
  30702. if (this._texture)
  30703. return this._texture._lodGenerationScale;
  30704. return 0.0;
  30705. },
  30706. set: function (value) {
  30707. if (this._texture)
  30708. this._texture._lodGenerationScale = value;
  30709. },
  30710. enumerable: true,
  30711. configurable: true
  30712. });
  30713. Object.defineProperty(BaseTexture.prototype, "uid", {
  30714. get: function () {
  30715. if (!this._uid) {
  30716. this._uid = BABYLON.Tools.RandomId();
  30717. }
  30718. return this._uid;
  30719. },
  30720. enumerable: true,
  30721. configurable: true
  30722. });
  30723. BaseTexture.prototype.toString = function () {
  30724. return this.name;
  30725. };
  30726. BaseTexture.prototype.getClassName = function () {
  30727. return "BaseTexture";
  30728. };
  30729. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30730. set: function (callback) {
  30731. if (this._onDisposeObserver) {
  30732. this.onDisposeObservable.remove(this._onDisposeObserver);
  30733. }
  30734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30740. get: function () {
  30741. return true;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. BaseTexture.prototype.getScene = function () {
  30747. return this._scene;
  30748. };
  30749. BaseTexture.prototype.getTextureMatrix = function () {
  30750. return BABYLON.Matrix.IdentityReadOnly;
  30751. };
  30752. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30753. return BABYLON.Matrix.IdentityReadOnly;
  30754. };
  30755. BaseTexture.prototype.getInternalTexture = function () {
  30756. return this._texture;
  30757. };
  30758. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30759. return !this.isBlocking || this.isReady();
  30760. };
  30761. BaseTexture.prototype.isReady = function () {
  30762. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30763. this.delayLoad();
  30764. return false;
  30765. }
  30766. if (this._texture) {
  30767. return this._texture.isReady;
  30768. }
  30769. return false;
  30770. };
  30771. BaseTexture.prototype.getSize = function () {
  30772. if (this._texture) {
  30773. if (this._texture.width) {
  30774. this._cachedSize.width = this._texture.width;
  30775. this._cachedSize.height = this._texture.height;
  30776. return this._cachedSize;
  30777. }
  30778. if (this._texture._size) {
  30779. this._cachedSize.width = this._texture._size;
  30780. this._cachedSize.height = this._texture._size;
  30781. return this._cachedSize;
  30782. }
  30783. }
  30784. return this._cachedSize;
  30785. };
  30786. BaseTexture.prototype.getBaseSize = function () {
  30787. if (!this.isReady() || !this._texture)
  30788. return BABYLON.Size.Zero();
  30789. if (this._texture._size) {
  30790. return new BABYLON.Size(this._texture._size, this._texture._size);
  30791. }
  30792. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30793. };
  30794. BaseTexture.prototype.scale = function (ratio) {
  30795. };
  30796. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30797. get: function () {
  30798. return false;
  30799. },
  30800. enumerable: true,
  30801. configurable: true
  30802. });
  30803. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30804. if (!this._scene) {
  30805. return null;
  30806. }
  30807. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30808. for (var index = 0; index < texturesCache.length; index++) {
  30809. var texturesCacheEntry = texturesCache[index];
  30810. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30811. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30812. texturesCacheEntry.incrementReferences();
  30813. return texturesCacheEntry;
  30814. }
  30815. }
  30816. }
  30817. return null;
  30818. };
  30819. BaseTexture.prototype._rebuild = function () {
  30820. };
  30821. BaseTexture.prototype.delayLoad = function () {
  30822. };
  30823. BaseTexture.prototype.clone = function () {
  30824. return null;
  30825. };
  30826. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30827. get: function () {
  30828. if (!this._texture) {
  30829. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30830. }
  30831. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30837. get: function () {
  30838. if (!this._texture) {
  30839. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30840. }
  30841. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30842. },
  30843. enumerable: true,
  30844. configurable: true
  30845. });
  30846. /**
  30847. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30848. * This will returns an RGBA array buffer containing either in values (0-255) or
  30849. * float values (0-1) depending of the underlying buffer type.
  30850. * @param faceIndex The face of the texture to read (in case of cube texture)
  30851. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30852. * @returns The Array buffer containing the pixels data.
  30853. */
  30854. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30855. if (faceIndex === void 0) { faceIndex = 0; }
  30856. if (level === void 0) { level = 0; }
  30857. if (!this._texture) {
  30858. return null;
  30859. }
  30860. var size = this.getSize();
  30861. var width = size.width;
  30862. var height = size.height;
  30863. var scene = this.getScene();
  30864. if (!scene) {
  30865. return null;
  30866. }
  30867. var engine = scene.getEngine();
  30868. if (level != 0) {
  30869. width = width / Math.pow(2, level);
  30870. height = height / Math.pow(2, level);
  30871. width = Math.round(width);
  30872. height = Math.round(height);
  30873. }
  30874. if (this._texture.isCube) {
  30875. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30876. }
  30877. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30878. };
  30879. BaseTexture.prototype.releaseInternalTexture = function () {
  30880. if (this._texture) {
  30881. this._texture.dispose();
  30882. this._texture = null;
  30883. }
  30884. };
  30885. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30886. get: function () {
  30887. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30888. return null;
  30889. }
  30890. if (!this._texture._sphericalPolynomial) {
  30891. this._texture._sphericalPolynomial =
  30892. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30893. }
  30894. return this._texture._sphericalPolynomial;
  30895. },
  30896. set: function (value) {
  30897. if (this._texture) {
  30898. this._texture._sphericalPolynomial = value;
  30899. }
  30900. },
  30901. enumerable: true,
  30902. configurable: true
  30903. });
  30904. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30905. get: function () {
  30906. if (this._texture) {
  30907. return this._texture._lodTextureHigh;
  30908. }
  30909. return null;
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30915. get: function () {
  30916. if (this._texture) {
  30917. return this._texture._lodTextureMid;
  30918. }
  30919. return null;
  30920. },
  30921. enumerable: true,
  30922. configurable: true
  30923. });
  30924. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30925. get: function () {
  30926. if (this._texture) {
  30927. return this._texture._lodTextureLow;
  30928. }
  30929. return null;
  30930. },
  30931. enumerable: true,
  30932. configurable: true
  30933. });
  30934. BaseTexture.prototype.dispose = function () {
  30935. if (!this._scene) {
  30936. return;
  30937. }
  30938. // Animations
  30939. this._scene.stopAnimation(this);
  30940. // Remove from scene
  30941. this._scene._removePendingData(this);
  30942. var index = this._scene.textures.indexOf(this);
  30943. if (index >= 0) {
  30944. this._scene.textures.splice(index, 1);
  30945. }
  30946. if (this._texture === undefined) {
  30947. return;
  30948. }
  30949. // Release
  30950. this.releaseInternalTexture();
  30951. // Callback
  30952. this.onDisposeObservable.notifyObservers(this);
  30953. this.onDisposeObservable.clear();
  30954. };
  30955. BaseTexture.prototype.serialize = function () {
  30956. if (!this.name) {
  30957. return null;
  30958. }
  30959. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30960. // Animations
  30961. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30962. return serializationObject;
  30963. };
  30964. BaseTexture.WhenAllReady = function (textures, callback) {
  30965. var numRemaining = textures.length;
  30966. if (numRemaining === 0) {
  30967. callback();
  30968. return;
  30969. }
  30970. var _loop_1 = function () {
  30971. texture = textures[i];
  30972. if (texture.isReady()) {
  30973. if (--numRemaining === 0) {
  30974. callback();
  30975. }
  30976. }
  30977. else {
  30978. onLoadObservable = texture.onLoadObservable;
  30979. var onLoadCallback_1 = function () {
  30980. onLoadObservable.removeCallback(onLoadCallback_1);
  30981. if (--numRemaining === 0) {
  30982. callback();
  30983. }
  30984. };
  30985. onLoadObservable.add(onLoadCallback_1);
  30986. }
  30987. };
  30988. var texture, onLoadObservable;
  30989. for (var i = 0; i < textures.length; i++) {
  30990. _loop_1();
  30991. }
  30992. };
  30993. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30994. __decorate([
  30995. BABYLON.serialize()
  30996. ], BaseTexture.prototype, "name", void 0);
  30997. __decorate([
  30998. BABYLON.serialize("hasAlpha")
  30999. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31000. __decorate([
  31001. BABYLON.serialize()
  31002. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31003. __decorate([
  31004. BABYLON.serialize()
  31005. ], BaseTexture.prototype, "level", void 0);
  31006. __decorate([
  31007. BABYLON.serialize()
  31008. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31009. __decorate([
  31010. BABYLON.serialize("coordinatesMode")
  31011. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31012. __decorate([
  31013. BABYLON.serialize()
  31014. ], BaseTexture.prototype, "wrapU", void 0);
  31015. __decorate([
  31016. BABYLON.serialize()
  31017. ], BaseTexture.prototype, "wrapV", void 0);
  31018. __decorate([
  31019. BABYLON.serialize()
  31020. ], BaseTexture.prototype, "wrapR", void 0);
  31021. __decorate([
  31022. BABYLON.serialize()
  31023. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31024. __decorate([
  31025. BABYLON.serialize()
  31026. ], BaseTexture.prototype, "isCube", void 0);
  31027. __decorate([
  31028. BABYLON.serialize()
  31029. ], BaseTexture.prototype, "is3D", void 0);
  31030. __decorate([
  31031. BABYLON.serialize()
  31032. ], BaseTexture.prototype, "gammaSpace", void 0);
  31033. __decorate([
  31034. BABYLON.serialize()
  31035. ], BaseTexture.prototype, "invertZ", void 0);
  31036. __decorate([
  31037. BABYLON.serialize()
  31038. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31039. __decorate([
  31040. BABYLON.serialize()
  31041. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31042. __decorate([
  31043. BABYLON.serialize()
  31044. ], BaseTexture.prototype, "lodGenerationScale", null);
  31045. __decorate([
  31046. BABYLON.serialize()
  31047. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31048. return BaseTexture;
  31049. }());
  31050. BABYLON.BaseTexture = BaseTexture;
  31051. })(BABYLON || (BABYLON = {}));
  31052. //# sourceMappingURL=babylon.baseTexture.js.map
  31053. var BABYLON;
  31054. (function (BABYLON) {
  31055. var Texture = /** @class */ (function (_super) {
  31056. __extends(Texture, _super);
  31057. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31058. if (noMipmap === void 0) { noMipmap = false; }
  31059. if (invertY === void 0) { invertY = true; }
  31060. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31061. if (onLoad === void 0) { onLoad = null; }
  31062. if (onError === void 0) { onError = null; }
  31063. if (buffer === void 0) { buffer = null; }
  31064. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31065. var _this = _super.call(this, scene) || this;
  31066. _this.uOffset = 0;
  31067. _this.vOffset = 0;
  31068. _this.uScale = 1.0;
  31069. _this.vScale = 1.0;
  31070. _this.uAng = 0;
  31071. _this.vAng = 0;
  31072. _this.wAng = 0;
  31073. /**
  31074. * Defines the center of rotation (U)
  31075. */
  31076. _this.uRotationCenter = 0.5;
  31077. /**
  31078. * Defines the center of rotation (V)
  31079. */
  31080. _this.vRotationCenter = 0.5;
  31081. /**
  31082. * Defines the center of rotation (W)
  31083. */
  31084. _this.wRotationCenter = 0.5;
  31085. _this._isBlocking = true;
  31086. _this.name = url || "";
  31087. _this.url = url;
  31088. _this._noMipmap = noMipmap;
  31089. _this._invertY = invertY;
  31090. _this._samplingMode = samplingMode;
  31091. _this._buffer = buffer;
  31092. _this._deleteBuffer = deleteBuffer;
  31093. if (format) {
  31094. _this._format = format;
  31095. }
  31096. scene = _this.getScene();
  31097. if (!scene) {
  31098. return _this;
  31099. }
  31100. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31101. var load = function () {
  31102. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31103. _this.onLoadObservable.notifyObservers(_this);
  31104. }
  31105. if (onLoad) {
  31106. onLoad();
  31107. }
  31108. if (!_this.isBlocking && scene) {
  31109. scene.resetCachedMaterial();
  31110. }
  31111. };
  31112. if (!_this.url) {
  31113. _this._delayedOnLoad = load;
  31114. _this._delayedOnError = onError;
  31115. return _this;
  31116. }
  31117. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31118. if (!_this._texture) {
  31119. if (!scene.useDelayedTextureLoading) {
  31120. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31121. if (deleteBuffer) {
  31122. delete _this._buffer;
  31123. }
  31124. }
  31125. else {
  31126. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31127. _this._delayedOnLoad = load;
  31128. _this._delayedOnError = onError;
  31129. }
  31130. }
  31131. else {
  31132. if (_this._texture.isReady) {
  31133. BABYLON.Tools.SetImmediate(function () { return load(); });
  31134. }
  31135. else {
  31136. _this._texture.onLoadedObservable.add(load);
  31137. }
  31138. }
  31139. return _this;
  31140. }
  31141. Object.defineProperty(Texture.prototype, "noMipmap", {
  31142. get: function () {
  31143. return this._noMipmap;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Texture.prototype, "isBlocking", {
  31149. get: function () {
  31150. return this._isBlocking;
  31151. },
  31152. set: function (value) {
  31153. this._isBlocking = value;
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Texture.prototype, "samplingMode", {
  31159. get: function () {
  31160. return this._samplingMode;
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. /**
  31166. * Update the url (and optional buffer) of this texture if url was null during construction.
  31167. * @param url the url of the texture
  31168. * @param buffer the buffer of the texture (defaults to null)
  31169. */
  31170. Texture.prototype.updateURL = function (url, buffer) {
  31171. if (buffer === void 0) { buffer = null; }
  31172. if (this.url) {
  31173. throw new Error("URL is already set");
  31174. }
  31175. this.url = url;
  31176. this._buffer = buffer;
  31177. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31178. this.delayLoad();
  31179. };
  31180. Texture.prototype.delayLoad = function () {
  31181. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31182. return;
  31183. }
  31184. var scene = this.getScene();
  31185. if (!scene) {
  31186. return;
  31187. }
  31188. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31189. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31190. if (!this._texture) {
  31191. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31192. if (this._deleteBuffer) {
  31193. delete this._buffer;
  31194. }
  31195. }
  31196. else {
  31197. if (this._delayedOnLoad) {
  31198. if (this._texture.isReady) {
  31199. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31200. }
  31201. else {
  31202. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31203. }
  31204. }
  31205. }
  31206. this._delayedOnLoad = null;
  31207. this._delayedOnError = null;
  31208. };
  31209. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31210. if (!this._texture) {
  31211. return;
  31212. }
  31213. var scene = this.getScene();
  31214. if (!scene) {
  31215. return;
  31216. }
  31217. this._samplingMode = samplingMode;
  31218. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31219. };
  31220. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31221. x *= this.uScale;
  31222. y *= this.vScale;
  31223. x -= this.uRotationCenter * this.uScale;
  31224. y -= this.vRotationCenter * this.vScale;
  31225. z -= this.wRotationCenter;
  31226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31227. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31228. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31229. t.z += this.wRotationCenter;
  31230. };
  31231. Texture.prototype.getTextureMatrix = function () {
  31232. var _this = this;
  31233. if (this.uOffset === this._cachedUOffset &&
  31234. this.vOffset === this._cachedVOffset &&
  31235. this.uScale === this._cachedUScale &&
  31236. this.vScale === this._cachedVScale &&
  31237. this.uAng === this._cachedUAng &&
  31238. this.vAng === this._cachedVAng &&
  31239. this.wAng === this._cachedWAng) {
  31240. return this._cachedTextureMatrix;
  31241. }
  31242. this._cachedUOffset = this.uOffset;
  31243. this._cachedVOffset = this.vOffset;
  31244. this._cachedUScale = this.uScale;
  31245. this._cachedVScale = this.vScale;
  31246. this._cachedUAng = this.uAng;
  31247. this._cachedVAng = this.vAng;
  31248. this._cachedWAng = this.wAng;
  31249. if (!this._cachedTextureMatrix) {
  31250. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31251. this._rowGenerationMatrix = new BABYLON.Matrix();
  31252. this._t0 = BABYLON.Vector3.Zero();
  31253. this._t1 = BABYLON.Vector3.Zero();
  31254. this._t2 = BABYLON.Vector3.Zero();
  31255. }
  31256. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31257. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31258. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31259. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31260. this._t1.subtractInPlace(this._t0);
  31261. this._t2.subtractInPlace(this._t0);
  31262. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31263. this._cachedTextureMatrix.m[0] = this._t1.x;
  31264. this._cachedTextureMatrix.m[1] = this._t1.y;
  31265. this._cachedTextureMatrix.m[2] = this._t1.z;
  31266. this._cachedTextureMatrix.m[4] = this._t2.x;
  31267. this._cachedTextureMatrix.m[5] = this._t2.y;
  31268. this._cachedTextureMatrix.m[6] = this._t2.z;
  31269. this._cachedTextureMatrix.m[8] = this._t0.x;
  31270. this._cachedTextureMatrix.m[9] = this._t0.y;
  31271. this._cachedTextureMatrix.m[10] = this._t0.z;
  31272. var scene = this.getScene();
  31273. if (!scene) {
  31274. return this._cachedTextureMatrix;
  31275. }
  31276. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31277. return mat.hasTexture(_this);
  31278. });
  31279. return this._cachedTextureMatrix;
  31280. };
  31281. Texture.prototype.getReflectionTextureMatrix = function () {
  31282. var _this = this;
  31283. var scene = this.getScene();
  31284. if (!scene) {
  31285. return this._cachedTextureMatrix;
  31286. }
  31287. if (this.uOffset === this._cachedUOffset &&
  31288. this.vOffset === this._cachedVOffset &&
  31289. this.uScale === this._cachedUScale &&
  31290. this.vScale === this._cachedVScale &&
  31291. this.coordinatesMode === this._cachedCoordinatesMode) {
  31292. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31293. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31294. return this._cachedTextureMatrix;
  31295. }
  31296. }
  31297. else {
  31298. return this._cachedTextureMatrix;
  31299. }
  31300. }
  31301. if (!this._cachedTextureMatrix) {
  31302. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31303. }
  31304. if (!this._projectionModeMatrix) {
  31305. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31306. }
  31307. this._cachedUOffset = this.uOffset;
  31308. this._cachedVOffset = this.vOffset;
  31309. this._cachedUScale = this.uScale;
  31310. this._cachedVScale = this.vScale;
  31311. this._cachedCoordinatesMode = this.coordinatesMode;
  31312. switch (this.coordinatesMode) {
  31313. case Texture.PLANAR_MODE:
  31314. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31315. this._cachedTextureMatrix[0] = this.uScale;
  31316. this._cachedTextureMatrix[5] = this.vScale;
  31317. this._cachedTextureMatrix[12] = this.uOffset;
  31318. this._cachedTextureMatrix[13] = this.vOffset;
  31319. break;
  31320. case Texture.PROJECTION_MODE:
  31321. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31322. this._projectionModeMatrix.m[0] = 0.5;
  31323. this._projectionModeMatrix.m[5] = -0.5;
  31324. this._projectionModeMatrix.m[10] = 0.0;
  31325. this._projectionModeMatrix.m[12] = 0.5;
  31326. this._projectionModeMatrix.m[13] = 0.5;
  31327. this._projectionModeMatrix.m[14] = 1.0;
  31328. this._projectionModeMatrix.m[15] = 1.0;
  31329. var projectionMatrix = scene.getProjectionMatrix();
  31330. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31331. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31332. break;
  31333. default:
  31334. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31335. break;
  31336. }
  31337. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31338. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31339. });
  31340. return this._cachedTextureMatrix;
  31341. };
  31342. Texture.prototype.clone = function () {
  31343. var _this = this;
  31344. return BABYLON.SerializationHelper.Clone(function () {
  31345. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31346. }, this);
  31347. };
  31348. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31349. get: function () {
  31350. if (!this._onLoadObservable) {
  31351. this._onLoadObservable = new BABYLON.Observable();
  31352. }
  31353. return this._onLoadObservable;
  31354. },
  31355. enumerable: true,
  31356. configurable: true
  31357. });
  31358. Texture.prototype.serialize = function () {
  31359. var serializationObject = _super.prototype.serialize.call(this);
  31360. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31361. serializationObject.base64String = this._buffer;
  31362. serializationObject.name = serializationObject.name.replace("data:", "");
  31363. }
  31364. serializationObject.invertY = this._invertY;
  31365. serializationObject.samplingMode = this.samplingMode;
  31366. return serializationObject;
  31367. };
  31368. Texture.prototype.getClassName = function () {
  31369. return "Texture";
  31370. };
  31371. Texture.prototype.dispose = function () {
  31372. _super.prototype.dispose.call(this);
  31373. if (this._onLoadObservable) {
  31374. this._onLoadObservable.clear();
  31375. this._onLoadObservable = null;
  31376. }
  31377. this._delayedOnLoad = null;
  31378. this._delayedOnError = null;
  31379. };
  31380. // Statics
  31381. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31382. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31383. if (onLoad === void 0) { onLoad = null; }
  31384. if (onError === void 0) { onError = null; }
  31385. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31386. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31387. };
  31388. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31389. if (parsedTexture.customType) {
  31390. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31391. // Update Sampling Mode
  31392. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31393. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31394. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31395. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31396. }
  31397. }
  31398. return parsedCustomTexture;
  31399. }
  31400. if (parsedTexture.isCube) {
  31401. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31402. }
  31403. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31404. return null;
  31405. }
  31406. var texture = BABYLON.SerializationHelper.Parse(function () {
  31407. var generateMipMaps = true;
  31408. if (parsedTexture.noMipmap) {
  31409. generateMipMaps = false;
  31410. }
  31411. if (parsedTexture.mirrorPlane) {
  31412. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31413. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31414. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31415. return mirrorTexture;
  31416. }
  31417. else if (parsedTexture.isRenderTarget) {
  31418. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31419. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31420. return renderTargetTexture;
  31421. }
  31422. else {
  31423. var texture;
  31424. if (parsedTexture.base64String) {
  31425. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31426. }
  31427. else {
  31428. var url = rootUrl + parsedTexture.name;
  31429. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31430. url = parsedTexture.url;
  31431. }
  31432. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31433. }
  31434. return texture;
  31435. }
  31436. }, parsedTexture, scene);
  31437. // Update Sampling Mode
  31438. if (parsedTexture.samplingMode) {
  31439. var sampling = parsedTexture.samplingMode;
  31440. if (texture._samplingMode !== sampling) {
  31441. texture.updateSamplingMode(sampling);
  31442. }
  31443. }
  31444. // Animations
  31445. if (parsedTexture.animations) {
  31446. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31447. var parsedAnimation = parsedTexture.animations[animationIndex];
  31448. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31449. }
  31450. }
  31451. return texture;
  31452. };
  31453. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31454. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31455. if (noMipmap === void 0) { noMipmap = false; }
  31456. if (invertY === void 0) { invertY = true; }
  31457. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31458. if (onLoad === void 0) { onLoad = null; }
  31459. if (onError === void 0) { onError = null; }
  31460. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31461. if (name.substr(0, 5) !== "data:") {
  31462. name = "data:" + name;
  31463. }
  31464. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31465. };
  31466. // Constants
  31467. Texture.NEAREST_SAMPLINGMODE = 1;
  31468. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31469. Texture.BILINEAR_SAMPLINGMODE = 2;
  31470. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31471. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31472. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31473. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31474. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31475. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31476. Texture.NEAREST_LINEAR = 7;
  31477. Texture.NEAREST_NEAREST = 8;
  31478. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31479. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31480. Texture.LINEAR_LINEAR = 11;
  31481. Texture.LINEAR_NEAREST = 12;
  31482. Texture.EXPLICIT_MODE = 0;
  31483. Texture.SPHERICAL_MODE = 1;
  31484. Texture.PLANAR_MODE = 2;
  31485. Texture.CUBIC_MODE = 3;
  31486. Texture.PROJECTION_MODE = 4;
  31487. Texture.SKYBOX_MODE = 5;
  31488. Texture.INVCUBIC_MODE = 6;
  31489. Texture.EQUIRECTANGULAR_MODE = 7;
  31490. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31491. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31492. Texture.CLAMP_ADDRESSMODE = 0;
  31493. Texture.WRAP_ADDRESSMODE = 1;
  31494. Texture.MIRROR_ADDRESSMODE = 2;
  31495. /**
  31496. * 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
  31497. */
  31498. Texture.UseSerializedUrlIfAny = false;
  31499. __decorate([
  31500. BABYLON.serialize()
  31501. ], Texture.prototype, "url", void 0);
  31502. __decorate([
  31503. BABYLON.serialize()
  31504. ], Texture.prototype, "uOffset", void 0);
  31505. __decorate([
  31506. BABYLON.serialize()
  31507. ], Texture.prototype, "vOffset", void 0);
  31508. __decorate([
  31509. BABYLON.serialize()
  31510. ], Texture.prototype, "uScale", void 0);
  31511. __decorate([
  31512. BABYLON.serialize()
  31513. ], Texture.prototype, "vScale", void 0);
  31514. __decorate([
  31515. BABYLON.serialize()
  31516. ], Texture.prototype, "uAng", void 0);
  31517. __decorate([
  31518. BABYLON.serialize()
  31519. ], Texture.prototype, "vAng", void 0);
  31520. __decorate([
  31521. BABYLON.serialize()
  31522. ], Texture.prototype, "wAng", void 0);
  31523. __decorate([
  31524. BABYLON.serialize()
  31525. ], Texture.prototype, "uRotationCenter", void 0);
  31526. __decorate([
  31527. BABYLON.serialize()
  31528. ], Texture.prototype, "vRotationCenter", void 0);
  31529. __decorate([
  31530. BABYLON.serialize()
  31531. ], Texture.prototype, "wRotationCenter", void 0);
  31532. __decorate([
  31533. BABYLON.serialize()
  31534. ], Texture.prototype, "isBlocking", null);
  31535. return Texture;
  31536. }(BABYLON.BaseTexture));
  31537. BABYLON.Texture = Texture;
  31538. })(BABYLON || (BABYLON = {}));
  31539. //# sourceMappingURL=babylon.texture.js.map
  31540. var BABYLON;
  31541. (function (BABYLON) {
  31542. /**
  31543. * @hidden
  31544. **/
  31545. var _InstancesBatch = /** @class */ (function () {
  31546. function _InstancesBatch() {
  31547. this.mustReturn = false;
  31548. this.visibleInstances = new Array();
  31549. this.renderSelf = new Array();
  31550. }
  31551. return _InstancesBatch;
  31552. }());
  31553. BABYLON._InstancesBatch = _InstancesBatch;
  31554. var Mesh = /** @class */ (function (_super) {
  31555. __extends(Mesh, _super);
  31556. /**
  31557. * @constructor
  31558. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31559. * @param {Scene} scene The scene to add this mesh to.
  31560. * @param {Node} parent The parent of this mesh, if it has one
  31561. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31562. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31563. * When false, achieved by calling a clone(), also passing False.
  31564. * This will make creation of children, recursive.
  31565. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31566. */
  31567. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31568. if (scene === void 0) { scene = null; }
  31569. if (parent === void 0) { parent = null; }
  31570. if (source === void 0) { source = null; }
  31571. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31572. var _this = _super.call(this, name, scene) || this;
  31573. // Events
  31574. /**
  31575. * An event triggered before rendering the mesh
  31576. */
  31577. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31578. /**
  31579. * An event triggered after rendering the mesh
  31580. */
  31581. _this.onAfterRenderObservable = new BABYLON.Observable();
  31582. /**
  31583. * An event triggered before drawing the mesh
  31584. */
  31585. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31586. // Members
  31587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31588. _this.instances = new Array();
  31589. _this._LODLevels = new Array();
  31590. _this._visibleInstances = {};
  31591. _this._renderIdForInstances = new Array();
  31592. _this._batchCache = new _InstancesBatch();
  31593. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31594. // Use by builder only to know what orientation were the mesh build in.
  31595. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31596. _this.overrideMaterialSideOrientation = null;
  31597. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31598. // Will be used to save a source mesh reference, If any
  31599. _this._source = null;
  31600. scene = _this.getScene();
  31601. if (source) {
  31602. // Geometry
  31603. if (source._geometry) {
  31604. source._geometry.applyToMesh(_this);
  31605. }
  31606. // Deep copy
  31607. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31608. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31609. // Source mesh
  31610. _this._source = source;
  31611. // Metadata
  31612. if (source.metadata && source.metadata.clone) {
  31613. _this.metadata = source.metadata.clone();
  31614. }
  31615. else {
  31616. _this.metadata = source.metadata;
  31617. }
  31618. // Tags
  31619. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31620. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31621. }
  31622. // Parent
  31623. _this.parent = source.parent;
  31624. // Pivot
  31625. _this.setPivotMatrix(source.getPivotMatrix());
  31626. _this.id = name + "." + source.id;
  31627. // Material
  31628. _this.material = source.material;
  31629. var index;
  31630. if (!doNotCloneChildren) {
  31631. // Children
  31632. var directDescendants = source.getDescendants(true);
  31633. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31634. var child = directDescendants[index_1];
  31635. if (child.clone) {
  31636. child.clone(name + "." + child.name, _this);
  31637. }
  31638. }
  31639. }
  31640. // Physics clone
  31641. var physicsEngine = _this.getScene().getPhysicsEngine();
  31642. if (clonePhysicsImpostor && physicsEngine) {
  31643. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31644. if (impostor) {
  31645. _this.physicsImpostor = impostor.clone(_this);
  31646. }
  31647. }
  31648. // Particles
  31649. for (index = 0; index < scene.particleSystems.length; index++) {
  31650. var system = scene.particleSystems[index];
  31651. if (system.emitter === source) {
  31652. system.clone(system.name, _this);
  31653. }
  31654. }
  31655. _this.refreshBoundingInfo();
  31656. _this.computeWorldMatrix(true);
  31657. }
  31658. // Parent
  31659. if (parent !== null) {
  31660. _this.parent = parent;
  31661. }
  31662. return _this;
  31663. }
  31664. Object.defineProperty(Mesh, "FRONTSIDE", {
  31665. /**
  31666. * Mesh side orientation : usually the external or front surface
  31667. */
  31668. get: function () {
  31669. return Mesh._FRONTSIDE;
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(Mesh, "BACKSIDE", {
  31675. /**
  31676. * Mesh side orientation : usually the internal or back surface
  31677. */
  31678. get: function () {
  31679. return Mesh._BACKSIDE;
  31680. },
  31681. enumerable: true,
  31682. configurable: true
  31683. });
  31684. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31685. /**
  31686. * Mesh side orientation : both internal and external or front and back surfaces
  31687. */
  31688. get: function () {
  31689. return Mesh._DOUBLESIDE;
  31690. },
  31691. enumerable: true,
  31692. configurable: true
  31693. });
  31694. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31695. /**
  31696. * Mesh side orientation : by default, `FRONTSIDE`
  31697. */
  31698. get: function () {
  31699. return Mesh._DEFAULTSIDE;
  31700. },
  31701. enumerable: true,
  31702. configurable: true
  31703. });
  31704. Object.defineProperty(Mesh, "NO_CAP", {
  31705. /**
  31706. * Mesh cap setting : no cap
  31707. */
  31708. get: function () {
  31709. return Mesh._NO_CAP;
  31710. },
  31711. enumerable: true,
  31712. configurable: true
  31713. });
  31714. Object.defineProperty(Mesh, "CAP_START", {
  31715. /**
  31716. * Mesh cap setting : one cap at the beginning of the mesh
  31717. */
  31718. get: function () {
  31719. return Mesh._CAP_START;
  31720. },
  31721. enumerable: true,
  31722. configurable: true
  31723. });
  31724. Object.defineProperty(Mesh, "CAP_END", {
  31725. /**
  31726. * Mesh cap setting : one cap at the end of the mesh
  31727. */
  31728. get: function () {
  31729. return Mesh._CAP_END;
  31730. },
  31731. enumerable: true,
  31732. configurable: true
  31733. });
  31734. Object.defineProperty(Mesh, "CAP_ALL", {
  31735. /**
  31736. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31737. */
  31738. get: function () {
  31739. return Mesh._CAP_ALL;
  31740. },
  31741. enumerable: true,
  31742. configurable: true
  31743. });
  31744. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31745. set: function (callback) {
  31746. if (this._onBeforeDrawObserver) {
  31747. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31748. }
  31749. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31750. },
  31751. enumerable: true,
  31752. configurable: true
  31753. });
  31754. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31755. get: function () {
  31756. return this._morphTargetManager;
  31757. },
  31758. set: function (value) {
  31759. if (this._morphTargetManager === value) {
  31760. return;
  31761. }
  31762. this._morphTargetManager = value;
  31763. this._syncGeometryWithMorphTargetManager();
  31764. },
  31765. enumerable: true,
  31766. configurable: true
  31767. });
  31768. Object.defineProperty(Mesh.prototype, "source", {
  31769. get: function () {
  31770. return this._source;
  31771. },
  31772. enumerable: true,
  31773. configurable: true
  31774. });
  31775. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31776. get: function () {
  31777. return this._unIndexed;
  31778. },
  31779. set: function (value) {
  31780. if (this._unIndexed !== value) {
  31781. this._unIndexed = value;
  31782. this._markSubMeshesAsAttributesDirty();
  31783. }
  31784. },
  31785. enumerable: true,
  31786. configurable: true
  31787. });
  31788. // Methods
  31789. /**
  31790. * Returns the string "Mesh".
  31791. */
  31792. Mesh.prototype.getClassName = function () {
  31793. return "Mesh";
  31794. };
  31795. /**
  31796. * Returns a string.
  31797. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31798. */
  31799. Mesh.prototype.toString = function (fullDetails) {
  31800. var ret = _super.prototype.toString.call(this, fullDetails);
  31801. ret += ", n vertices: " + this.getTotalVertices();
  31802. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31803. if (this.animations) {
  31804. for (var i = 0; i < this.animations.length; i++) {
  31805. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31806. }
  31807. }
  31808. if (fullDetails) {
  31809. if (this._geometry) {
  31810. var ib = this.getIndices();
  31811. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31812. if (vb && ib) {
  31813. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31814. }
  31815. }
  31816. else {
  31817. ret += ", flat shading: UNKNOWN";
  31818. }
  31819. }
  31820. return ret;
  31821. };
  31822. Mesh.prototype._unBindEffect = function () {
  31823. _super.prototype._unBindEffect.call(this);
  31824. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31825. var instance = _a[_i];
  31826. instance._unBindEffect();
  31827. }
  31828. };
  31829. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31830. /**
  31831. * True if the mesh has some Levels Of Details (LOD).
  31832. * Returns a boolean.
  31833. */
  31834. get: function () {
  31835. return this._LODLevels.length > 0;
  31836. },
  31837. enumerable: true,
  31838. configurable: true
  31839. });
  31840. /**
  31841. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31842. * @returns an array of {BABYLON.MeshLODLevel}
  31843. */
  31844. Mesh.prototype.getLODLevels = function () {
  31845. return this._LODLevels;
  31846. };
  31847. Mesh.prototype._sortLODLevels = function () {
  31848. this._LODLevels.sort(function (a, b) {
  31849. if (a.distance < b.distance) {
  31850. return 1;
  31851. }
  31852. if (a.distance > b.distance) {
  31853. return -1;
  31854. }
  31855. return 0;
  31856. });
  31857. };
  31858. /**
  31859. * Add a mesh as LOD level triggered at the given distance.
  31860. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31861. * @param distance The distance from the center of the object to show this level
  31862. * @param mesh The mesh to be added as LOD level (can be null)
  31863. * @return This mesh (for chaining)
  31864. */
  31865. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31866. if (mesh && mesh._masterMesh) {
  31867. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31868. return this;
  31869. }
  31870. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31871. this._LODLevels.push(level);
  31872. if (mesh) {
  31873. mesh._masterMesh = this;
  31874. }
  31875. this._sortLODLevels();
  31876. return this;
  31877. };
  31878. /**
  31879. * Returns the LOD level mesh at the passed distance or null if not found.
  31880. * It is related to the method `addLODLevel(distance, mesh)`.
  31881. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31882. * Returns an object Mesh or `null`.
  31883. */
  31884. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31885. for (var index = 0; index < this._LODLevels.length; index++) {
  31886. var level = this._LODLevels[index];
  31887. if (level.distance === distance) {
  31888. return level.mesh;
  31889. }
  31890. }
  31891. return null;
  31892. };
  31893. /**
  31894. * Remove a mesh from the LOD array
  31895. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31896. * @param {Mesh} mesh The mesh to be removed.
  31897. * @return {Mesh} This mesh (for chaining)
  31898. */
  31899. Mesh.prototype.removeLODLevel = function (mesh) {
  31900. for (var index = 0; index < this._LODLevels.length; index++) {
  31901. if (this._LODLevels[index].mesh === mesh) {
  31902. this._LODLevels.splice(index, 1);
  31903. if (mesh) {
  31904. mesh._masterMesh = null;
  31905. }
  31906. }
  31907. }
  31908. this._sortLODLevels();
  31909. return this;
  31910. };
  31911. /**
  31912. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31913. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31914. */
  31915. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31916. if (!this._LODLevels || this._LODLevels.length === 0) {
  31917. return this;
  31918. }
  31919. var bSphere;
  31920. if (boundingSphere) {
  31921. bSphere = boundingSphere;
  31922. }
  31923. else {
  31924. var boundingInfo = this.getBoundingInfo();
  31925. bSphere = boundingInfo.boundingSphere;
  31926. }
  31927. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31928. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31929. if (this.onLODLevelSelection) {
  31930. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31931. }
  31932. return this;
  31933. }
  31934. for (var index = 0; index < this._LODLevels.length; index++) {
  31935. var level = this._LODLevels[index];
  31936. if (level.distance < distanceToCamera) {
  31937. if (level.mesh) {
  31938. level.mesh._preActivate();
  31939. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31940. }
  31941. if (this.onLODLevelSelection) {
  31942. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31943. }
  31944. return level.mesh;
  31945. }
  31946. }
  31947. if (this.onLODLevelSelection) {
  31948. this.onLODLevelSelection(distanceToCamera, this, this);
  31949. }
  31950. return this;
  31951. };
  31952. Object.defineProperty(Mesh.prototype, "geometry", {
  31953. /**
  31954. * Returns the mesh internal Geometry object.
  31955. */
  31956. get: function () {
  31957. return this._geometry;
  31958. },
  31959. enumerable: true,
  31960. configurable: true
  31961. });
  31962. /**
  31963. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31964. */
  31965. Mesh.prototype.getTotalVertices = function () {
  31966. if (this._geometry === null || this._geometry === undefined) {
  31967. return 0;
  31968. }
  31969. return this._geometry.getTotalVertices();
  31970. };
  31971. /**
  31972. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31973. * 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.
  31974. * You can force the copy with forceCopy === true
  31975. * Returns null if the mesh has no geometry or no vertex buffer.
  31976. * Possible `kind` values :
  31977. * - BABYLON.VertexBuffer.PositionKind
  31978. * - BABYLON.VertexBuffer.UVKind
  31979. * - BABYLON.VertexBuffer.UV2Kind
  31980. * - BABYLON.VertexBuffer.UV3Kind
  31981. * - BABYLON.VertexBuffer.UV4Kind
  31982. * - BABYLON.VertexBuffer.UV5Kind
  31983. * - BABYLON.VertexBuffer.UV6Kind
  31984. * - BABYLON.VertexBuffer.ColorKind
  31985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31989. */
  31990. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31991. if (!this._geometry) {
  31992. return null;
  31993. }
  31994. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31995. };
  31996. /**
  31997. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31998. * Returns `null` if the mesh has no geometry.
  31999. * Possible `kind` values :
  32000. * - BABYLON.VertexBuffer.PositionKind
  32001. * - BABYLON.VertexBuffer.UVKind
  32002. * - BABYLON.VertexBuffer.UV2Kind
  32003. * - BABYLON.VertexBuffer.UV3Kind
  32004. * - BABYLON.VertexBuffer.UV4Kind
  32005. * - BABYLON.VertexBuffer.UV5Kind
  32006. * - BABYLON.VertexBuffer.UV6Kind
  32007. * - BABYLON.VertexBuffer.ColorKind
  32008. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32009. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32010. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32011. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32012. */
  32013. Mesh.prototype.getVertexBuffer = function (kind) {
  32014. if (!this._geometry) {
  32015. return null;
  32016. }
  32017. return this._geometry.getVertexBuffer(kind);
  32018. };
  32019. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32020. if (!this._geometry) {
  32021. if (this._delayInfo) {
  32022. return this._delayInfo.indexOf(kind) !== -1;
  32023. }
  32024. return false;
  32025. }
  32026. return this._geometry.isVerticesDataPresent(kind);
  32027. };
  32028. /**
  32029. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32030. * Possible `kind` values :
  32031. * - BABYLON.VertexBuffer.PositionKind
  32032. * - BABYLON.VertexBuffer.UVKind
  32033. * - BABYLON.VertexBuffer.UV2Kind
  32034. * - BABYLON.VertexBuffer.UV3Kind
  32035. * - BABYLON.VertexBuffer.UV4Kind
  32036. * - BABYLON.VertexBuffer.UV5Kind
  32037. * - BABYLON.VertexBuffer.UV6Kind
  32038. * - BABYLON.VertexBuffer.ColorKind
  32039. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32040. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32041. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32042. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32043. */
  32044. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32045. if (!this._geometry) {
  32046. if (this._delayInfo) {
  32047. return this._delayInfo.indexOf(kind) !== -1;
  32048. }
  32049. return false;
  32050. }
  32051. return this._geometry.isVertexBufferUpdatable(kind);
  32052. };
  32053. /**
  32054. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  32055. * Possible `kind` values :
  32056. * - BABYLON.VertexBuffer.PositionKind
  32057. * - BABYLON.VertexBuffer.UVKind
  32058. * - BABYLON.VertexBuffer.UV2Kind
  32059. * - BABYLON.VertexBuffer.UV3Kind
  32060. * - BABYLON.VertexBuffer.UV4Kind
  32061. * - BABYLON.VertexBuffer.UV5Kind
  32062. * - BABYLON.VertexBuffer.UV6Kind
  32063. * - BABYLON.VertexBuffer.ColorKind
  32064. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32065. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32066. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32067. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32068. */
  32069. Mesh.prototype.getVerticesDataKinds = function () {
  32070. if (!this._geometry) {
  32071. var result = new Array();
  32072. if (this._delayInfo) {
  32073. this._delayInfo.forEach(function (kind, index, array) {
  32074. result.push(kind);
  32075. });
  32076. }
  32077. return result;
  32078. }
  32079. return this._geometry.getVerticesDataKinds();
  32080. };
  32081. /**
  32082. * Returns a positive integer : the total number of indices in this mesh geometry.
  32083. * Returns zero if the mesh has no geometry.
  32084. */
  32085. Mesh.prototype.getTotalIndices = function () {
  32086. if (!this._geometry) {
  32087. return 0;
  32088. }
  32089. return this._geometry.getTotalIndices();
  32090. };
  32091. /**
  32092. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32093. * 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.
  32094. * Returns an empty array if the mesh has no geometry.
  32095. */
  32096. Mesh.prototype.getIndices = function (copyWhenShared) {
  32097. if (!this._geometry) {
  32098. return [];
  32099. }
  32100. return this._geometry.getIndices(copyWhenShared);
  32101. };
  32102. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32103. get: function () {
  32104. return this._masterMesh !== null && this._masterMesh !== undefined;
  32105. },
  32106. enumerable: true,
  32107. configurable: true
  32108. });
  32109. /**
  32110. * Determine if the current mesh is ready to be rendered
  32111. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32112. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32113. * @returns true if all associated assets are ready (material, textures, shaders)
  32114. */
  32115. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32116. if (completeCheck === void 0) { completeCheck = false; }
  32117. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32118. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32119. return false;
  32120. }
  32121. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32122. return false;
  32123. }
  32124. if (!this.subMeshes || this.subMeshes.length === 0) {
  32125. return true;
  32126. }
  32127. if (!completeCheck) {
  32128. return true;
  32129. }
  32130. var engine = this.getEngine();
  32131. var scene = this.getScene();
  32132. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32133. this.computeWorldMatrix();
  32134. var mat = this.material || scene.defaultMaterial;
  32135. if (mat) {
  32136. if (mat.storeEffectOnSubMeshes) {
  32137. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32138. var subMesh = _a[_i];
  32139. var effectiveMaterial = subMesh.getMaterial();
  32140. if (effectiveMaterial) {
  32141. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32142. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32143. return false;
  32144. }
  32145. }
  32146. else {
  32147. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32148. return false;
  32149. }
  32150. }
  32151. }
  32152. }
  32153. }
  32154. else {
  32155. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32156. return false;
  32157. }
  32158. }
  32159. }
  32160. // Shadows
  32161. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32162. var light = _c[_b];
  32163. var generator = light.getShadowGenerator();
  32164. if (generator) {
  32165. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32166. var subMesh = _e[_d];
  32167. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32168. return false;
  32169. }
  32170. }
  32171. }
  32172. }
  32173. // LOD
  32174. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32175. var lod = _g[_f];
  32176. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32177. return false;
  32178. }
  32179. }
  32180. return true;
  32181. };
  32182. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32183. /**
  32184. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32185. * This property is pertinent only for updatable parametric shapes.
  32186. */
  32187. get: function () {
  32188. return this._areNormalsFrozen;
  32189. },
  32190. enumerable: true,
  32191. configurable: true
  32192. });
  32193. /**
  32194. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32195. * It has no effect at all on other shapes.
  32196. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32197. * Returns the Mesh.
  32198. */
  32199. Mesh.prototype.freezeNormals = function () {
  32200. this._areNormalsFrozen = true;
  32201. return this;
  32202. };
  32203. /**
  32204. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32205. * It has no effect at all on other shapes.
  32206. * It reactivates the mesh normals computation if it was previously frozen.
  32207. * Returns the Mesh.
  32208. */
  32209. Mesh.prototype.unfreezeNormals = function () {
  32210. this._areNormalsFrozen = false;
  32211. return this;
  32212. };
  32213. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32214. /**
  32215. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32216. */
  32217. set: function (count) {
  32218. this._overridenInstanceCount = count;
  32219. },
  32220. enumerable: true,
  32221. configurable: true
  32222. });
  32223. // Methods
  32224. Mesh.prototype._preActivate = function () {
  32225. var sceneRenderId = this.getScene().getRenderId();
  32226. if (this._preActivateId === sceneRenderId) {
  32227. return this;
  32228. }
  32229. this._preActivateId = sceneRenderId;
  32230. this._visibleInstances = null;
  32231. return this;
  32232. };
  32233. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32234. if (this._visibleInstances) {
  32235. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32236. }
  32237. return this;
  32238. };
  32239. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32240. if (!this._visibleInstances) {
  32241. this._visibleInstances = {};
  32242. this._visibleInstances.defaultRenderId = renderId;
  32243. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32244. }
  32245. if (!this._visibleInstances[renderId]) {
  32246. this._visibleInstances[renderId] = new Array();
  32247. }
  32248. this._visibleInstances[renderId].push(instance);
  32249. return this;
  32250. };
  32251. /**
  32252. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32253. * This means the mesh underlying bounding box and sphere are recomputed.
  32254. * Returns the Mesh.
  32255. */
  32256. Mesh.prototype.refreshBoundingInfo = function () {
  32257. return this._refreshBoundingInfo(false);
  32258. };
  32259. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32260. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32261. return this;
  32262. }
  32263. var data = this._getPositionData(applySkeleton);
  32264. if (data) {
  32265. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32266. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32267. }
  32268. if (this.subMeshes) {
  32269. for (var index = 0; index < this.subMeshes.length; index++) {
  32270. this.subMeshes[index].refreshBoundingInfo();
  32271. }
  32272. }
  32273. this._updateBoundingInfo();
  32274. return this;
  32275. };
  32276. Mesh.prototype._getPositionData = function (applySkeleton) {
  32277. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32278. if (data && applySkeleton && this.skeleton) {
  32279. data = BABYLON.Tools.Slice(data);
  32280. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32281. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32282. if (matricesWeightsData && matricesIndicesData) {
  32283. var needExtras = this.numBoneInfluencers > 4;
  32284. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32285. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32286. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32287. var tempVector = BABYLON.Tmp.Vector3[0];
  32288. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32289. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32290. var matWeightIdx = 0;
  32291. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32292. finalMatrix.reset();
  32293. var inf;
  32294. var weight;
  32295. for (inf = 0; inf < 4; inf++) {
  32296. weight = matricesWeightsData[matWeightIdx + inf];
  32297. if (weight <= 0)
  32298. break;
  32299. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32300. finalMatrix.addToSelf(tempMatrix);
  32301. }
  32302. if (needExtras) {
  32303. for (inf = 0; inf < 4; inf++) {
  32304. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32305. if (weight <= 0)
  32306. break;
  32307. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32308. finalMatrix.addToSelf(tempMatrix);
  32309. }
  32310. }
  32311. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32312. tempVector.toArray(data, index);
  32313. }
  32314. }
  32315. }
  32316. return data;
  32317. };
  32318. Mesh.prototype._createGlobalSubMesh = function (force) {
  32319. var totalVertices = this.getTotalVertices();
  32320. if (!totalVertices || !this.getIndices()) {
  32321. return null;
  32322. }
  32323. // Check if we need to recreate the submeshes
  32324. if (this.subMeshes && this.subMeshes.length > 0) {
  32325. var ib = this.getIndices();
  32326. if (!ib) {
  32327. return null;
  32328. }
  32329. var totalIndices = ib.length;
  32330. var needToRecreate = false;
  32331. if (force) {
  32332. needToRecreate = true;
  32333. }
  32334. else {
  32335. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32336. var submesh = _a[_i];
  32337. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32338. needToRecreate = true;
  32339. break;
  32340. }
  32341. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32342. needToRecreate = true;
  32343. break;
  32344. }
  32345. }
  32346. }
  32347. if (!needToRecreate) {
  32348. return this.subMeshes[0];
  32349. }
  32350. }
  32351. this.releaseSubMeshes();
  32352. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32353. };
  32354. Mesh.prototype.subdivide = function (count) {
  32355. if (count < 1) {
  32356. return;
  32357. }
  32358. var totalIndices = this.getTotalIndices();
  32359. var subdivisionSize = (totalIndices / count) | 0;
  32360. var offset = 0;
  32361. // Ensure that subdivisionSize is a multiple of 3
  32362. while (subdivisionSize % 3 !== 0) {
  32363. subdivisionSize++;
  32364. }
  32365. this.releaseSubMeshes();
  32366. for (var index = 0; index < count; index++) {
  32367. if (offset >= totalIndices) {
  32368. break;
  32369. }
  32370. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32371. offset += subdivisionSize;
  32372. }
  32373. this.synchronizeInstances();
  32374. };
  32375. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32376. if (updatable === void 0) { updatable = false; }
  32377. if (!this._geometry) {
  32378. var vertexData = new BABYLON.VertexData();
  32379. vertexData.set(data, kind);
  32380. var scene = this.getScene();
  32381. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32382. }
  32383. else {
  32384. this._geometry.setVerticesData(kind, data, updatable, stride);
  32385. }
  32386. return this;
  32387. };
  32388. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32389. if (updatable === void 0) { updatable = true; }
  32390. var vb = this.getVertexBuffer(kind);
  32391. if (!vb || vb.isUpdatable() === updatable) {
  32392. return;
  32393. }
  32394. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32395. };
  32396. /**
  32397. * Sets the mesh VertexBuffer.
  32398. * Returns the Mesh.
  32399. */
  32400. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32401. if (!this._geometry) {
  32402. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32403. }
  32404. this._geometry.setVerticesBuffer(buffer);
  32405. return this;
  32406. };
  32407. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32408. if (!this._geometry) {
  32409. return this;
  32410. }
  32411. if (!makeItUnique) {
  32412. this._geometry.updateVerticesData(kind, data, updateExtends);
  32413. }
  32414. else {
  32415. this.makeGeometryUnique();
  32416. this.updateVerticesData(kind, data, updateExtends, false);
  32417. }
  32418. return this;
  32419. };
  32420. /**
  32421. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32422. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32423. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32424. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32425. * Returns the Mesh.
  32426. */
  32427. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32428. if (computeNormals === void 0) { computeNormals = true; }
  32429. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32430. if (!positions) {
  32431. return this;
  32432. }
  32433. positionFunction(positions);
  32434. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32435. if (computeNormals) {
  32436. var indices = this.getIndices();
  32437. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32438. if (!normals) {
  32439. return this;
  32440. }
  32441. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32442. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32443. }
  32444. return this;
  32445. };
  32446. /**
  32447. * Creates a un-shared specific occurence of the geometry for the mesh.
  32448. * Returns the Mesh.
  32449. */
  32450. Mesh.prototype.makeGeometryUnique = function () {
  32451. if (!this._geometry) {
  32452. return this;
  32453. }
  32454. var oldGeometry = this._geometry;
  32455. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32456. oldGeometry.releaseForMesh(this, true);
  32457. geometry.applyToMesh(this);
  32458. return this;
  32459. };
  32460. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32461. if (totalVertices === void 0) { totalVertices = null; }
  32462. if (updatable === void 0) { updatable = false; }
  32463. if (!this._geometry) {
  32464. var vertexData = new BABYLON.VertexData();
  32465. vertexData.indices = indices;
  32466. var scene = this.getScene();
  32467. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32468. }
  32469. else {
  32470. this._geometry.setIndices(indices, totalVertices, updatable);
  32471. }
  32472. return this;
  32473. };
  32474. /**
  32475. * Update the current index buffer
  32476. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32477. * Returns the Mesh.
  32478. */
  32479. Mesh.prototype.updateIndices = function (indices, offset) {
  32480. if (!this._geometry) {
  32481. return this;
  32482. }
  32483. this._geometry.updateIndices(indices, offset);
  32484. return this;
  32485. };
  32486. /**
  32487. * Invert the geometry to move from a right handed system to a left handed one.
  32488. * Returns the Mesh.
  32489. */
  32490. Mesh.prototype.toLeftHanded = function () {
  32491. if (!this._geometry) {
  32492. return this;
  32493. }
  32494. this._geometry.toLeftHanded();
  32495. return this;
  32496. };
  32497. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32498. if (!this._geometry) {
  32499. return this;
  32500. }
  32501. var engine = this.getScene().getEngine();
  32502. // Wireframe
  32503. var indexToBind;
  32504. if (this._unIndexed) {
  32505. indexToBind = null;
  32506. }
  32507. else {
  32508. switch (fillMode) {
  32509. case BABYLON.Material.PointFillMode:
  32510. indexToBind = null;
  32511. break;
  32512. case BABYLON.Material.WireFrameFillMode:
  32513. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32514. break;
  32515. default:
  32516. case BABYLON.Material.TriangleFillMode:
  32517. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32518. break;
  32519. }
  32520. }
  32521. // VBOs
  32522. this._geometry._bind(effect, indexToBind);
  32523. return this;
  32524. };
  32525. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32526. if (alternate === void 0) { alternate = false; }
  32527. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32528. return this;
  32529. }
  32530. this.onBeforeDrawObservable.notifyObservers(this);
  32531. var scene = this.getScene();
  32532. var engine = scene.getEngine();
  32533. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32534. // or triangles as points
  32535. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32536. }
  32537. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32538. // Triangles as wireframe
  32539. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32540. }
  32541. else {
  32542. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32543. }
  32544. if (scene._isAlternateRenderingEnabled && !alternate) {
  32545. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32546. if (!effect || !scene.activeCamera) {
  32547. return this;
  32548. }
  32549. scene._switchToAlternateCameraConfiguration(true);
  32550. this._effectiveMaterial.bindView(effect);
  32551. this._effectiveMaterial.bindViewProjection(effect);
  32552. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32553. this._draw(subMesh, fillMode, instancesCount, true);
  32554. engine.setViewport(scene.activeCamera.viewport);
  32555. scene._switchToAlternateCameraConfiguration(false);
  32556. this._effectiveMaterial.bindView(effect);
  32557. this._effectiveMaterial.bindViewProjection(effect);
  32558. }
  32559. return this;
  32560. };
  32561. /**
  32562. * Registers for this mesh a javascript function called just before the rendering process.
  32563. * This function is passed the current mesh.
  32564. * Return the Mesh.
  32565. */
  32566. Mesh.prototype.registerBeforeRender = function (func) {
  32567. this.onBeforeRenderObservable.add(func);
  32568. return this;
  32569. };
  32570. /**
  32571. * Disposes a previously registered javascript function called before the rendering.
  32572. * This function is passed the current mesh.
  32573. * Returns the Mesh.
  32574. */
  32575. Mesh.prototype.unregisterBeforeRender = function (func) {
  32576. this.onBeforeRenderObservable.removeCallback(func);
  32577. return this;
  32578. };
  32579. /**
  32580. * Registers for this mesh a javascript function called just after the rendering is complete.
  32581. * This function is passed the current mesh.
  32582. * Returns the Mesh.
  32583. */
  32584. Mesh.prototype.registerAfterRender = function (func) {
  32585. this.onAfterRenderObservable.add(func);
  32586. return this;
  32587. };
  32588. /**
  32589. * Disposes a previously registered javascript function called after the rendering.
  32590. * This function is passed the current mesh.
  32591. * Return the Mesh.
  32592. */
  32593. Mesh.prototype.unregisterAfterRender = function (func) {
  32594. this.onAfterRenderObservable.removeCallback(func);
  32595. return this;
  32596. };
  32597. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32598. var scene = this.getScene();
  32599. this._batchCache.mustReturn = false;
  32600. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32601. this._batchCache.visibleInstances[subMeshId] = null;
  32602. if (this._visibleInstances) {
  32603. var currentRenderId = scene.getRenderId();
  32604. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32605. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32606. var selfRenderId = this._renderId;
  32607. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32608. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32609. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32610. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32611. }
  32612. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32613. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32614. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32615. this._batchCache.mustReturn = true;
  32616. return this._batchCache;
  32617. }
  32618. if (currentRenderId !== selfRenderId) {
  32619. this._batchCache.renderSelf[subMeshId] = false;
  32620. }
  32621. }
  32622. this._renderIdForInstances[subMeshId] = currentRenderId;
  32623. }
  32624. return this._batchCache;
  32625. };
  32626. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32627. var visibleInstances = batch.visibleInstances[subMesh._id];
  32628. if (!visibleInstances) {
  32629. return this;
  32630. }
  32631. var matricesCount = visibleInstances.length + 1;
  32632. var bufferSize = matricesCount * 16 * 4;
  32633. var currentInstancesBufferSize = this._instancesBufferSize;
  32634. var instancesBuffer = this._instancesBuffer;
  32635. while (this._instancesBufferSize < bufferSize) {
  32636. this._instancesBufferSize *= 2;
  32637. }
  32638. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32639. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32640. }
  32641. var offset = 0;
  32642. var instancesCount = 0;
  32643. var world = this.getWorldMatrix();
  32644. if (batch.renderSelf[subMesh._id]) {
  32645. world.copyToArray(this._instancesData, offset);
  32646. offset += 16;
  32647. instancesCount++;
  32648. }
  32649. if (visibleInstances) {
  32650. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32651. var instance = visibleInstances[instanceIndex];
  32652. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32653. offset += 16;
  32654. instancesCount++;
  32655. }
  32656. }
  32657. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32658. if (instancesBuffer) {
  32659. instancesBuffer.dispose();
  32660. }
  32661. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32662. this._instancesBuffer = instancesBuffer;
  32663. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32664. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32665. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32666. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32667. }
  32668. else {
  32669. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32670. }
  32671. this._bind(subMesh, effect, fillMode);
  32672. this._draw(subMesh, fillMode, instancesCount);
  32673. engine.unbindInstanceAttributes();
  32674. return this;
  32675. };
  32676. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32677. var scene = this.getScene();
  32678. var engine = scene.getEngine();
  32679. if (hardwareInstancedRendering) {
  32680. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32681. }
  32682. else {
  32683. if (batch.renderSelf[subMesh._id]) {
  32684. // Draw
  32685. if (onBeforeDraw) {
  32686. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32687. }
  32688. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32689. }
  32690. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32691. if (visibleInstancesForSubMesh) {
  32692. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32693. var instance = visibleInstancesForSubMesh[instanceIndex];
  32694. // World
  32695. var world = instance.getWorldMatrix();
  32696. if (onBeforeDraw) {
  32697. onBeforeDraw(true, world, effectiveMaterial);
  32698. }
  32699. // Draw
  32700. this._draw(subMesh, fillMode);
  32701. }
  32702. }
  32703. }
  32704. return this;
  32705. };
  32706. /**
  32707. * Triggers the draw call for the mesh.
  32708. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32709. * Returns the Mesh.
  32710. */
  32711. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32712. this._checkOcclusionQuery();
  32713. if (this._isOccluded) {
  32714. return this;
  32715. }
  32716. var scene = this.getScene();
  32717. // Managing instances
  32718. var batch = this._getInstancesRenderList(subMesh._id);
  32719. if (batch.mustReturn) {
  32720. return this;
  32721. }
  32722. // Checking geometry state
  32723. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32724. return this;
  32725. }
  32726. this.onBeforeRenderObservable.notifyObservers(this);
  32727. var engine = scene.getEngine();
  32728. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32729. // Material
  32730. var material = subMesh.getMaterial();
  32731. if (!material) {
  32732. return this;
  32733. }
  32734. this._effectiveMaterial = material;
  32735. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32736. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32737. return this;
  32738. }
  32739. }
  32740. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32741. return this;
  32742. }
  32743. // Alpha mode
  32744. if (enableAlphaMode) {
  32745. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32746. }
  32747. // Outline - step 1
  32748. var savedDepthWrite = engine.getDepthWrite();
  32749. if (this.renderOutline) {
  32750. engine.setDepthWrite(false);
  32751. scene.getOutlineRenderer().render(subMesh, batch);
  32752. engine.setDepthWrite(savedDepthWrite);
  32753. }
  32754. var effect;
  32755. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32756. effect = subMesh.effect;
  32757. }
  32758. else {
  32759. effect = this._effectiveMaterial.getEffect();
  32760. }
  32761. if (!effect) {
  32762. return this;
  32763. }
  32764. var sideOrientation = this.overrideMaterialSideOrientation;
  32765. if (sideOrientation == null) {
  32766. sideOrientation = this._effectiveMaterial.sideOrientation;
  32767. if (this._getWorldMatrixDeterminant() < 0) {
  32768. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32769. }
  32770. }
  32771. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32772. if (this._effectiveMaterial.forceDepthWrite) {
  32773. engine.setDepthWrite(true);
  32774. }
  32775. // Bind
  32776. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32777. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32778. this._bind(subMesh, effect, fillMode);
  32779. }
  32780. var world = this.getWorldMatrix();
  32781. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32782. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32783. }
  32784. else {
  32785. this._effectiveMaterial.bind(world, this);
  32786. }
  32787. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32788. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32789. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32790. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32791. }
  32792. // Draw
  32793. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32794. // Unbind
  32795. this._effectiveMaterial.unbind();
  32796. // Outline - step 2
  32797. if (this.renderOutline && savedDepthWrite) {
  32798. engine.setDepthWrite(true);
  32799. engine.setColorWrite(false);
  32800. scene.getOutlineRenderer().render(subMesh, batch);
  32801. engine.setColorWrite(true);
  32802. }
  32803. // Overlay
  32804. if (this.renderOverlay) {
  32805. var currentMode = engine.getAlphaMode();
  32806. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32807. scene.getOutlineRenderer().render(subMesh, batch, true);
  32808. engine.setAlphaMode(currentMode);
  32809. }
  32810. this.onAfterRenderObservable.notifyObservers(this);
  32811. return this;
  32812. };
  32813. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32814. if (isInstance && effectiveMaterial) {
  32815. effectiveMaterial.bindOnlyWorldMatrix(world);
  32816. }
  32817. };
  32818. /**
  32819. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32820. */
  32821. Mesh.prototype.getEmittedParticleSystems = function () {
  32822. var results = new Array();
  32823. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32824. var particleSystem = this.getScene().particleSystems[index];
  32825. if (particleSystem.emitter === this) {
  32826. results.push(particleSystem);
  32827. }
  32828. }
  32829. return results;
  32830. };
  32831. /**
  32832. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32833. */
  32834. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32835. var results = new Array();
  32836. var descendants = this.getDescendants();
  32837. descendants.push(this);
  32838. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32839. var particleSystem = this.getScene().particleSystems[index];
  32840. var emitter = particleSystem.emitter;
  32841. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32842. results.push(particleSystem);
  32843. }
  32844. }
  32845. return results;
  32846. };
  32847. /**
  32848. * Normalize matrix weights so that all vertices have a total weight set to 1
  32849. */
  32850. Mesh.prototype.cleanMatrixWeights = function () {
  32851. var epsilon = 1e-3;
  32852. var noInfluenceBoneIndex = 0.0;
  32853. if (this.skeleton) {
  32854. noInfluenceBoneIndex = this.skeleton.bones.length;
  32855. }
  32856. else {
  32857. return;
  32858. }
  32859. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32860. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32861. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32862. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32863. var influencers = this.numBoneInfluencers;
  32864. var size = matricesWeights.length;
  32865. for (var i = 0; i < size; i += 4) {
  32866. var weight = 0.0;
  32867. var firstZeroWeight = -1;
  32868. for (var j = 0; j < 4; j++) {
  32869. var w = matricesWeights[i + j];
  32870. weight += w;
  32871. if (w < epsilon && firstZeroWeight < 0) {
  32872. firstZeroWeight = j;
  32873. }
  32874. }
  32875. if (matricesWeightsExtra) {
  32876. for (var j = 0; j < 4; j++) {
  32877. var w = matricesWeightsExtra[i + j];
  32878. weight += w;
  32879. if (w < epsilon && firstZeroWeight < 0) {
  32880. firstZeroWeight = j + 4;
  32881. }
  32882. }
  32883. }
  32884. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32885. firstZeroWeight = influencers - 1;
  32886. }
  32887. if (weight > epsilon) {
  32888. var mweight = 1.0 / weight;
  32889. for (var j = 0; j < 4; j++) {
  32890. matricesWeights[i + j] *= mweight;
  32891. }
  32892. if (matricesWeightsExtra) {
  32893. for (var j = 0; j < 4; j++) {
  32894. matricesWeightsExtra[i + j] *= mweight;
  32895. }
  32896. }
  32897. }
  32898. else {
  32899. if (firstZeroWeight >= 4) {
  32900. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32901. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32902. }
  32903. else {
  32904. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32905. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32906. }
  32907. }
  32908. }
  32909. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32910. if (matricesIndicesExtra) {
  32911. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32912. }
  32913. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32914. if (matricesWeightsExtra) {
  32915. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32916. }
  32917. };
  32918. Mesh.prototype._checkDelayState = function () {
  32919. var scene = this.getScene();
  32920. if (this._geometry) {
  32921. this._geometry.load(scene);
  32922. }
  32923. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32925. this._queueLoad(scene);
  32926. }
  32927. return this;
  32928. };
  32929. Mesh.prototype._queueLoad = function (scene) {
  32930. var _this = this;
  32931. scene._addPendingData(this);
  32932. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32933. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32934. if (data instanceof ArrayBuffer) {
  32935. _this._delayLoadingFunction(data, _this);
  32936. }
  32937. else {
  32938. _this._delayLoadingFunction(JSON.parse(data), _this);
  32939. }
  32940. _this.instances.forEach(function (instance) {
  32941. instance._syncSubMeshes();
  32942. });
  32943. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32944. scene._removePendingData(_this);
  32945. }, function () { }, scene.database, getBinaryData);
  32946. return this;
  32947. };
  32948. /**
  32949. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32950. */
  32951. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32952. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32953. return false;
  32954. }
  32955. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32956. return false;
  32957. }
  32958. this._checkDelayState();
  32959. return true;
  32960. };
  32961. /**
  32962. * Sets the mesh material by the material or multiMaterial `id` property.
  32963. * The material `id` is a string identifying the material or the multiMaterial.
  32964. * This method returns the Mesh.
  32965. */
  32966. Mesh.prototype.setMaterialByID = function (id) {
  32967. var materials = this.getScene().materials;
  32968. var index;
  32969. for (index = materials.length - 1; index > -1; index--) {
  32970. if (materials[index].id === id) {
  32971. this.material = materials[index];
  32972. return this;
  32973. }
  32974. }
  32975. // Multi
  32976. var multiMaterials = this.getScene().multiMaterials;
  32977. for (index = multiMaterials.length - 1; index > -1; index--) {
  32978. if (multiMaterials[index].id === id) {
  32979. this.material = multiMaterials[index];
  32980. return this;
  32981. }
  32982. }
  32983. return this;
  32984. };
  32985. /**
  32986. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32987. */
  32988. Mesh.prototype.getAnimatables = function () {
  32989. var results = new Array();
  32990. if (this.material) {
  32991. results.push(this.material);
  32992. }
  32993. if (this.skeleton) {
  32994. results.push(this.skeleton);
  32995. }
  32996. return results;
  32997. };
  32998. /**
  32999. * Modifies the mesh geometry according to the passed transformation matrix.
  33000. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33001. * The mesh normals are modified accordingly the same transformation.
  33002. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  33003. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33004. * Returns the Mesh.
  33005. */
  33006. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33007. // Position
  33008. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33009. return this;
  33010. }
  33011. var submeshes = this.subMeshes.splice(0);
  33012. this._resetPointsArrayCache();
  33013. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33014. var temp = new Array();
  33015. var index;
  33016. for (index = 0; index < data.length; index += 3) {
  33017. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33018. }
  33019. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33020. // Normals
  33021. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33022. return this;
  33023. }
  33024. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33025. temp = [];
  33026. for (index = 0; index < data.length; index += 3) {
  33027. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33028. }
  33029. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33030. // flip faces?
  33031. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33032. this.flipFaces();
  33033. }
  33034. // Restore submeshes
  33035. this.releaseSubMeshes();
  33036. this.subMeshes = submeshes;
  33037. return this;
  33038. };
  33039. /**
  33040. * Modifies the mesh geometry according to its own current World Matrix.
  33041. * The mesh World Matrix is then reset.
  33042. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33043. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  33044. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33045. * Returns the Mesh.
  33046. */
  33047. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33048. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33049. this.scaling.copyFromFloats(1, 1, 1);
  33050. this.position.copyFromFloats(0, 0, 0);
  33051. this.rotation.copyFromFloats(0, 0, 0);
  33052. //only if quaternion is already set
  33053. if (this.rotationQuaternion) {
  33054. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33055. }
  33056. this._worldMatrix = BABYLON.Matrix.Identity();
  33057. return this;
  33058. };
  33059. Object.defineProperty(Mesh.prototype, "_positions", {
  33060. // Cache
  33061. get: function () {
  33062. if (this._geometry) {
  33063. return this._geometry._positions;
  33064. }
  33065. return null;
  33066. },
  33067. enumerable: true,
  33068. configurable: true
  33069. });
  33070. Mesh.prototype._resetPointsArrayCache = function () {
  33071. if (this._geometry) {
  33072. this._geometry._resetPointsArrayCache();
  33073. }
  33074. return this;
  33075. };
  33076. Mesh.prototype._generatePointsArray = function () {
  33077. if (this._geometry) {
  33078. return this._geometry._generatePointsArray();
  33079. }
  33080. return false;
  33081. };
  33082. /**
  33083. * Returns a new Mesh object generated from the current mesh properties.
  33084. * This method must not get confused with createInstance().
  33085. * The parameter `name` is a string, the name given to the new mesh.
  33086. * The optional parameter `newParent` can be any Node object (default `null`).
  33087. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  33088. * 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.
  33089. */
  33090. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33091. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33092. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33093. };
  33094. /**
  33095. * Releases resources associated with this mesh.
  33096. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33097. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33098. */
  33099. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33100. var _this = this;
  33101. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33102. this.morphTargetManager = null;
  33103. if (this._geometry) {
  33104. this._geometry.releaseForMesh(this, true);
  33105. }
  33106. // Sources
  33107. var meshes = this.getScene().meshes;
  33108. meshes.forEach(function (abstractMesh) {
  33109. var mesh = abstractMesh;
  33110. if (mesh._source && mesh._source === _this) {
  33111. mesh._source = null;
  33112. }
  33113. });
  33114. this._source = null;
  33115. // Instances
  33116. if (this._instancesBuffer) {
  33117. this._instancesBuffer.dispose();
  33118. this._instancesBuffer = null;
  33119. }
  33120. while (this.instances.length) {
  33121. this.instances[0].dispose();
  33122. }
  33123. // Effect layers.
  33124. var effectLayers = this.getScene().effectLayers;
  33125. for (var i = 0; i < effectLayers.length; i++) {
  33126. var effectLayer = effectLayers[i];
  33127. if (effectLayer) {
  33128. effectLayer._disposeMesh(this);
  33129. }
  33130. }
  33131. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33132. };
  33133. /**
  33134. * Modifies the mesh geometry according to a displacement map.
  33135. * 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.
  33136. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33137. * This method returns nothing.
  33138. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33139. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33140. * 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.
  33141. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33142. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33143. *
  33144. * Returns the Mesh.
  33145. */
  33146. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33147. var _this = this;
  33148. var scene = this.getScene();
  33149. var onload = function (img) {
  33150. // Getting height map data
  33151. var canvas = document.createElement("canvas");
  33152. var context = canvas.getContext("2d");
  33153. var heightMapWidth = img.width;
  33154. var heightMapHeight = img.height;
  33155. canvas.width = heightMapWidth;
  33156. canvas.height = heightMapHeight;
  33157. context.drawImage(img, 0, 0);
  33158. // Create VertexData from map data
  33159. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33160. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33161. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33162. //execute success callback, if set
  33163. if (onSuccess) {
  33164. onSuccess(_this);
  33165. }
  33166. };
  33167. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33168. return this;
  33169. };
  33170. /**
  33171. * Modifies the mesh geometry according to a displacementMap buffer.
  33172. * 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.
  33173. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33174. * This method returns nothing.
  33175. * 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.
  33176. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33177. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33178. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33179. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33180. *
  33181. * Returns the Mesh.
  33182. */
  33183. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33185. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33186. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33187. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33188. return this;
  33189. }
  33190. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33191. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33192. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33193. var position = BABYLON.Vector3.Zero();
  33194. var normal = BABYLON.Vector3.Zero();
  33195. var uv = BABYLON.Vector2.Zero();
  33196. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33197. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33198. for (var index = 0; index < positions.length; index += 3) {
  33199. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33200. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33201. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33202. // Compute height
  33203. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33204. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33205. var pos = (u + v * heightMapWidth) * 4;
  33206. var r = buffer[pos] / 255.0;
  33207. var g = buffer[pos + 1] / 255.0;
  33208. var b = buffer[pos + 2] / 255.0;
  33209. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33210. normal.normalize();
  33211. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33212. position = position.add(normal);
  33213. position.toArray(positions, index);
  33214. }
  33215. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33216. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33217. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33218. return this;
  33219. };
  33220. /**
  33221. * Modify the mesh to get a flat shading rendering.
  33222. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33223. * This method returns the Mesh.
  33224. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33225. */
  33226. Mesh.prototype.convertToFlatShadedMesh = function () {
  33227. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33228. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33229. var kinds = this.getVerticesDataKinds();
  33230. var vbs = {};
  33231. var data = {};
  33232. var newdata = {};
  33233. var updatableNormals = false;
  33234. var kindIndex;
  33235. var kind;
  33236. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33237. kind = kinds[kindIndex];
  33238. var vertexBuffer = this.getVertexBuffer(kind);
  33239. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33240. updatableNormals = vertexBuffer.isUpdatable();
  33241. kinds.splice(kindIndex, 1);
  33242. kindIndex--;
  33243. continue;
  33244. }
  33245. vbs[kind] = vertexBuffer;
  33246. data[kind] = vbs[kind].getData();
  33247. newdata[kind] = [];
  33248. }
  33249. // Save previous submeshes
  33250. var previousSubmeshes = this.subMeshes.slice(0);
  33251. var indices = this.getIndices();
  33252. var totalIndices = this.getTotalIndices();
  33253. // Generating unique vertices per face
  33254. var index;
  33255. for (index = 0; index < totalIndices; index++) {
  33256. var vertexIndex = indices[index];
  33257. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33258. kind = kinds[kindIndex];
  33259. var stride = vbs[kind].getStrideSize();
  33260. for (var offset = 0; offset < stride; offset++) {
  33261. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33262. }
  33263. }
  33264. }
  33265. // Updating faces & normal
  33266. var normals = [];
  33267. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33268. for (index = 0; index < totalIndices; index += 3) {
  33269. indices[index] = index;
  33270. indices[index + 1] = index + 1;
  33271. indices[index + 2] = index + 2;
  33272. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33273. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33274. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33275. var p1p2 = p1.subtract(p2);
  33276. var p3p2 = p3.subtract(p2);
  33277. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33278. // Store same normals for every vertex
  33279. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33280. normals.push(normal.x);
  33281. normals.push(normal.y);
  33282. normals.push(normal.z);
  33283. }
  33284. }
  33285. this.setIndices(indices);
  33286. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33287. // Updating vertex buffers
  33288. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33289. kind = kinds[kindIndex];
  33290. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33291. }
  33292. // Updating submeshes
  33293. this.releaseSubMeshes();
  33294. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33295. var previousOne = previousSubmeshes[submeshIndex];
  33296. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33297. }
  33298. this.synchronizeInstances();
  33299. return this;
  33300. };
  33301. /**
  33302. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33303. * In other words, more vertices, no more indices and a single bigger VBO.
  33304. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33305. * Returns the Mesh.
  33306. */
  33307. Mesh.prototype.convertToUnIndexedMesh = function () {
  33308. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33309. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33310. var kinds = this.getVerticesDataKinds();
  33311. var vbs = {};
  33312. var data = {};
  33313. var newdata = {};
  33314. var kindIndex;
  33315. var kind;
  33316. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33317. kind = kinds[kindIndex];
  33318. var vertexBuffer = this.getVertexBuffer(kind);
  33319. vbs[kind] = vertexBuffer;
  33320. data[kind] = vbs[kind].getData();
  33321. newdata[kind] = [];
  33322. }
  33323. // Save previous submeshes
  33324. var previousSubmeshes = this.subMeshes.slice(0);
  33325. var indices = this.getIndices();
  33326. var totalIndices = this.getTotalIndices();
  33327. // Generating unique vertices per face
  33328. var index;
  33329. for (index = 0; index < totalIndices; index++) {
  33330. var vertexIndex = indices[index];
  33331. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33332. kind = kinds[kindIndex];
  33333. var stride = vbs[kind].getStrideSize();
  33334. for (var offset = 0; offset < stride; offset++) {
  33335. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33336. }
  33337. }
  33338. }
  33339. // Updating indices
  33340. for (index = 0; index < totalIndices; index += 3) {
  33341. indices[index] = index;
  33342. indices[index + 1] = index + 1;
  33343. indices[index + 2] = index + 2;
  33344. }
  33345. this.setIndices(indices);
  33346. // Updating vertex buffers
  33347. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33348. kind = kinds[kindIndex];
  33349. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33350. }
  33351. // Updating submeshes
  33352. this.releaseSubMeshes();
  33353. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33354. var previousOne = previousSubmeshes[submeshIndex];
  33355. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33356. }
  33357. this._unIndexed = true;
  33358. this.synchronizeInstances();
  33359. return this;
  33360. };
  33361. /**
  33362. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33363. * This method returns the Mesh.
  33364. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33365. */
  33366. Mesh.prototype.flipFaces = function (flipNormals) {
  33367. if (flipNormals === void 0) { flipNormals = false; }
  33368. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33369. var i;
  33370. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33371. for (i = 0; i < vertex_data.normals.length; i++) {
  33372. vertex_data.normals[i] *= -1;
  33373. }
  33374. }
  33375. if (vertex_data.indices) {
  33376. var temp;
  33377. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33378. // reassign indices
  33379. temp = vertex_data.indices[i + 1];
  33380. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33381. vertex_data.indices[i + 2] = temp;
  33382. }
  33383. }
  33384. vertex_data.applyToMesh(this);
  33385. return this;
  33386. };
  33387. // Instances
  33388. /**
  33389. * Creates a new InstancedMesh object from the mesh model.
  33390. * An instance shares the same properties and the same material than its model.
  33391. * Only these properties of each instance can then be set individually :
  33392. * - position
  33393. * - rotation
  33394. * - rotationQuaternion
  33395. * - setPivotMatrix
  33396. * - scaling
  33397. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33398. * Warning : this method is not supported for Line mesh and LineSystem
  33399. */
  33400. Mesh.prototype.createInstance = function (name) {
  33401. return new BABYLON.InstancedMesh(name, this);
  33402. };
  33403. /**
  33404. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33405. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33406. * This method returns the Mesh.
  33407. */
  33408. Mesh.prototype.synchronizeInstances = function () {
  33409. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33410. var instance = this.instances[instanceIndex];
  33411. instance._syncSubMeshes();
  33412. }
  33413. return this;
  33414. };
  33415. /**
  33416. * Simplify the mesh according to the given array of settings.
  33417. * Function will return immediately and will simplify async. It returns the Mesh.
  33418. * @param settings a collection of simplification settings.
  33419. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33420. * @param type the type of simplification to run.
  33421. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33422. */
  33423. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33424. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33425. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33426. this.getScene().simplificationQueue.addTask({
  33427. settings: settings,
  33428. parallelProcessing: parallelProcessing,
  33429. mesh: this,
  33430. simplificationType: simplificationType,
  33431. successCallback: successCallback
  33432. });
  33433. return this;
  33434. };
  33435. /**
  33436. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33437. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33438. * This should be used together with the simplification to avoid disappearing triangles.
  33439. * Returns the Mesh.
  33440. * @param successCallback an optional success callback to be called after the optimization finished.
  33441. */
  33442. Mesh.prototype.optimizeIndices = function (successCallback) {
  33443. var _this = this;
  33444. var indices = this.getIndices();
  33445. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33446. if (!positions || !indices) {
  33447. return this;
  33448. }
  33449. var vectorPositions = new Array();
  33450. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33451. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33452. }
  33453. var dupes = new Array();
  33454. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33455. var realPos = vectorPositions.length - 1 - iteration;
  33456. var testedPosition = vectorPositions[realPos];
  33457. for (var j = 0; j < realPos; ++j) {
  33458. var againstPosition = vectorPositions[j];
  33459. if (testedPosition.equals(againstPosition)) {
  33460. dupes[realPos] = j;
  33461. break;
  33462. }
  33463. }
  33464. }, function () {
  33465. for (var i = 0; i < indices.length; ++i) {
  33466. indices[i] = dupes[indices[i]] || indices[i];
  33467. }
  33468. //indices are now reordered
  33469. var originalSubMeshes = _this.subMeshes.slice(0);
  33470. _this.setIndices(indices);
  33471. _this.subMeshes = originalSubMeshes;
  33472. if (successCallback) {
  33473. successCallback(_this);
  33474. }
  33475. });
  33476. return this;
  33477. };
  33478. Mesh.prototype.serialize = function (serializationObject) {
  33479. serializationObject.name = this.name;
  33480. serializationObject.id = this.id;
  33481. serializationObject.type = this.getClassName();
  33482. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33483. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33484. }
  33485. serializationObject.position = this.position.asArray();
  33486. if (this.rotationQuaternion) {
  33487. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33488. }
  33489. else if (this.rotation) {
  33490. serializationObject.rotation = this.rotation.asArray();
  33491. }
  33492. serializationObject.scaling = this.scaling.asArray();
  33493. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33494. serializationObject.isEnabled = this.isEnabled(false);
  33495. serializationObject.isVisible = this.isVisible;
  33496. serializationObject.infiniteDistance = this.infiniteDistance;
  33497. serializationObject.pickable = this.isPickable;
  33498. serializationObject.receiveShadows = this.receiveShadows;
  33499. serializationObject.billboardMode = this.billboardMode;
  33500. serializationObject.visibility = this.visibility;
  33501. serializationObject.checkCollisions = this.checkCollisions;
  33502. serializationObject.isBlocker = this.isBlocker;
  33503. // Parent
  33504. if (this.parent) {
  33505. serializationObject.parentId = this.parent.id;
  33506. }
  33507. // Geometry
  33508. serializationObject.isUnIndexed = this.isUnIndexed;
  33509. var geometry = this._geometry;
  33510. if (geometry) {
  33511. var geometryId = geometry.id;
  33512. serializationObject.geometryId = geometryId;
  33513. // SubMeshes
  33514. serializationObject.subMeshes = [];
  33515. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33516. var subMesh = this.subMeshes[subIndex];
  33517. serializationObject.subMeshes.push({
  33518. materialIndex: subMesh.materialIndex,
  33519. verticesStart: subMesh.verticesStart,
  33520. verticesCount: subMesh.verticesCount,
  33521. indexStart: subMesh.indexStart,
  33522. indexCount: subMesh.indexCount
  33523. });
  33524. }
  33525. }
  33526. // Material
  33527. if (this.material) {
  33528. serializationObject.materialId = this.material.id;
  33529. }
  33530. else {
  33531. this.material = null;
  33532. }
  33533. // Morph targets
  33534. if (this.morphTargetManager) {
  33535. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33536. }
  33537. // Skeleton
  33538. if (this.skeleton) {
  33539. serializationObject.skeletonId = this.skeleton.id;
  33540. }
  33541. // Physics
  33542. //TODO implement correct serialization for physics impostors.
  33543. var impostor = this.getPhysicsImpostor();
  33544. if (impostor) {
  33545. serializationObject.physicsMass = impostor.getParam("mass");
  33546. serializationObject.physicsFriction = impostor.getParam("friction");
  33547. serializationObject.physicsRestitution = impostor.getParam("mass");
  33548. serializationObject.physicsImpostor = impostor.type;
  33549. }
  33550. // Metadata
  33551. if (this.metadata) {
  33552. serializationObject.metadata = this.metadata;
  33553. }
  33554. // Instances
  33555. serializationObject.instances = [];
  33556. for (var index = 0; index < this.instances.length; index++) {
  33557. var instance = this.instances[index];
  33558. var serializationInstance = {
  33559. name: instance.name,
  33560. id: instance.id,
  33561. position: instance.position.asArray(),
  33562. scaling: instance.scaling.asArray()
  33563. };
  33564. if (instance.rotationQuaternion) {
  33565. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33566. }
  33567. else if (instance.rotation) {
  33568. serializationInstance.rotation = instance.rotation.asArray();
  33569. }
  33570. serializationObject.instances.push(serializationInstance);
  33571. // Animations
  33572. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33573. serializationInstance.ranges = instance.serializeAnimationRanges();
  33574. }
  33575. //
  33576. // Animations
  33577. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33578. serializationObject.ranges = this.serializeAnimationRanges();
  33579. // Layer mask
  33580. serializationObject.layerMask = this.layerMask;
  33581. // Alpha
  33582. serializationObject.alphaIndex = this.alphaIndex;
  33583. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33584. // Overlay
  33585. serializationObject.overlayAlpha = this.overlayAlpha;
  33586. serializationObject.overlayColor = this.overlayColor.asArray();
  33587. serializationObject.renderOverlay = this.renderOverlay;
  33588. // Fog
  33589. serializationObject.applyFog = this.applyFog;
  33590. // Action Manager
  33591. if (this.actionManager) {
  33592. serializationObject.actions = this.actionManager.serialize(this.name);
  33593. }
  33594. };
  33595. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33596. if (!this.geometry) {
  33597. return;
  33598. }
  33599. this._markSubMeshesAsAttributesDirty();
  33600. var morphTargetManager = this._morphTargetManager;
  33601. if (morphTargetManager && morphTargetManager.vertexCount) {
  33602. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33603. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33604. this.morphTargetManager = null;
  33605. return;
  33606. }
  33607. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33608. var morphTarget = morphTargetManager.getActiveTarget(index);
  33609. var positions = morphTarget.getPositions();
  33610. if (!positions) {
  33611. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33612. return;
  33613. }
  33614. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33615. var normals = morphTarget.getNormals();
  33616. if (normals) {
  33617. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33618. }
  33619. var tangents = morphTarget.getTangents();
  33620. if (tangents) {
  33621. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33622. }
  33623. }
  33624. }
  33625. else {
  33626. var index = 0;
  33627. // Positions
  33628. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33629. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33630. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33631. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33632. }
  33633. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33634. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33635. }
  33636. index++;
  33637. }
  33638. }
  33639. };
  33640. // Statics
  33641. /**
  33642. * Returns a new Mesh object parsed from the source provided.
  33643. * The parameter `parsedMesh` is the source.
  33644. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33645. */
  33646. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33647. var mesh;
  33648. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33649. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33650. }
  33651. else {
  33652. mesh = new Mesh(parsedMesh.name, scene);
  33653. }
  33654. mesh.id = parsedMesh.id;
  33655. if (BABYLON.Tags) {
  33656. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33657. }
  33658. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33659. if (parsedMesh.metadata !== undefined) {
  33660. mesh.metadata = parsedMesh.metadata;
  33661. }
  33662. if (parsedMesh.rotationQuaternion) {
  33663. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33664. }
  33665. else if (parsedMesh.rotation) {
  33666. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33667. }
  33668. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33669. if (parsedMesh.localMatrix) {
  33670. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33671. }
  33672. else if (parsedMesh.pivotMatrix) {
  33673. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33674. }
  33675. mesh.setEnabled(parsedMesh.isEnabled);
  33676. mesh.isVisible = parsedMesh.isVisible;
  33677. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33678. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33679. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33680. if (parsedMesh.applyFog !== undefined) {
  33681. mesh.applyFog = parsedMesh.applyFog;
  33682. }
  33683. if (parsedMesh.pickable !== undefined) {
  33684. mesh.isPickable = parsedMesh.pickable;
  33685. }
  33686. if (parsedMesh.alphaIndex !== undefined) {
  33687. mesh.alphaIndex = parsedMesh.alphaIndex;
  33688. }
  33689. mesh.receiveShadows = parsedMesh.receiveShadows;
  33690. mesh.billboardMode = parsedMesh.billboardMode;
  33691. if (parsedMesh.visibility !== undefined) {
  33692. mesh.visibility = parsedMesh.visibility;
  33693. }
  33694. mesh.checkCollisions = parsedMesh.checkCollisions;
  33695. if (parsedMesh.isBlocker !== undefined) {
  33696. mesh.isBlocker = parsedMesh.isBlocker;
  33697. }
  33698. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33699. // freezeWorldMatrix
  33700. if (parsedMesh.freezeWorldMatrix) {
  33701. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33702. }
  33703. // Parent
  33704. if (parsedMesh.parentId) {
  33705. mesh._waitingParentId = parsedMesh.parentId;
  33706. }
  33707. // Actions
  33708. if (parsedMesh.actions !== undefined) {
  33709. mesh._waitingActions = parsedMesh.actions;
  33710. }
  33711. // Overlay
  33712. if (parsedMesh.overlayAlpha !== undefined) {
  33713. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33714. }
  33715. if (parsedMesh.overlayColor !== undefined) {
  33716. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33717. }
  33718. if (parsedMesh.renderOverlay !== undefined) {
  33719. mesh.renderOverlay = parsedMesh.renderOverlay;
  33720. }
  33721. // Geometry
  33722. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33723. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33724. if (parsedMesh.delayLoadingFile) {
  33725. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33726. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33727. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33728. if (parsedMesh._binaryInfo) {
  33729. mesh._binaryInfo = parsedMesh._binaryInfo;
  33730. }
  33731. mesh._delayInfo = [];
  33732. if (parsedMesh.hasUVs) {
  33733. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33734. }
  33735. if (parsedMesh.hasUVs2) {
  33736. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33737. }
  33738. if (parsedMesh.hasUVs3) {
  33739. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33740. }
  33741. if (parsedMesh.hasUVs4) {
  33742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33743. }
  33744. if (parsedMesh.hasUVs5) {
  33745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33746. }
  33747. if (parsedMesh.hasUVs6) {
  33748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33749. }
  33750. if (parsedMesh.hasColors) {
  33751. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33752. }
  33753. if (parsedMesh.hasMatricesIndices) {
  33754. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33755. }
  33756. if (parsedMesh.hasMatricesWeights) {
  33757. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33758. }
  33759. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33760. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33761. mesh._checkDelayState();
  33762. }
  33763. }
  33764. else {
  33765. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33766. }
  33767. // Material
  33768. if (parsedMesh.materialId) {
  33769. mesh.setMaterialByID(parsedMesh.materialId);
  33770. }
  33771. else {
  33772. mesh.material = null;
  33773. }
  33774. // Morph targets
  33775. if (parsedMesh.morphTargetManagerId > -1) {
  33776. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33777. }
  33778. // Skeleton
  33779. if (parsedMesh.skeletonId > -1) {
  33780. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33781. if (parsedMesh.numBoneInfluencers) {
  33782. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33783. }
  33784. }
  33785. // Animations
  33786. if (parsedMesh.animations) {
  33787. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33788. var parsedAnimation = parsedMesh.animations[animationIndex];
  33789. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33790. }
  33791. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33792. }
  33793. if (parsedMesh.autoAnimate) {
  33794. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33795. }
  33796. // Layer Mask
  33797. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33798. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33799. }
  33800. else {
  33801. mesh.layerMask = 0x0FFFFFFF;
  33802. }
  33803. // Physics
  33804. if (parsedMesh.physicsImpostor) {
  33805. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33806. mass: parsedMesh.physicsMass,
  33807. friction: parsedMesh.physicsFriction,
  33808. restitution: parsedMesh.physicsRestitution
  33809. }, scene);
  33810. }
  33811. // Instances
  33812. if (parsedMesh.instances) {
  33813. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33814. var parsedInstance = parsedMesh.instances[index];
  33815. var instance = mesh.createInstance(parsedInstance.name);
  33816. if (parsedInstance.id) {
  33817. instance.id = parsedInstance.id;
  33818. }
  33819. if (BABYLON.Tags) {
  33820. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33821. }
  33822. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33823. if (parsedInstance.parentId) {
  33824. instance._waitingParentId = parsedInstance.parentId;
  33825. }
  33826. if (parsedInstance.rotationQuaternion) {
  33827. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33828. }
  33829. else if (parsedInstance.rotation) {
  33830. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33831. }
  33832. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33833. instance.checkCollisions = mesh.checkCollisions;
  33834. if (parsedMesh.animations) {
  33835. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33836. parsedAnimation = parsedMesh.animations[animationIndex];
  33837. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33838. }
  33839. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33840. if (parsedMesh.autoAnimate) {
  33841. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33842. }
  33843. }
  33844. }
  33845. }
  33846. return mesh;
  33847. };
  33848. /**
  33849. * Creates a ribbon mesh.
  33850. * Please consider using the same method from the MeshBuilder class instead.
  33851. * 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.
  33852. *
  33853. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33854. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33855. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33856. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33857. * 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.
  33858. * 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.
  33859. * 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
  33860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33861. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33863. */
  33864. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33865. if (closeArray === void 0) { closeArray = false; }
  33866. if (updatable === void 0) { updatable = false; }
  33867. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33868. pathArray: pathArray,
  33869. closeArray: closeArray,
  33870. closePath: closePath,
  33871. offset: offset,
  33872. updatable: updatable,
  33873. sideOrientation: sideOrientation,
  33874. instance: instance
  33875. }, scene);
  33876. };
  33877. /**
  33878. * Creates a plane polygonal mesh. By default, this is a disc.
  33879. * Please consider using the same method from the MeshBuilder class instead.
  33880. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33881. * 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.
  33882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33883. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33885. */
  33886. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33887. if (scene === void 0) { scene = null; }
  33888. var options = {
  33889. radius: radius,
  33890. tessellation: tessellation,
  33891. sideOrientation: sideOrientation,
  33892. updatable: updatable
  33893. };
  33894. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33895. };
  33896. /**
  33897. * Creates a box mesh.
  33898. * Please consider using the same method from the MeshBuilder class instead.
  33899. * The parameter `size` sets the size (float) of each box side (default 1).
  33900. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33901. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33903. */
  33904. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33905. if (scene === void 0) { scene = null; }
  33906. var options = {
  33907. size: size,
  33908. sideOrientation: sideOrientation,
  33909. updatable: updatable
  33910. };
  33911. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33912. };
  33913. /**
  33914. * Creates a sphere mesh.
  33915. * Please consider using the same method from the MeshBuilder class instead.
  33916. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33917. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33919. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33921. */
  33922. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33923. var options = {
  33924. segments: segments,
  33925. diameterX: diameter,
  33926. diameterY: diameter,
  33927. diameterZ: diameter,
  33928. sideOrientation: sideOrientation,
  33929. updatable: updatable
  33930. };
  33931. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33932. };
  33933. /**
  33934. * Creates a cylinder or a cone mesh.
  33935. * Please consider using the same method from the MeshBuilder class instead.
  33936. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33937. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33938. * 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.
  33939. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33940. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33942. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33944. */
  33945. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33946. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33947. if (scene !== undefined) {
  33948. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33949. updatable = scene;
  33950. }
  33951. scene = subdivisions;
  33952. subdivisions = 1;
  33953. }
  33954. var options = {
  33955. height: height,
  33956. diameterTop: diameterTop,
  33957. diameterBottom: diameterBottom,
  33958. tessellation: tessellation,
  33959. subdivisions: subdivisions,
  33960. sideOrientation: sideOrientation,
  33961. updatable: updatable
  33962. };
  33963. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33964. };
  33965. // Torus (Code from SharpDX.org)
  33966. /**
  33967. * Creates a torus mesh.
  33968. * Please consider using the same method from the MeshBuilder class instead.
  33969. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33970. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33971. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33973. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33975. */
  33976. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33977. var options = {
  33978. diameter: diameter,
  33979. thickness: thickness,
  33980. tessellation: tessellation,
  33981. sideOrientation: sideOrientation,
  33982. updatable: updatable
  33983. };
  33984. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33985. };
  33986. /**
  33987. * Creates a torus knot mesh.
  33988. * Please consider using the same method from the MeshBuilder class instead.
  33989. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33990. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33991. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33992. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33994. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33996. */
  33997. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33998. var options = {
  33999. radius: radius,
  34000. tube: tube,
  34001. radialSegments: radialSegments,
  34002. tubularSegments: tubularSegments,
  34003. p: p,
  34004. q: q,
  34005. sideOrientation: sideOrientation,
  34006. updatable: updatable
  34007. };
  34008. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34009. };
  34010. /**
  34011. * Creates a line mesh.
  34012. * Please consider using the same method from the MeshBuilder class instead.
  34013. * 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.
  34014. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  34015. * The parameter `points` is an array successive Vector3.
  34016. * 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
  34017. * When updating an instance, remember that only point positions can change, not the number of points.
  34018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34019. */
  34020. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34021. if (scene === void 0) { scene = null; }
  34022. if (updatable === void 0) { updatable = false; }
  34023. if (instance === void 0) { instance = null; }
  34024. var options = {
  34025. points: points,
  34026. updatable: updatable,
  34027. instance: instance
  34028. };
  34029. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34030. };
  34031. /**
  34032. * Creates a dashed line mesh.
  34033. * Please consider using the same method from the MeshBuilder class instead.
  34034. * 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.
  34035. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  34036. * The parameter `points` is an array successive Vector3.
  34037. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  34038. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  34039. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  34040. * 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
  34041. * When updating an instance, remember that only point positions can change, not the number of points.
  34042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34043. */
  34044. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34045. if (scene === void 0) { scene = null; }
  34046. var options = {
  34047. points: points,
  34048. dashSize: dashSize,
  34049. gapSize: gapSize,
  34050. dashNb: dashNb,
  34051. updatable: updatable,
  34052. instance: instance
  34053. };
  34054. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34055. };
  34056. /**
  34057. * Creates a polygon mesh.
  34058. * Please consider using the same method from the MeshBuilder class instead.
  34059. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34060. * 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.
  34061. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34063. * Remember you can only change the shape positions, not their number when updating a polygon.
  34064. */
  34065. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34066. var options = {
  34067. shape: shape,
  34068. holes: holes,
  34069. updatable: updatable,
  34070. sideOrientation: sideOrientation
  34071. };
  34072. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34073. };
  34074. /**
  34075. * Creates an extruded polygon mesh, with depth in the Y direction.
  34076. * Please consider using the same method from the MeshBuilder class instead.
  34077. */
  34078. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34079. var options = {
  34080. shape: shape,
  34081. holes: holes,
  34082. depth: depth,
  34083. updatable: updatable,
  34084. sideOrientation: sideOrientation
  34085. };
  34086. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34087. };
  34088. /**
  34089. * Creates an extruded shape mesh.
  34090. * 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.
  34091. * Please consider using the same method from the MeshBuilder class instead.
  34092. *
  34093. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34094. * 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
  34095. * extruded along the Z axis.
  34096. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34097. * 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.
  34098. * The parameter `scale` (float, default 1) is the value to scale the shape.
  34099. * 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
  34100. * 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
  34101. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34103. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34105. */
  34106. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34107. if (scene === void 0) { scene = null; }
  34108. var options = {
  34109. shape: shape,
  34110. path: path,
  34111. scale: scale,
  34112. rotation: rotation,
  34113. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34114. sideOrientation: sideOrientation,
  34115. instance: instance,
  34116. updatable: updatable
  34117. };
  34118. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34119. };
  34120. /**
  34121. * Creates an custom extruded shape mesh.
  34122. * 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.
  34123. * Please consider using the same method from the MeshBuilder class instead.
  34124. *
  34125. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34126. * 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
  34127. * extruded along the Z axis.
  34128. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34129. * 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
  34130. * and the distance of this point from the begining of the path :
  34131. * ```javascript
  34132. * var rotationFunction = function(i, distance) {
  34133. * // do things
  34134. * return rotationValue; }
  34135. * ```
  34136. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34137. * 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
  34138. * and the distance of this point from the begining of the path :
  34139. * ```javascript
  34140. * var scaleFunction = function(i, distance) {
  34141. * // do things
  34142. * return scaleValue;}
  34143. * ```
  34144. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34145. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34146. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34147. * 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
  34148. * 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
  34149. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34151. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34153. */
  34154. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34155. var options = {
  34156. shape: shape,
  34157. path: path,
  34158. scaleFunction: scaleFunction,
  34159. rotationFunction: rotationFunction,
  34160. ribbonCloseArray: ribbonCloseArray,
  34161. ribbonClosePath: ribbonClosePath,
  34162. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34163. sideOrientation: sideOrientation,
  34164. instance: instance,
  34165. updatable: updatable
  34166. };
  34167. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34168. };
  34169. /**
  34170. * Creates lathe mesh.
  34171. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34172. * Please consider using the same method from the MeshBuilder class instead.
  34173. * 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
  34174. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34175. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34176. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34177. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34178. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34180. */
  34181. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34182. var options = {
  34183. shape: shape,
  34184. radius: radius,
  34185. tessellation: tessellation,
  34186. sideOrientation: sideOrientation,
  34187. updatable: updatable
  34188. };
  34189. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34190. };
  34191. /**
  34192. * Creates a plane mesh.
  34193. * Please consider using the same method from the MeshBuilder class instead.
  34194. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34196. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34198. */
  34199. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34200. var options = {
  34201. size: size,
  34202. width: size,
  34203. height: size,
  34204. sideOrientation: sideOrientation,
  34205. updatable: updatable
  34206. };
  34207. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34208. };
  34209. /**
  34210. * Creates a ground mesh.
  34211. * Please consider using the same method from the MeshBuilder class instead.
  34212. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34213. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34215. */
  34216. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34217. var options = {
  34218. width: width,
  34219. height: height,
  34220. subdivisions: subdivisions,
  34221. updatable: updatable
  34222. };
  34223. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34224. };
  34225. /**
  34226. * Creates a tiled ground mesh.
  34227. * Please consider using the same method from the MeshBuilder class instead.
  34228. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34229. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34230. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34231. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34232. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34233. * numbers of subdivisions on the ground width and height of each tile.
  34234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34235. */
  34236. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34237. var options = {
  34238. xmin: xmin,
  34239. zmin: zmin,
  34240. xmax: xmax,
  34241. zmax: zmax,
  34242. subdivisions: subdivisions,
  34243. precision: precision,
  34244. updatable: updatable
  34245. };
  34246. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34247. };
  34248. /**
  34249. * Creates a ground mesh from a height map.
  34250. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34251. * Please consider using the same method from the MeshBuilder class instead.
  34252. * The parameter `url` sets the URL of the height map image resource.
  34253. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34254. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34255. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34256. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34257. * 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).
  34258. * This function is passed the newly built mesh :
  34259. * ```javascript
  34260. * function(mesh) { // do things
  34261. * return; }
  34262. * ```
  34263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34264. */
  34265. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34266. var options = {
  34267. width: width,
  34268. height: height,
  34269. subdivisions: subdivisions,
  34270. minHeight: minHeight,
  34271. maxHeight: maxHeight,
  34272. updatable: updatable,
  34273. onReady: onReady
  34274. };
  34275. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34276. };
  34277. /**
  34278. * Creates a tube mesh.
  34279. * 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.
  34280. * Please consider using the same method from the MeshBuilder class instead.
  34281. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34282. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34283. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34284. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34285. * 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.
  34286. * It must return a radius value (positive float) :
  34287. * ```javascript
  34288. * var radiusFunction = function(i, distance) {
  34289. * // do things
  34290. * return radius; }
  34291. * ```
  34292. * 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
  34293. * 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
  34294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34295. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34297. */
  34298. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34299. var options = {
  34300. path: path,
  34301. radius: radius,
  34302. tessellation: tessellation,
  34303. radiusFunction: radiusFunction,
  34304. arc: 1,
  34305. cap: cap,
  34306. updatable: updatable,
  34307. sideOrientation: sideOrientation,
  34308. instance: instance
  34309. };
  34310. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34311. };
  34312. /**
  34313. * Creates a polyhedron mesh.
  34314. * Please consider using the same method from the MeshBuilder class instead.
  34315. * 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
  34316. * to choose the wanted type.
  34317. * The parameter `size` (positive float, default 1) sets the polygon size.
  34318. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34319. * 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`.
  34320. * 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
  34321. * 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)`).
  34322. * 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
  34323. * 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.
  34324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34325. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34327. */
  34328. Mesh.CreatePolyhedron = function (name, options, scene) {
  34329. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34330. };
  34331. /**
  34332. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34333. * Please consider using the same method from the MeshBuilder class instead.
  34334. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34335. * 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`).
  34336. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34337. * 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.
  34338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34339. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34341. */
  34342. Mesh.CreateIcoSphere = function (name, options, scene) {
  34343. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34344. };
  34345. /**
  34346. * Creates a decal mesh.
  34347. * Please consider using the same method from the MeshBuilder class instead.
  34348. * 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.
  34349. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34350. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34351. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34352. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34353. */
  34354. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34355. var options = {
  34356. position: position,
  34357. normal: normal,
  34358. size: size,
  34359. angle: angle
  34360. };
  34361. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34362. };
  34363. // Skeletons
  34364. /**
  34365. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34366. */
  34367. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34368. if (!this._sourcePositions) {
  34369. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34370. if (!source) {
  34371. return this._sourcePositions;
  34372. }
  34373. this._sourcePositions = new Float32Array(source);
  34374. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34375. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34376. }
  34377. }
  34378. return this._sourcePositions;
  34379. };
  34380. /**
  34381. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34382. */
  34383. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34384. if (!this._sourceNormals) {
  34385. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34386. if (!source) {
  34387. return this._sourceNormals;
  34388. }
  34389. this._sourceNormals = new Float32Array(source);
  34390. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34392. }
  34393. }
  34394. return this._sourceNormals;
  34395. };
  34396. /**
  34397. * Updates the vertex buffer by applying transformation from the bones.
  34398. * Returns the Mesh.
  34399. *
  34400. * @param {skeleton} skeleton to apply
  34401. */
  34402. Mesh.prototype.applySkeleton = function (skeleton) {
  34403. if (!this.geometry) {
  34404. return this;
  34405. }
  34406. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34407. return this;
  34408. }
  34409. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34410. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34411. return this;
  34412. }
  34413. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34414. return this;
  34415. }
  34416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34417. return this;
  34418. }
  34419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34420. return this;
  34421. }
  34422. if (!this._sourcePositions) {
  34423. var submeshes = this.subMeshes.slice();
  34424. this.setPositionsForCPUSkinning();
  34425. this.subMeshes = submeshes;
  34426. }
  34427. if (!this._sourceNormals) {
  34428. this.setNormalsForCPUSkinning();
  34429. }
  34430. // positionsData checks for not being Float32Array will only pass at most once
  34431. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34432. if (!positionsData) {
  34433. return this;
  34434. }
  34435. if (!(positionsData instanceof Float32Array)) {
  34436. positionsData = new Float32Array(positionsData);
  34437. }
  34438. // normalsData checks for not being Float32Array will only pass at most once
  34439. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34440. if (!normalsData) {
  34441. return this;
  34442. }
  34443. if (!(normalsData instanceof Float32Array)) {
  34444. normalsData = new Float32Array(normalsData);
  34445. }
  34446. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34447. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34448. if (!matricesWeightsData || !matricesIndicesData) {
  34449. return this;
  34450. }
  34451. var needExtras = this.numBoneInfluencers > 4;
  34452. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34453. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34454. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34455. var tempVector3 = BABYLON.Vector3.Zero();
  34456. var finalMatrix = new BABYLON.Matrix();
  34457. var tempMatrix = new BABYLON.Matrix();
  34458. var matWeightIdx = 0;
  34459. var inf;
  34460. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34461. var weight;
  34462. for (inf = 0; inf < 4; inf++) {
  34463. weight = matricesWeightsData[matWeightIdx + inf];
  34464. if (weight > 0) {
  34465. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34466. finalMatrix.addToSelf(tempMatrix);
  34467. }
  34468. else
  34469. break;
  34470. }
  34471. if (needExtras) {
  34472. for (inf = 0; inf < 4; inf++) {
  34473. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34474. if (weight > 0) {
  34475. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34476. finalMatrix.addToSelf(tempMatrix);
  34477. }
  34478. else
  34479. break;
  34480. }
  34481. }
  34482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34483. tempVector3.toArray(positionsData, index);
  34484. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34485. tempVector3.toArray(normalsData, index);
  34486. finalMatrix.reset();
  34487. }
  34488. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34489. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34490. return this;
  34491. };
  34492. // Tools
  34493. /**
  34494. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34495. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34496. */
  34497. Mesh.MinMax = function (meshes) {
  34498. var minVector = null;
  34499. var maxVector = null;
  34500. meshes.forEach(function (mesh, index, array) {
  34501. var boundingInfo = mesh.getBoundingInfo();
  34502. var boundingBox = boundingInfo.boundingBox;
  34503. if (!minVector || !maxVector) {
  34504. minVector = boundingBox.minimumWorld;
  34505. maxVector = boundingBox.maximumWorld;
  34506. }
  34507. else {
  34508. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34509. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34510. }
  34511. });
  34512. if (!minVector || !maxVector) {
  34513. return {
  34514. min: BABYLON.Vector3.Zero(),
  34515. max: BABYLON.Vector3.Zero()
  34516. };
  34517. }
  34518. return {
  34519. min: minVector,
  34520. max: maxVector
  34521. };
  34522. };
  34523. /**
  34524. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34525. */
  34526. Mesh.Center = function (meshesOrMinMaxVector) {
  34527. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34528. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34529. };
  34530. /**
  34531. * Merge the array of meshes into a single mesh for performance reasons.
  34532. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34533. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34534. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34535. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34536. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34537. */
  34538. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34539. if (disposeSource === void 0) { disposeSource = true; }
  34540. var index;
  34541. if (!allow32BitsIndices) {
  34542. var totalVertices = 0;
  34543. // Counting vertices
  34544. for (index = 0; index < meshes.length; index++) {
  34545. if (meshes[index]) {
  34546. totalVertices += meshes[index].getTotalVertices();
  34547. if (totalVertices > 65536) {
  34548. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34549. return null;
  34550. }
  34551. }
  34552. }
  34553. }
  34554. // Merge
  34555. var vertexData = null;
  34556. var otherVertexData;
  34557. var indiceArray = new Array();
  34558. var source = null;
  34559. for (index = 0; index < meshes.length; index++) {
  34560. if (meshes[index]) {
  34561. meshes[index].computeWorldMatrix(true);
  34562. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34563. otherVertexData.transform(meshes[index].getWorldMatrix());
  34564. if (vertexData) {
  34565. vertexData.merge(otherVertexData);
  34566. }
  34567. else {
  34568. vertexData = otherVertexData;
  34569. source = meshes[index];
  34570. }
  34571. if (subdivideWithSubMeshes) {
  34572. indiceArray.push(meshes[index].getTotalIndices());
  34573. }
  34574. }
  34575. }
  34576. source = source;
  34577. if (!meshSubclass) {
  34578. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34579. }
  34580. vertexData.applyToMesh(meshSubclass);
  34581. // Setting properties
  34582. meshSubclass.material = source.material;
  34583. meshSubclass.checkCollisions = source.checkCollisions;
  34584. // Cleaning
  34585. if (disposeSource) {
  34586. for (index = 0; index < meshes.length; index++) {
  34587. if (meshes[index]) {
  34588. meshes[index].dispose();
  34589. }
  34590. }
  34591. }
  34592. // Subdivide
  34593. if (subdivideWithSubMeshes) {
  34594. //-- removal of global submesh
  34595. meshSubclass.releaseSubMeshes();
  34596. index = 0;
  34597. var offset = 0;
  34598. //-- apply subdivision according to index table
  34599. while (index < indiceArray.length) {
  34600. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34601. offset += indiceArray[index];
  34602. index++;
  34603. }
  34604. }
  34605. return meshSubclass;
  34606. };
  34607. // Consts
  34608. Mesh._FRONTSIDE = 0;
  34609. Mesh._BACKSIDE = 1;
  34610. Mesh._DOUBLESIDE = 2;
  34611. Mesh._DEFAULTSIDE = 0;
  34612. Mesh._NO_CAP = 0;
  34613. Mesh._CAP_START = 1;
  34614. Mesh._CAP_END = 2;
  34615. Mesh._CAP_ALL = 3;
  34616. return Mesh;
  34617. }(BABYLON.AbstractMesh));
  34618. BABYLON.Mesh = Mesh;
  34619. })(BABYLON || (BABYLON = {}));
  34620. //# sourceMappingURL=babylon.mesh.js.map
  34621. var BABYLON;
  34622. (function (BABYLON) {
  34623. var BaseSubMesh = /** @class */ (function () {
  34624. function BaseSubMesh() {
  34625. }
  34626. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34627. get: function () {
  34628. return this._materialEffect;
  34629. },
  34630. enumerable: true,
  34631. configurable: true
  34632. });
  34633. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34634. if (defines === void 0) { defines = null; }
  34635. if (this._materialEffect === effect) {
  34636. if (!effect) {
  34637. this._materialDefines = null;
  34638. }
  34639. return;
  34640. }
  34641. this._materialDefines = defines;
  34642. this._materialEffect = effect;
  34643. };
  34644. return BaseSubMesh;
  34645. }());
  34646. BABYLON.BaseSubMesh = BaseSubMesh;
  34647. var SubMesh = /** @class */ (function (_super) {
  34648. __extends(SubMesh, _super);
  34649. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34650. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34651. var _this = _super.call(this) || this;
  34652. _this.materialIndex = materialIndex;
  34653. _this.verticesStart = verticesStart;
  34654. _this.verticesCount = verticesCount;
  34655. _this.indexStart = indexStart;
  34656. _this.indexCount = indexCount;
  34657. _this._renderId = 0;
  34658. _this._mesh = mesh;
  34659. _this._renderingMesh = renderingMesh || mesh;
  34660. mesh.subMeshes.push(_this);
  34661. _this._trianglePlanes = [];
  34662. _this._id = mesh.subMeshes.length - 1;
  34663. if (createBoundingBox) {
  34664. _this.refreshBoundingInfo();
  34665. mesh.computeWorldMatrix(true);
  34666. }
  34667. return _this;
  34668. }
  34669. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34670. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34671. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34672. };
  34673. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34674. get: function () {
  34675. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34676. },
  34677. enumerable: true,
  34678. configurable: true
  34679. });
  34680. /**
  34681. * Returns the submesh BoudingInfo object.
  34682. */
  34683. SubMesh.prototype.getBoundingInfo = function () {
  34684. if (this.IsGlobal) {
  34685. return this._mesh.getBoundingInfo();
  34686. }
  34687. return this._boundingInfo;
  34688. };
  34689. /**
  34690. * Sets the submesh BoundingInfo.
  34691. * Return the SubMesh.
  34692. */
  34693. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34694. this._boundingInfo = boundingInfo;
  34695. return this;
  34696. };
  34697. /**
  34698. * Returns the mesh of the current submesh.
  34699. */
  34700. SubMesh.prototype.getMesh = function () {
  34701. return this._mesh;
  34702. };
  34703. /**
  34704. * Returns the rendering mesh of the submesh.
  34705. */
  34706. SubMesh.prototype.getRenderingMesh = function () {
  34707. return this._renderingMesh;
  34708. };
  34709. /**
  34710. * Returns the submesh material.
  34711. */
  34712. SubMesh.prototype.getMaterial = function () {
  34713. var rootMaterial = this._renderingMesh.material;
  34714. if (rootMaterial === null || rootMaterial === undefined) {
  34715. return this._mesh.getScene().defaultMaterial;
  34716. }
  34717. else if (rootMaterial.getSubMaterial) {
  34718. var multiMaterial = rootMaterial;
  34719. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34720. if (this._currentMaterial !== effectiveMaterial) {
  34721. this._currentMaterial = effectiveMaterial;
  34722. this._materialDefines = null;
  34723. }
  34724. return effectiveMaterial;
  34725. }
  34726. return rootMaterial;
  34727. };
  34728. // Methods
  34729. /**
  34730. * Sets a new updated BoundingInfo object to the submesh.
  34731. * Returns the SubMesh.
  34732. */
  34733. SubMesh.prototype.refreshBoundingInfo = function () {
  34734. this._lastColliderWorldVertices = null;
  34735. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34736. return this;
  34737. }
  34738. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34739. if (!data) {
  34740. this._boundingInfo = this._mesh.getBoundingInfo();
  34741. return this;
  34742. }
  34743. var indices = this._renderingMesh.getIndices();
  34744. var extend;
  34745. //is this the only submesh?
  34746. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34747. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34748. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34749. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34750. }
  34751. else {
  34752. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34753. }
  34754. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34755. return this;
  34756. };
  34757. SubMesh.prototype._checkCollision = function (collider) {
  34758. var boundingInfo = this.getBoundingInfo();
  34759. return boundingInfo._checkCollision(collider);
  34760. };
  34761. /**
  34762. * Updates the submesh BoundingInfo.
  34763. * Returns the Submesh.
  34764. */
  34765. SubMesh.prototype.updateBoundingInfo = function (world) {
  34766. var boundingInfo = this.getBoundingInfo();
  34767. if (!boundingInfo) {
  34768. this.refreshBoundingInfo();
  34769. boundingInfo = this.getBoundingInfo();
  34770. }
  34771. boundingInfo.update(world);
  34772. return this;
  34773. };
  34774. /**
  34775. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34776. * Boolean returned.
  34777. */
  34778. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34779. var boundingInfo = this.getBoundingInfo();
  34780. if (!boundingInfo) {
  34781. return false;
  34782. }
  34783. return boundingInfo.isInFrustum(frustumPlanes);
  34784. };
  34785. /**
  34786. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34787. * Boolean returned.
  34788. */
  34789. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34790. var boundingInfo = this.getBoundingInfo();
  34791. if (!boundingInfo) {
  34792. return false;
  34793. }
  34794. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34795. };
  34796. /**
  34797. * Renders the submesh.
  34798. * Returns it.
  34799. */
  34800. SubMesh.prototype.render = function (enableAlphaMode) {
  34801. this._renderingMesh.render(this, enableAlphaMode);
  34802. return this;
  34803. };
  34804. /**
  34805. * Returns a new Index Buffer.
  34806. * Type returned : WebGLBuffer.
  34807. */
  34808. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34809. if (!this._linesIndexBuffer) {
  34810. var linesIndices = [];
  34811. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34812. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34813. }
  34814. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34815. this.linesIndexCount = linesIndices.length;
  34816. }
  34817. return this._linesIndexBuffer;
  34818. };
  34819. /**
  34820. * True is the passed Ray intersects the submesh bounding box.
  34821. * Boolean returned.
  34822. */
  34823. SubMesh.prototype.canIntersects = function (ray) {
  34824. var boundingInfo = this.getBoundingInfo();
  34825. if (!boundingInfo) {
  34826. return false;
  34827. }
  34828. return ray.intersectsBox(boundingInfo.boundingBox);
  34829. };
  34830. /**
  34831. * Returns an object IntersectionInfo.
  34832. */
  34833. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34834. var intersectInfo = null;
  34835. var material = this.getMaterial();
  34836. if (!material) {
  34837. return null;
  34838. }
  34839. switch (material.fillMode) {
  34840. case BABYLON.Material.PointListDrawMode:
  34841. case BABYLON.Material.LineListDrawMode:
  34842. case BABYLON.Material.LineLoopDrawMode:
  34843. case BABYLON.Material.LineStripDrawMode:
  34844. case BABYLON.Material.TriangleFanDrawMode:
  34845. case BABYLON.Material.TriangleStripDrawMode:
  34846. return null;
  34847. }
  34848. // LineMesh first as it's also a Mesh...
  34849. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34850. var lineMesh = this._mesh;
  34851. // Line test
  34852. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34853. var p0 = positions[indices[index]];
  34854. var p1 = positions[indices[index + 1]];
  34855. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34856. if (length < 0) {
  34857. continue;
  34858. }
  34859. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34860. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34861. if (fastCheck) {
  34862. break;
  34863. }
  34864. }
  34865. }
  34866. }
  34867. else {
  34868. // Triangles test
  34869. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34870. var p0 = positions[indices[index]];
  34871. var p1 = positions[indices[index + 1]];
  34872. var p2 = positions[indices[index + 2]];
  34873. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34874. if (currentIntersectInfo) {
  34875. if (currentIntersectInfo.distance < 0) {
  34876. continue;
  34877. }
  34878. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34879. intersectInfo = currentIntersectInfo;
  34880. intersectInfo.faceId = index / 3;
  34881. if (fastCheck) {
  34882. break;
  34883. }
  34884. }
  34885. }
  34886. }
  34887. }
  34888. return intersectInfo;
  34889. };
  34890. SubMesh.prototype._rebuild = function () {
  34891. if (this._linesIndexBuffer) {
  34892. this._linesIndexBuffer = null;
  34893. }
  34894. };
  34895. // Clone
  34896. /**
  34897. * Creates a new Submesh from the passed Mesh.
  34898. */
  34899. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34900. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34901. if (!this.IsGlobal) {
  34902. var boundingInfo = this.getBoundingInfo();
  34903. if (!boundingInfo) {
  34904. return result;
  34905. }
  34906. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34907. }
  34908. return result;
  34909. };
  34910. // Dispose
  34911. /**
  34912. * Disposes the Submesh.
  34913. * Returns nothing.
  34914. */
  34915. SubMesh.prototype.dispose = function () {
  34916. if (this._linesIndexBuffer) {
  34917. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34918. this._linesIndexBuffer = null;
  34919. }
  34920. // Remove from mesh
  34921. var index = this._mesh.subMeshes.indexOf(this);
  34922. this._mesh.subMeshes.splice(index, 1);
  34923. };
  34924. // Statics
  34925. /**
  34926. * Creates a new Submesh from the passed parameters :
  34927. * - materialIndex (integer) : the index of the main mesh material.
  34928. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34929. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34930. * - mesh (Mesh) : the main mesh to create the submesh from.
  34931. * - renderingMesh (optional Mesh) : rendering mesh.
  34932. */
  34933. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34934. var minVertexIndex = Number.MAX_VALUE;
  34935. var maxVertexIndex = -Number.MAX_VALUE;
  34936. renderingMesh = (renderingMesh || mesh);
  34937. var indices = renderingMesh.getIndices();
  34938. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34939. var vertexIndex = indices[index];
  34940. if (vertexIndex < minVertexIndex)
  34941. minVertexIndex = vertexIndex;
  34942. if (vertexIndex > maxVertexIndex)
  34943. maxVertexIndex = vertexIndex;
  34944. }
  34945. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34946. };
  34947. return SubMesh;
  34948. }(BaseSubMesh));
  34949. BABYLON.SubMesh = SubMesh;
  34950. })(BABYLON || (BABYLON = {}));
  34951. //# sourceMappingURL=babylon.subMesh.js.map
  34952. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34953. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34954. s = arguments[i];
  34955. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34956. t[p] = s[p];
  34957. }
  34958. return t;
  34959. };
  34960. var BABYLON;
  34961. (function (BABYLON) {
  34962. /**
  34963. * Manages the defines for the Material
  34964. */
  34965. var MaterialDefines = /** @class */ (function () {
  34966. function MaterialDefines() {
  34967. this._isDirty = true;
  34968. /** @hidden */
  34969. this._areLightsDirty = true;
  34970. /** @hidden */
  34971. this._areAttributesDirty = true;
  34972. /** @hidden */
  34973. this._areTexturesDirty = true;
  34974. /** @hidden */
  34975. this._areFresnelDirty = true;
  34976. /** @hidden */
  34977. this._areMiscDirty = true;
  34978. /** @hidden */
  34979. this._areImageProcessingDirty = true;
  34980. /** @hidden */
  34981. this._normals = false;
  34982. /** @hidden */
  34983. this._uvs = false;
  34984. /** @hidden */
  34985. this._needNormals = false;
  34986. /** @hidden */
  34987. this._needUVs = false;
  34988. }
  34989. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34990. /**
  34991. * Specifies if the material needs to be re-calculated
  34992. */
  34993. get: function () {
  34994. return this._isDirty;
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. /**
  35000. * Marks the material to indicate that it has been re-calculated
  35001. */
  35002. MaterialDefines.prototype.markAsProcessed = function () {
  35003. this._isDirty = false;
  35004. this._areAttributesDirty = false;
  35005. this._areTexturesDirty = false;
  35006. this._areFresnelDirty = false;
  35007. this._areLightsDirty = false;
  35008. this._areMiscDirty = false;
  35009. this._areImageProcessingDirty = false;
  35010. };
  35011. /**
  35012. * Marks the material to indicate that it needs to be re-calculated
  35013. */
  35014. MaterialDefines.prototype.markAsUnprocessed = function () {
  35015. this._isDirty = true;
  35016. };
  35017. /**
  35018. * Marks the material to indicate all of its defines need to be re-calculated
  35019. */
  35020. MaterialDefines.prototype.markAllAsDirty = function () {
  35021. this._areTexturesDirty = true;
  35022. this._areAttributesDirty = true;
  35023. this._areLightsDirty = true;
  35024. this._areFresnelDirty = true;
  35025. this._areMiscDirty = true;
  35026. this._areImageProcessingDirty = true;
  35027. this._isDirty = true;
  35028. };
  35029. /**
  35030. * Marks the material to indicate that image processing needs to be re-calculated
  35031. */
  35032. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35033. this._areImageProcessingDirty = true;
  35034. this._isDirty = true;
  35035. };
  35036. /**
  35037. * Marks the material to indicate the lights need to be re-calculated
  35038. */
  35039. MaterialDefines.prototype.markAsLightDirty = function () {
  35040. this._areLightsDirty = true;
  35041. this._isDirty = true;
  35042. };
  35043. /**
  35044. * Marks the attribute state as changed
  35045. */
  35046. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35047. this._areAttributesDirty = true;
  35048. this._isDirty = true;
  35049. };
  35050. /**
  35051. * Marks the texture state as changed
  35052. */
  35053. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35054. this._areTexturesDirty = true;
  35055. this._isDirty = true;
  35056. };
  35057. /**
  35058. * Marks the fresnel state as changed
  35059. */
  35060. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35061. this._areFresnelDirty = true;
  35062. this._isDirty = true;
  35063. };
  35064. /**
  35065. * Marks the misc state as changed
  35066. */
  35067. MaterialDefines.prototype.markAsMiscDirty = function () {
  35068. this._areMiscDirty = true;
  35069. this._isDirty = true;
  35070. };
  35071. /**
  35072. * Rebuilds the material defines
  35073. */
  35074. MaterialDefines.prototype.rebuild = function () {
  35075. if (this._keys) {
  35076. delete this._keys;
  35077. }
  35078. this._keys = [];
  35079. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35080. var key = _a[_i];
  35081. if (key[0] === "_") {
  35082. continue;
  35083. }
  35084. this._keys.push(key);
  35085. }
  35086. };
  35087. /**
  35088. * Specifies if two material defines are equal
  35089. * @param other - A material define instance to compare to
  35090. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35091. */
  35092. MaterialDefines.prototype.isEqual = function (other) {
  35093. if (this._keys.length !== other._keys.length) {
  35094. return false;
  35095. }
  35096. for (var index = 0; index < this._keys.length; index++) {
  35097. var prop = this._keys[index];
  35098. if (this[prop] !== other[prop]) {
  35099. return false;
  35100. }
  35101. }
  35102. return true;
  35103. };
  35104. /**
  35105. * Clones this instance's defines to another instance
  35106. * @param other - material defines to clone values to
  35107. */
  35108. MaterialDefines.prototype.cloneTo = function (other) {
  35109. if (this._keys.length !== other._keys.length) {
  35110. other._keys = this._keys.slice(0);
  35111. }
  35112. for (var index = 0; index < this._keys.length; index++) {
  35113. var prop = this._keys[index];
  35114. other[prop] = this[prop];
  35115. }
  35116. };
  35117. /**
  35118. * Resets the material define values
  35119. */
  35120. MaterialDefines.prototype.reset = function () {
  35121. for (var index = 0; index < this._keys.length; index++) {
  35122. var prop = this._keys[index];
  35123. var type = typeof this[prop];
  35124. switch (type) {
  35125. case "number":
  35126. this[prop] = 0;
  35127. break;
  35128. case "string":
  35129. this[prop] = "";
  35130. break;
  35131. default:
  35132. this[prop] = false;
  35133. break;
  35134. }
  35135. }
  35136. };
  35137. /**
  35138. * Converts the material define values to a string
  35139. * @returns - String of material define information
  35140. */
  35141. MaterialDefines.prototype.toString = function () {
  35142. var result = "";
  35143. for (var index = 0; index < this._keys.length; index++) {
  35144. var prop = this._keys[index];
  35145. var value = this[prop];
  35146. var type = typeof value;
  35147. switch (type) {
  35148. case "number":
  35149. case "string":
  35150. result += "#define " + prop + " " + value + "\n";
  35151. break;
  35152. default:
  35153. if (value) {
  35154. result += "#define " + prop + "\n";
  35155. }
  35156. break;
  35157. }
  35158. }
  35159. return result;
  35160. };
  35161. return MaterialDefines;
  35162. }());
  35163. BABYLON.MaterialDefines = MaterialDefines;
  35164. /**
  35165. * Base class for the main features of a material in Babylon.js
  35166. */
  35167. var Material = /** @class */ (function () {
  35168. /**
  35169. * Creates a material instance
  35170. * @param name defines the name of the material
  35171. * @param scene defines the scene to reference
  35172. * @param doNotAdd specifies if the material should be added to the scene
  35173. */
  35174. function Material(name, scene, doNotAdd) {
  35175. /**
  35176. * Specifies if the ready state should be checked on each call
  35177. */
  35178. this.checkReadyOnEveryCall = false;
  35179. /**
  35180. * Specifies if the ready state should be checked once
  35181. */
  35182. this.checkReadyOnlyOnce = false;
  35183. /**
  35184. * The state of the material
  35185. */
  35186. this.state = "";
  35187. /**
  35188. * The alpha value of the material
  35189. */
  35190. this._alpha = 1.0;
  35191. /**
  35192. * Specifies if back face culling is enabled
  35193. */
  35194. this._backFaceCulling = true;
  35195. /**
  35196. * Specifies if the material should be serialized
  35197. */
  35198. this.doNotSerialize = false;
  35199. /**
  35200. * Specifies if the effect should be stored on sub meshes
  35201. */
  35202. this.storeEffectOnSubMeshes = false;
  35203. /**
  35204. * An event triggered when the material is disposed
  35205. */
  35206. this.onDisposeObservable = new BABYLON.Observable();
  35207. /**
  35208. * An event triggered when the material is bound
  35209. */
  35210. this.onBindObservable = new BABYLON.Observable();
  35211. /**
  35212. * An event triggered when the material is unbound
  35213. */
  35214. this.onUnBindObservable = new BABYLON.Observable();
  35215. /**
  35216. * Stores the value of the alpha mode
  35217. */
  35218. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35219. /**
  35220. * Stores the state of the need depth pre-pass value
  35221. */
  35222. this._needDepthPrePass = false;
  35223. /**
  35224. * Specifies if depth writing should be disabled
  35225. */
  35226. this.disableDepthWrite = false;
  35227. /**
  35228. * Specifies if depth writing should be forced
  35229. */
  35230. this.forceDepthWrite = false;
  35231. /**
  35232. * Specifies if there should be a separate pass for culling
  35233. */
  35234. this.separateCullingPass = false;
  35235. /**
  35236. * Stores the state specifing if fog should be enabled
  35237. */
  35238. this._fogEnabled = true;
  35239. /**
  35240. * Stores the size of points
  35241. */
  35242. this.pointSize = 1.0;
  35243. /**
  35244. * Stores the z offset value
  35245. */
  35246. this.zOffset = 0;
  35247. /**
  35248. * Specifies if the material was previously ready
  35249. */
  35250. this._wasPreviouslyReady = false;
  35251. /**
  35252. * Stores the fill mode state
  35253. */
  35254. this._fillMode = Material.TriangleFillMode;
  35255. this.name = name;
  35256. this.id = name || BABYLON.Tools.RandomId();
  35257. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35258. this.uniqueId = this._scene.getUniqueId();
  35259. if (this._scene.useRightHandedSystem) {
  35260. this.sideOrientation = Material.ClockWiseSideOrientation;
  35261. }
  35262. else {
  35263. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35264. }
  35265. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35266. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35267. if (!doNotAdd) {
  35268. this._scene.materials.push(this);
  35269. }
  35270. }
  35271. Object.defineProperty(Material, "TriangleFillMode", {
  35272. /**
  35273. * Returns the triangle fill mode
  35274. */
  35275. get: function () {
  35276. return Material._TriangleFillMode;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(Material, "WireFrameFillMode", {
  35282. /**
  35283. * Returns the wireframe mode
  35284. */
  35285. get: function () {
  35286. return Material._WireFrameFillMode;
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(Material, "PointFillMode", {
  35292. /**
  35293. * Returns the point fill mode
  35294. */
  35295. get: function () {
  35296. return Material._PointFillMode;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(Material, "PointListDrawMode", {
  35302. /**
  35303. * Returns the point list draw mode
  35304. */
  35305. get: function () {
  35306. return Material._PointListDrawMode;
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. Object.defineProperty(Material, "LineListDrawMode", {
  35312. /**
  35313. * Returns the line list draw mode
  35314. */
  35315. get: function () {
  35316. return Material._LineListDrawMode;
  35317. },
  35318. enumerable: true,
  35319. configurable: true
  35320. });
  35321. Object.defineProperty(Material, "LineLoopDrawMode", {
  35322. /**
  35323. * Returns the line loop draw mode
  35324. */
  35325. get: function () {
  35326. return Material._LineLoopDrawMode;
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(Material, "LineStripDrawMode", {
  35332. /**
  35333. * Returns the line strip draw mode
  35334. */
  35335. get: function () {
  35336. return Material._LineStripDrawMode;
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35342. /**
  35343. * Returns the triangle strip draw mode
  35344. */
  35345. get: function () {
  35346. return Material._TriangleStripDrawMode;
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35352. /**
  35353. * Returns the triangle fan draw mode
  35354. */
  35355. get: function () {
  35356. return Material._TriangleFanDrawMode;
  35357. },
  35358. enumerable: true,
  35359. configurable: true
  35360. });
  35361. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35362. /**
  35363. * Returns the clock-wise side orientation
  35364. */
  35365. get: function () {
  35366. return Material._ClockWiseSideOrientation;
  35367. },
  35368. enumerable: true,
  35369. configurable: true
  35370. });
  35371. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35372. /**
  35373. * Returns the counter clock-wise side orientation
  35374. */
  35375. get: function () {
  35376. return Material._CounterClockWiseSideOrientation;
  35377. },
  35378. enumerable: true,
  35379. configurable: true
  35380. });
  35381. Object.defineProperty(Material, "TextureDirtyFlag", {
  35382. /**
  35383. * Returns the dirty texture flag value
  35384. */
  35385. get: function () {
  35386. return Material._TextureDirtyFlag;
  35387. },
  35388. enumerable: true,
  35389. configurable: true
  35390. });
  35391. Object.defineProperty(Material, "LightDirtyFlag", {
  35392. /**
  35393. * Returns the dirty light flag value
  35394. */
  35395. get: function () {
  35396. return Material._LightDirtyFlag;
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35402. /**
  35403. * Returns the dirty fresnel flag value
  35404. */
  35405. get: function () {
  35406. return Material._FresnelDirtyFlag;
  35407. },
  35408. enumerable: true,
  35409. configurable: true
  35410. });
  35411. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35412. /**
  35413. * Returns the dirty attributes flag value
  35414. */
  35415. get: function () {
  35416. return Material._AttributesDirtyFlag;
  35417. },
  35418. enumerable: true,
  35419. configurable: true
  35420. });
  35421. Object.defineProperty(Material, "MiscDirtyFlag", {
  35422. /**
  35423. * Returns the dirty misc flag value
  35424. */
  35425. get: function () {
  35426. return Material._MiscDirtyFlag;
  35427. },
  35428. enumerable: true,
  35429. configurable: true
  35430. });
  35431. Object.defineProperty(Material.prototype, "alpha", {
  35432. /**
  35433. * Gets the alpha value of the material
  35434. */
  35435. get: function () {
  35436. return this._alpha;
  35437. },
  35438. /**
  35439. * Sets the alpha value of the material
  35440. */
  35441. set: function (value) {
  35442. if (this._alpha === value) {
  35443. return;
  35444. }
  35445. this._alpha = value;
  35446. this.markAsDirty(Material.MiscDirtyFlag);
  35447. },
  35448. enumerable: true,
  35449. configurable: true
  35450. });
  35451. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35452. /**
  35453. * Gets the back-face culling state
  35454. */
  35455. get: function () {
  35456. return this._backFaceCulling;
  35457. },
  35458. /**
  35459. * Sets the back-face culling state
  35460. */
  35461. set: function (value) {
  35462. if (this._backFaceCulling === value) {
  35463. return;
  35464. }
  35465. this._backFaceCulling = value;
  35466. this.markAsDirty(Material.TextureDirtyFlag);
  35467. },
  35468. enumerable: true,
  35469. configurable: true
  35470. });
  35471. Object.defineProperty(Material.prototype, "onDispose", {
  35472. /**
  35473. * Called during a dispose event
  35474. */
  35475. set: function (callback) {
  35476. if (this._onDisposeObserver) {
  35477. this.onDisposeObservable.remove(this._onDisposeObserver);
  35478. }
  35479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35480. },
  35481. enumerable: true,
  35482. configurable: true
  35483. });
  35484. Object.defineProperty(Material.prototype, "onBind", {
  35485. /**
  35486. * Called during a bind event
  35487. */
  35488. set: function (callback) {
  35489. if (this._onBindObserver) {
  35490. this.onBindObservable.remove(this._onBindObserver);
  35491. }
  35492. this._onBindObserver = this.onBindObservable.add(callback);
  35493. },
  35494. enumerable: true,
  35495. configurable: true
  35496. });
  35497. Object.defineProperty(Material.prototype, "alphaMode", {
  35498. /**
  35499. * Gets the value of the alpha mode
  35500. */
  35501. get: function () {
  35502. return this._alphaMode;
  35503. },
  35504. /**
  35505. * Sets the value of the alpha mode.
  35506. *
  35507. * | Value | Type | Description |
  35508. * | --- | --- | --- |
  35509. * | 0 | ALPHA_DISABLE | |
  35510. * | 1 | ALPHA_ADD | |
  35511. * | 2 | ALPHA_COMBINE | |
  35512. * | 3 | ALPHA_SUBTRACT | |
  35513. * | 4 | ALPHA_MULTIPLY | |
  35514. * | 5 | ALPHA_MAXIMIZED | |
  35515. * | 6 | ALPHA_ONEONE | |
  35516. * | 7 | ALPHA_PREMULTIPLIED | |
  35517. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35518. * | 9 | ALPHA_INTERPOLATE | |
  35519. * | 10 | ALPHA_SCREENMODE | |
  35520. *
  35521. */
  35522. set: function (value) {
  35523. if (this._alphaMode === value) {
  35524. return;
  35525. }
  35526. this._alphaMode = value;
  35527. this.markAsDirty(Material.TextureDirtyFlag);
  35528. },
  35529. enumerable: true,
  35530. configurable: true
  35531. });
  35532. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35533. /**
  35534. * Gets the depth pre-pass value
  35535. */
  35536. get: function () {
  35537. return this._needDepthPrePass;
  35538. },
  35539. /**
  35540. * Sets the need depth pre-pass value
  35541. */
  35542. set: function (value) {
  35543. if (this._needDepthPrePass === value) {
  35544. return;
  35545. }
  35546. this._needDepthPrePass = value;
  35547. if (this._needDepthPrePass) {
  35548. this.checkReadyOnEveryCall = true;
  35549. }
  35550. },
  35551. enumerable: true,
  35552. configurable: true
  35553. });
  35554. Object.defineProperty(Material.prototype, "fogEnabled", {
  35555. /**
  35556. * Gets the value of the fog enabled state
  35557. */
  35558. get: function () {
  35559. return this._fogEnabled;
  35560. },
  35561. /**
  35562. * Sets the state for enabling fog
  35563. */
  35564. set: function (value) {
  35565. if (this._fogEnabled === value) {
  35566. return;
  35567. }
  35568. this._fogEnabled = value;
  35569. this.markAsDirty(Material.MiscDirtyFlag);
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. Object.defineProperty(Material.prototype, "wireframe", {
  35575. /**
  35576. * Gets a value specifying if wireframe mode is enabled
  35577. */
  35578. get: function () {
  35579. switch (this._fillMode) {
  35580. case Material.WireFrameFillMode:
  35581. case Material.LineListDrawMode:
  35582. case Material.LineLoopDrawMode:
  35583. case Material.LineStripDrawMode:
  35584. return true;
  35585. }
  35586. return this._scene.forceWireframe;
  35587. },
  35588. /**
  35589. * Sets the state of wireframe mode
  35590. */
  35591. set: function (value) {
  35592. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35593. },
  35594. enumerable: true,
  35595. configurable: true
  35596. });
  35597. Object.defineProperty(Material.prototype, "pointsCloud", {
  35598. /**
  35599. * Gets the value specifying if point clouds are enabled
  35600. */
  35601. get: function () {
  35602. switch (this._fillMode) {
  35603. case Material.PointFillMode:
  35604. case Material.PointListDrawMode:
  35605. return true;
  35606. }
  35607. return this._scene.forcePointsCloud;
  35608. },
  35609. /**
  35610. * Sets the state of point cloud mode
  35611. */
  35612. set: function (value) {
  35613. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. Object.defineProperty(Material.prototype, "fillMode", {
  35619. /**
  35620. * Gets the material fill mode
  35621. */
  35622. get: function () {
  35623. return this._fillMode;
  35624. },
  35625. /**
  35626. * Sets the material fill mode
  35627. */
  35628. set: function (value) {
  35629. if (this._fillMode === value) {
  35630. return;
  35631. }
  35632. this._fillMode = value;
  35633. this.markAsDirty(Material.MiscDirtyFlag);
  35634. },
  35635. enumerable: true,
  35636. configurable: true
  35637. });
  35638. /**
  35639. * Returns a string representation of the current material
  35640. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35641. * @returns a string with material information
  35642. */
  35643. Material.prototype.toString = function (fullDetails) {
  35644. var ret = "Name: " + this.name;
  35645. if (fullDetails) {
  35646. }
  35647. return ret;
  35648. };
  35649. /**
  35650. * Gets the class name of the material
  35651. * @returns a string with the class name of the material
  35652. */
  35653. Material.prototype.getClassName = function () {
  35654. return "Material";
  35655. };
  35656. Object.defineProperty(Material.prototype, "isFrozen", {
  35657. /**
  35658. * Specifies if updates for the material been locked
  35659. */
  35660. get: function () {
  35661. return this.checkReadyOnlyOnce;
  35662. },
  35663. enumerable: true,
  35664. configurable: true
  35665. });
  35666. /**
  35667. * Locks updates for the material
  35668. */
  35669. Material.prototype.freeze = function () {
  35670. this.checkReadyOnlyOnce = true;
  35671. };
  35672. /**
  35673. * Unlocks updates for the material
  35674. */
  35675. Material.prototype.unfreeze = function () {
  35676. this.checkReadyOnlyOnce = false;
  35677. };
  35678. /**
  35679. * Specifies if the material is ready to be used
  35680. * @param mesh defines the mesh to check
  35681. * @param useInstances specifies if instances should be used
  35682. * @returns a boolean indicating if the material is ready to be used
  35683. */
  35684. Material.prototype.isReady = function (mesh, useInstances) {
  35685. return true;
  35686. };
  35687. /**
  35688. * Specifies that the submesh is ready to be used
  35689. * @param mesh defines the mesh to check
  35690. * @param subMesh defines which submesh to check
  35691. * @param useInstances specifies that instances should be used
  35692. * @returns a boolean indicating that the submesh is ready or not
  35693. */
  35694. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35695. return false;
  35696. };
  35697. /**
  35698. * Returns the material effect
  35699. * @returns the effect associated with the material
  35700. */
  35701. Material.prototype.getEffect = function () {
  35702. return this._effect;
  35703. };
  35704. /**
  35705. * Returns the current scene
  35706. * @returns a Scene
  35707. */
  35708. Material.prototype.getScene = function () {
  35709. return this._scene;
  35710. };
  35711. /**
  35712. * Specifies if the material will require alpha blending
  35713. * @returns a boolean specifying if alpha blending is needed
  35714. */
  35715. Material.prototype.needAlphaBlending = function () {
  35716. return (this.alpha < 1.0);
  35717. };
  35718. /**
  35719. * Specifies if the mesh will require alpha blending
  35720. * @param mesh defines the mesh to check
  35721. * @returns a boolean specifying if alpha blending is needed for the mesh
  35722. */
  35723. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35724. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35725. };
  35726. /**
  35727. * Specifies if this material should be rendered in alpha test mode
  35728. * @returns a boolean specifying if an alpha test is needed.
  35729. */
  35730. Material.prototype.needAlphaTesting = function () {
  35731. return false;
  35732. };
  35733. /**
  35734. * Gets the texture used for the alpha test
  35735. * @returns the texture to use for alpha testing
  35736. */
  35737. Material.prototype.getAlphaTestTexture = function () {
  35738. return null;
  35739. };
  35740. /**
  35741. * Marks the material to indicate that it needs to be re-calculated
  35742. */
  35743. Material.prototype.markDirty = function () {
  35744. this._wasPreviouslyReady = false;
  35745. };
  35746. /** @hidden */
  35747. Material.prototype._preBind = function (effect, overrideOrientation) {
  35748. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35749. var engine = this._scene.getEngine();
  35750. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35751. var reverse = orientation === Material.ClockWiseSideOrientation;
  35752. engine.enableEffect(effect ? effect : this._effect);
  35753. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35754. return reverse;
  35755. };
  35756. /**
  35757. * Binds the material to the mesh
  35758. * @param world defines the world transformation matrix
  35759. * @param mesh defines the mesh to bind the material to
  35760. */
  35761. Material.prototype.bind = function (world, mesh) {
  35762. };
  35763. /**
  35764. * Binds the submesh to the material
  35765. * @param world defines the world transformation matrix
  35766. * @param mesh defines the mesh containing the submesh
  35767. * @param subMesh defines the submesh to bind the material to
  35768. */
  35769. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35770. };
  35771. /**
  35772. * Binds the world matrix to the material
  35773. * @param world defines the world transformation matrix
  35774. */
  35775. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35776. };
  35777. /**
  35778. * Binds the scene's uniform buffer to the effect.
  35779. * @param effect defines the effect to bind to the scene uniform buffer
  35780. * @param sceneUbo defines the uniform buffer storing scene data
  35781. */
  35782. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35783. sceneUbo.bindToEffect(effect, "Scene");
  35784. };
  35785. /**
  35786. * Binds the view matrix to the effect
  35787. * @param effect defines the effect to bind the view matrix to
  35788. */
  35789. Material.prototype.bindView = function (effect) {
  35790. if (!this._useUBO) {
  35791. effect.setMatrix("view", this.getScene().getViewMatrix());
  35792. }
  35793. else {
  35794. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35795. }
  35796. };
  35797. /**
  35798. * Binds the view projection matrix to the effect
  35799. * @param effect defines the effect to bind the view projection matrix to
  35800. */
  35801. Material.prototype.bindViewProjection = function (effect) {
  35802. if (!this._useUBO) {
  35803. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35804. }
  35805. else {
  35806. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35807. }
  35808. };
  35809. /**
  35810. * Specifies if material alpha testing should be turned on for the mesh
  35811. * @param mesh defines the mesh to check
  35812. */
  35813. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35814. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35815. };
  35816. /**
  35817. * Processes to execute after binding the material to a mesh
  35818. * @param mesh defines the rendered mesh
  35819. */
  35820. Material.prototype._afterBind = function (mesh) {
  35821. this._scene._cachedMaterial = this;
  35822. if (mesh) {
  35823. this._scene._cachedVisibility = mesh.visibility;
  35824. }
  35825. else {
  35826. this._scene._cachedVisibility = 1;
  35827. }
  35828. if (mesh) {
  35829. this.onBindObservable.notifyObservers(mesh);
  35830. }
  35831. if (this.disableDepthWrite) {
  35832. var engine = this._scene.getEngine();
  35833. this._cachedDepthWriteState = engine.getDepthWrite();
  35834. engine.setDepthWrite(false);
  35835. }
  35836. };
  35837. /**
  35838. * Unbinds the material from the mesh
  35839. */
  35840. Material.prototype.unbind = function () {
  35841. this.onUnBindObservable.notifyObservers(this);
  35842. if (this.disableDepthWrite) {
  35843. var engine = this._scene.getEngine();
  35844. engine.setDepthWrite(this._cachedDepthWriteState);
  35845. }
  35846. };
  35847. /**
  35848. * Gets the active textures from the material
  35849. * @returns an array of textures
  35850. */
  35851. Material.prototype.getActiveTextures = function () {
  35852. return [];
  35853. };
  35854. /**
  35855. * Specifies if the material uses a texture
  35856. * @param texture defines the texture to check against the material
  35857. * @returns a boolean specifying if the material uses the texture
  35858. */
  35859. Material.prototype.hasTexture = function (texture) {
  35860. return false;
  35861. };
  35862. /**
  35863. * Makes a duplicate of the material, and gives it a new name
  35864. * @param name defines the new name for the duplicated material
  35865. * @returns the cloned material
  35866. */
  35867. Material.prototype.clone = function (name) {
  35868. return null;
  35869. };
  35870. /**
  35871. * Gets the meshes bound to the material
  35872. * @returns an array of meshes bound to the material
  35873. */
  35874. Material.prototype.getBindedMeshes = function () {
  35875. var result = new Array();
  35876. for (var index = 0; index < this._scene.meshes.length; index++) {
  35877. var mesh = this._scene.meshes[index];
  35878. if (mesh.material === this) {
  35879. result.push(mesh);
  35880. }
  35881. }
  35882. return result;
  35883. };
  35884. /**
  35885. * Force shader compilation
  35886. * @param mesh defines the mesh associated with this material
  35887. * @param onCompiled defines a function to execute once the material is compiled
  35888. * @param options defines the options to configure the compilation
  35889. */
  35890. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35891. var _this = this;
  35892. var localOptions = __assign({ clipPlane: false }, options);
  35893. var subMesh = new BABYLON.BaseSubMesh();
  35894. var scene = this.getScene();
  35895. var checkReady = function () {
  35896. if (!_this._scene || !_this._scene.getEngine()) {
  35897. return;
  35898. }
  35899. if (subMesh._materialDefines) {
  35900. subMesh._materialDefines._renderId = -1;
  35901. }
  35902. var clipPlaneState = scene.clipPlane;
  35903. if (localOptions.clipPlane) {
  35904. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35905. }
  35906. if (_this.storeEffectOnSubMeshes) {
  35907. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35908. if (onCompiled) {
  35909. onCompiled(_this);
  35910. }
  35911. }
  35912. else {
  35913. setTimeout(checkReady, 16);
  35914. }
  35915. }
  35916. else {
  35917. if (_this.isReady(mesh)) {
  35918. if (onCompiled) {
  35919. onCompiled(_this);
  35920. }
  35921. }
  35922. else {
  35923. setTimeout(checkReady, 16);
  35924. }
  35925. }
  35926. if (localOptions.clipPlane) {
  35927. scene.clipPlane = clipPlaneState;
  35928. }
  35929. };
  35930. checkReady();
  35931. };
  35932. /**
  35933. * Force shader compilation
  35934. * @param mesh defines the mesh that will use this material
  35935. * @param options defines additional options for compiling the shaders
  35936. * @returns a promise that resolves when the compilation completes
  35937. */
  35938. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35939. var _this = this;
  35940. return new Promise(function (resolve) {
  35941. _this.forceCompilation(mesh, function () {
  35942. resolve();
  35943. }, options);
  35944. });
  35945. };
  35946. /**
  35947. * Marks a define in the material to indicate that it needs to be re-computed
  35948. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35949. */
  35950. Material.prototype.markAsDirty = function (flag) {
  35951. if (flag & Material.TextureDirtyFlag) {
  35952. this._markAllSubMeshesAsTexturesDirty();
  35953. }
  35954. if (flag & Material.LightDirtyFlag) {
  35955. this._markAllSubMeshesAsLightsDirty();
  35956. }
  35957. if (flag & Material.FresnelDirtyFlag) {
  35958. this._markAllSubMeshesAsFresnelDirty();
  35959. }
  35960. if (flag & Material.AttributesDirtyFlag) {
  35961. this._markAllSubMeshesAsAttributesDirty();
  35962. }
  35963. if (flag & Material.MiscDirtyFlag) {
  35964. this._markAllSubMeshesAsMiscDirty();
  35965. }
  35966. this.getScene().resetCachedMaterial();
  35967. };
  35968. /**
  35969. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35970. * @param func defines a function which checks material defines against the submeshes
  35971. */
  35972. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35973. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35974. var mesh = _a[_i];
  35975. if (!mesh.subMeshes) {
  35976. continue;
  35977. }
  35978. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35979. var subMesh = _c[_b];
  35980. if (subMesh.getMaterial() !== this) {
  35981. continue;
  35982. }
  35983. if (!subMesh._materialDefines) {
  35984. continue;
  35985. }
  35986. func(subMesh._materialDefines);
  35987. }
  35988. }
  35989. };
  35990. /**
  35991. * Indicates that image processing needs to be re-calculated for all submeshes
  35992. */
  35993. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35994. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35995. };
  35996. /**
  35997. * Indicates that textures need to be re-calculated for all submeshes
  35998. */
  35999. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36000. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36001. };
  36002. /**
  36003. * Indicates that fresnel needs to be re-calculated for all submeshes
  36004. */
  36005. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36006. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36007. };
  36008. /**
  36009. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36010. */
  36011. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36012. this._markAllSubMeshesAsDirty(function (defines) {
  36013. defines.markAsFresnelDirty();
  36014. defines.markAsMiscDirty();
  36015. });
  36016. };
  36017. /**
  36018. * Indicates that lights need to be re-calculated for all submeshes
  36019. */
  36020. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36021. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36022. };
  36023. /**
  36024. * Indicates that attributes need to be re-calculated for all submeshes
  36025. */
  36026. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36027. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36028. };
  36029. /**
  36030. * Indicates that misc needs to be re-calculated for all submeshes
  36031. */
  36032. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36033. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36034. };
  36035. /**
  36036. * Indicates that textures and misc need to be re-calculated for all submeshes
  36037. */
  36038. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36039. this._markAllSubMeshesAsDirty(function (defines) {
  36040. defines.markAsTexturesDirty();
  36041. defines.markAsMiscDirty();
  36042. });
  36043. };
  36044. /**
  36045. * Disposes the material
  36046. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36047. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36048. */
  36049. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36050. // Animations
  36051. this.getScene().stopAnimation(this);
  36052. this.getScene().freeProcessedMaterials();
  36053. // Remove from scene
  36054. var index = this._scene.materials.indexOf(this);
  36055. if (index >= 0) {
  36056. this._scene.materials.splice(index, 1);
  36057. }
  36058. // Remove from meshes
  36059. for (index = 0; index < this._scene.meshes.length; index++) {
  36060. var mesh = this._scene.meshes[index];
  36061. if (mesh.material === this) {
  36062. mesh.material = null;
  36063. if (mesh.geometry) {
  36064. var geometry = (mesh.geometry);
  36065. if (this.storeEffectOnSubMeshes) {
  36066. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36067. var subMesh = _a[_i];
  36068. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36069. if (forceDisposeEffect && subMesh._materialEffect) {
  36070. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36071. }
  36072. }
  36073. }
  36074. else {
  36075. geometry._releaseVertexArrayObject(this._effect);
  36076. }
  36077. }
  36078. }
  36079. }
  36080. this._uniformBuffer.dispose();
  36081. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36082. if (forceDisposeEffect && this._effect) {
  36083. if (!this.storeEffectOnSubMeshes) {
  36084. this._scene.getEngine()._releaseEffect(this._effect);
  36085. }
  36086. this._effect = null;
  36087. }
  36088. // Callback
  36089. this.onDisposeObservable.notifyObservers(this);
  36090. this.onDisposeObservable.clear();
  36091. this.onBindObservable.clear();
  36092. this.onUnBindObservable.clear();
  36093. };
  36094. /**
  36095. * Serializes this material
  36096. * @returns the serialized material object
  36097. */
  36098. Material.prototype.serialize = function () {
  36099. return BABYLON.SerializationHelper.Serialize(this);
  36100. };
  36101. /**
  36102. * Creates a MultiMaterial from parsed MultiMaterial data.
  36103. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36104. * @param scene defines the hosting scene
  36105. * @returns a new MultiMaterial
  36106. */
  36107. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36108. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36109. multiMaterial.id = parsedMultiMaterial.id;
  36110. if (BABYLON.Tags) {
  36111. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36112. }
  36113. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36114. var subMatId = parsedMultiMaterial.materials[matIndex];
  36115. if (subMatId) {
  36116. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36117. }
  36118. else {
  36119. multiMaterial.subMaterials.push(null);
  36120. }
  36121. }
  36122. return multiMaterial;
  36123. };
  36124. /**
  36125. * Creates a material from parsed material data
  36126. * @param parsedMaterial defines parsed material data
  36127. * @param scene defines the hosting scene
  36128. * @param rootUrl defines the root URL to use to load textures
  36129. * @returns a new material
  36130. */
  36131. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36132. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36133. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36134. }
  36135. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36136. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36137. if (!BABYLON.LegacyPBRMaterial) {
  36138. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36139. return;
  36140. }
  36141. }
  36142. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36143. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36144. };
  36145. // Triangle views
  36146. Material._TriangleFillMode = 0;
  36147. Material._WireFrameFillMode = 1;
  36148. Material._PointFillMode = 2;
  36149. // Draw modes
  36150. Material._PointListDrawMode = 3;
  36151. Material._LineListDrawMode = 4;
  36152. Material._LineLoopDrawMode = 5;
  36153. Material._LineStripDrawMode = 6;
  36154. Material._TriangleStripDrawMode = 7;
  36155. Material._TriangleFanDrawMode = 8;
  36156. /**
  36157. * Stores the clock-wise side orientation
  36158. */
  36159. Material._ClockWiseSideOrientation = 0;
  36160. /**
  36161. * Stores the counter clock-wise side orientation
  36162. */
  36163. Material._CounterClockWiseSideOrientation = 1;
  36164. /**
  36165. * The dirty texture flag value
  36166. */
  36167. Material._TextureDirtyFlag = 1;
  36168. /**
  36169. * The dirty light flag value
  36170. */
  36171. Material._LightDirtyFlag = 2;
  36172. /**
  36173. * The dirty fresnel flag value
  36174. */
  36175. Material._FresnelDirtyFlag = 4;
  36176. /**
  36177. * The dirty attribute flag value
  36178. */
  36179. Material._AttributesDirtyFlag = 8;
  36180. /**
  36181. * The dirty misc flag value
  36182. */
  36183. Material._MiscDirtyFlag = 16;
  36184. __decorate([
  36185. BABYLON.serialize()
  36186. ], Material.prototype, "id", void 0);
  36187. __decorate([
  36188. BABYLON.serialize()
  36189. ], Material.prototype, "uniqueId", void 0);
  36190. __decorate([
  36191. BABYLON.serialize()
  36192. ], Material.prototype, "name", void 0);
  36193. __decorate([
  36194. BABYLON.serialize()
  36195. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36196. __decorate([
  36197. BABYLON.serialize()
  36198. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36199. __decorate([
  36200. BABYLON.serialize()
  36201. ], Material.prototype, "state", void 0);
  36202. __decorate([
  36203. BABYLON.serialize("alpha")
  36204. ], Material.prototype, "_alpha", void 0);
  36205. __decorate([
  36206. BABYLON.serialize("backFaceCulling")
  36207. ], Material.prototype, "_backFaceCulling", void 0);
  36208. __decorate([
  36209. BABYLON.serialize()
  36210. ], Material.prototype, "sideOrientation", void 0);
  36211. __decorate([
  36212. BABYLON.serialize("alphaMode")
  36213. ], Material.prototype, "_alphaMode", void 0);
  36214. __decorate([
  36215. BABYLON.serialize()
  36216. ], Material.prototype, "_needDepthPrePass", void 0);
  36217. __decorate([
  36218. BABYLON.serialize()
  36219. ], Material.prototype, "disableDepthWrite", void 0);
  36220. __decorate([
  36221. BABYLON.serialize()
  36222. ], Material.prototype, "forceDepthWrite", void 0);
  36223. __decorate([
  36224. BABYLON.serialize()
  36225. ], Material.prototype, "separateCullingPass", void 0);
  36226. __decorate([
  36227. BABYLON.serialize("fogEnabled")
  36228. ], Material.prototype, "_fogEnabled", void 0);
  36229. __decorate([
  36230. BABYLON.serialize()
  36231. ], Material.prototype, "pointSize", void 0);
  36232. __decorate([
  36233. BABYLON.serialize()
  36234. ], Material.prototype, "zOffset", void 0);
  36235. __decorate([
  36236. BABYLON.serialize()
  36237. ], Material.prototype, "wireframe", null);
  36238. __decorate([
  36239. BABYLON.serialize()
  36240. ], Material.prototype, "pointsCloud", null);
  36241. __decorate([
  36242. BABYLON.serialize()
  36243. ], Material.prototype, "fillMode", null);
  36244. return Material;
  36245. }());
  36246. BABYLON.Material = Material;
  36247. })(BABYLON || (BABYLON = {}));
  36248. //# sourceMappingURL=babylon.material.js.map
  36249. var BABYLON;
  36250. (function (BABYLON) {
  36251. var UniformBuffer = /** @class */ (function () {
  36252. /**
  36253. * Uniform buffer objects.
  36254. *
  36255. * Handles blocks of uniform on the GPU.
  36256. *
  36257. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36258. *
  36259. * For more information, please refer to :
  36260. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36261. */
  36262. function UniformBuffer(engine, data, dynamic) {
  36263. this._engine = engine;
  36264. this._noUBO = !engine.supportsUniformBuffers;
  36265. this._dynamic = dynamic;
  36266. this._data = data || [];
  36267. this._uniformLocations = {};
  36268. this._uniformSizes = {};
  36269. this._uniformLocationPointer = 0;
  36270. this._needSync = false;
  36271. if (this._noUBO) {
  36272. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36273. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36274. this.updateFloat = this._updateFloatForEffect;
  36275. this.updateFloat2 = this._updateFloat2ForEffect;
  36276. this.updateFloat3 = this._updateFloat3ForEffect;
  36277. this.updateFloat4 = this._updateFloat4ForEffect;
  36278. this.updateMatrix = this._updateMatrixForEffect;
  36279. this.updateVector3 = this._updateVector3ForEffect;
  36280. this.updateVector4 = this._updateVector4ForEffect;
  36281. this.updateColor3 = this._updateColor3ForEffect;
  36282. this.updateColor4 = this._updateColor4ForEffect;
  36283. }
  36284. else {
  36285. this._engine._uniformBuffers.push(this);
  36286. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36287. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36288. this.updateFloat = this._updateFloatForUniform;
  36289. this.updateFloat2 = this._updateFloat2ForUniform;
  36290. this.updateFloat3 = this._updateFloat3ForUniform;
  36291. this.updateFloat4 = this._updateFloat4ForUniform;
  36292. this.updateMatrix = this._updateMatrixForUniform;
  36293. this.updateVector3 = this._updateVector3ForUniform;
  36294. this.updateVector4 = this._updateVector4ForUniform;
  36295. this.updateColor3 = this._updateColor3ForUniform;
  36296. this.updateColor4 = this._updateColor4ForUniform;
  36297. }
  36298. }
  36299. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36300. // Properties
  36301. /**
  36302. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36303. * or just falling back on setUniformXXX calls.
  36304. */
  36305. get: function () {
  36306. return !this._noUBO;
  36307. },
  36308. enumerable: true,
  36309. configurable: true
  36310. });
  36311. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36312. /**
  36313. * Indicates if the WebGL underlying uniform buffer is in sync
  36314. * with the javascript cache data.
  36315. */
  36316. get: function () {
  36317. return !this._needSync;
  36318. },
  36319. enumerable: true,
  36320. configurable: true
  36321. });
  36322. /**
  36323. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36324. * Also, a dynamic UniformBuffer will disable cache verification and always
  36325. * update the underlying WebGL uniform buffer to the GPU.
  36326. */
  36327. UniformBuffer.prototype.isDynamic = function () {
  36328. return this._dynamic !== undefined;
  36329. };
  36330. /**
  36331. * The data cache on JS side.
  36332. */
  36333. UniformBuffer.prototype.getData = function () {
  36334. return this._bufferData;
  36335. };
  36336. /**
  36337. * The underlying WebGL Uniform buffer.
  36338. */
  36339. UniformBuffer.prototype.getBuffer = function () {
  36340. return this._buffer;
  36341. };
  36342. /**
  36343. * std140 layout specifies how to align data within an UBO structure.
  36344. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36345. * for specs.
  36346. */
  36347. UniformBuffer.prototype._fillAlignment = function (size) {
  36348. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36349. // and 4x4 matrices
  36350. // TODO : change if other types are used
  36351. var alignment;
  36352. if (size <= 2) {
  36353. alignment = size;
  36354. }
  36355. else {
  36356. alignment = 4;
  36357. }
  36358. if ((this._uniformLocationPointer % alignment) !== 0) {
  36359. var oldPointer = this._uniformLocationPointer;
  36360. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36361. var diff = this._uniformLocationPointer - oldPointer;
  36362. for (var i = 0; i < diff; i++) {
  36363. this._data.push(0);
  36364. }
  36365. }
  36366. };
  36367. /**
  36368. * Adds an uniform in the buffer.
  36369. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36370. * for the layout to be correct !
  36371. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36372. * @param {number|number[]} size Data size, or data directly.
  36373. */
  36374. UniformBuffer.prototype.addUniform = function (name, size) {
  36375. if (this._noUBO) {
  36376. return;
  36377. }
  36378. if (this._uniformLocations[name] !== undefined) {
  36379. // Already existing uniform
  36380. return;
  36381. }
  36382. // This function must be called in the order of the shader layout !
  36383. // size can be the size of the uniform, or data directly
  36384. var data;
  36385. if (size instanceof Array) {
  36386. data = size;
  36387. size = data.length;
  36388. }
  36389. else {
  36390. size = size;
  36391. data = [];
  36392. // Fill with zeros
  36393. for (var i = 0; i < size; i++) {
  36394. data.push(0);
  36395. }
  36396. }
  36397. this._fillAlignment(size);
  36398. this._uniformSizes[name] = size;
  36399. this._uniformLocations[name] = this._uniformLocationPointer;
  36400. this._uniformLocationPointer += size;
  36401. for (var i = 0; i < size; i++) {
  36402. this._data.push(data[i]);
  36403. }
  36404. this._needSync = true;
  36405. };
  36406. /**
  36407. * Wrapper for addUniform.
  36408. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36409. * @param {Matrix} mat A 4x4 matrix.
  36410. */
  36411. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36412. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36413. };
  36414. /**
  36415. * Wrapper for addUniform.
  36416. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36417. * @param {number} x
  36418. * @param {number} y
  36419. */
  36420. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36421. var temp = [x, y];
  36422. this.addUniform(name, temp);
  36423. };
  36424. /**
  36425. * Wrapper for addUniform.
  36426. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36427. * @param {number} x
  36428. * @param {number} y
  36429. * @param {number} z
  36430. */
  36431. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36432. var temp = [x, y, z];
  36433. this.addUniform(name, temp);
  36434. };
  36435. /**
  36436. * Wrapper for addUniform.
  36437. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36438. * @param {Color3} color
  36439. */
  36440. UniformBuffer.prototype.addColor3 = function (name, color) {
  36441. var temp = new Array();
  36442. color.toArray(temp);
  36443. this.addUniform(name, temp);
  36444. };
  36445. /**
  36446. * Wrapper for addUniform.
  36447. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36448. * @param {Color3} color
  36449. * @param {number} alpha
  36450. */
  36451. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36452. var temp = new Array();
  36453. color.toArray(temp);
  36454. temp.push(alpha);
  36455. this.addUniform(name, temp);
  36456. };
  36457. /**
  36458. * Wrapper for addUniform.
  36459. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36460. * @param {Vector3} vector
  36461. */
  36462. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36463. var temp = new Array();
  36464. vector.toArray(temp);
  36465. this.addUniform(name, temp);
  36466. };
  36467. /**
  36468. * Wrapper for addUniform.
  36469. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36470. */
  36471. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36472. this.addUniform(name, 12);
  36473. };
  36474. /**
  36475. * Wrapper for addUniform.
  36476. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36477. */
  36478. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36479. this.addUniform(name, 8);
  36480. };
  36481. /**
  36482. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36483. */
  36484. UniformBuffer.prototype.create = function () {
  36485. if (this._noUBO) {
  36486. return;
  36487. }
  36488. if (this._buffer) {
  36489. return; // nothing to do
  36490. }
  36491. // See spec, alignment must be filled as a vec4
  36492. this._fillAlignment(4);
  36493. this._bufferData = new Float32Array(this._data);
  36494. this._rebuild();
  36495. this._needSync = true;
  36496. };
  36497. UniformBuffer.prototype._rebuild = function () {
  36498. if (this._noUBO) {
  36499. return;
  36500. }
  36501. if (this._dynamic) {
  36502. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36503. }
  36504. else {
  36505. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36506. }
  36507. };
  36508. /**
  36509. * Updates the WebGL Uniform Buffer on the GPU.
  36510. * If the `dynamic` flag is set to true, no cache comparison is done.
  36511. * Otherwise, the buffer will be updated only if the cache differs.
  36512. */
  36513. UniformBuffer.prototype.update = function () {
  36514. if (!this._buffer) {
  36515. this.create();
  36516. return;
  36517. }
  36518. if (!this._dynamic && !this._needSync) {
  36519. return;
  36520. }
  36521. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36522. this._needSync = false;
  36523. };
  36524. /**
  36525. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36526. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36527. * @param {number[]|Float32Array} data Flattened data
  36528. * @param {number} size Size of the data.
  36529. */
  36530. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36531. var location = this._uniformLocations[uniformName];
  36532. if (location === undefined) {
  36533. if (this._buffer) {
  36534. // Cannot add an uniform if the buffer is already created
  36535. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36536. return;
  36537. }
  36538. this.addUniform(uniformName, size);
  36539. location = this._uniformLocations[uniformName];
  36540. }
  36541. if (!this._buffer) {
  36542. this.create();
  36543. }
  36544. if (!this._dynamic) {
  36545. // Cache for static uniform buffers
  36546. var changed = false;
  36547. for (var i = 0; i < size; i++) {
  36548. if (this._bufferData[location + i] !== data[i]) {
  36549. changed = true;
  36550. this._bufferData[location + i] = data[i];
  36551. }
  36552. }
  36553. this._needSync = this._needSync || changed;
  36554. }
  36555. else {
  36556. // No cache for dynamic
  36557. for (var i = 0; i < size; i++) {
  36558. this._bufferData[location + i] = data[i];
  36559. }
  36560. }
  36561. };
  36562. // Update methods
  36563. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36564. // To match std140, matrix must be realigned
  36565. for (var i = 0; i < 3; i++) {
  36566. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36567. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36568. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36569. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36570. }
  36571. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36572. };
  36573. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36574. this._currentEffect.setMatrix3x3(name, matrix);
  36575. };
  36576. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36577. this._currentEffect.setMatrix2x2(name, matrix);
  36578. };
  36579. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36580. // To match std140, matrix must be realigned
  36581. for (var i = 0; i < 2; i++) {
  36582. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36583. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36584. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36585. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36586. }
  36587. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36588. };
  36589. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36590. this._currentEffect.setFloat(name, x);
  36591. };
  36592. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36593. UniformBuffer._tempBuffer[0] = x;
  36594. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36595. };
  36596. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36597. if (suffix === void 0) { suffix = ""; }
  36598. this._currentEffect.setFloat2(name + suffix, x, y);
  36599. };
  36600. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36601. if (suffix === void 0) { suffix = ""; }
  36602. UniformBuffer._tempBuffer[0] = x;
  36603. UniformBuffer._tempBuffer[1] = y;
  36604. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36605. };
  36606. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36607. if (suffix === void 0) { suffix = ""; }
  36608. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36609. };
  36610. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36611. if (suffix === void 0) { suffix = ""; }
  36612. UniformBuffer._tempBuffer[0] = x;
  36613. UniformBuffer._tempBuffer[1] = y;
  36614. UniformBuffer._tempBuffer[2] = z;
  36615. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36616. };
  36617. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36618. if (suffix === void 0) { suffix = ""; }
  36619. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36620. };
  36621. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36622. if (suffix === void 0) { suffix = ""; }
  36623. UniformBuffer._tempBuffer[0] = x;
  36624. UniformBuffer._tempBuffer[1] = y;
  36625. UniformBuffer._tempBuffer[2] = z;
  36626. UniformBuffer._tempBuffer[3] = w;
  36627. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36628. };
  36629. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36630. this._currentEffect.setMatrix(name, mat);
  36631. };
  36632. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36633. this.updateUniform(name, mat.toArray(), 16);
  36634. };
  36635. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36636. this._currentEffect.setVector3(name, vector);
  36637. };
  36638. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36639. vector.toArray(UniformBuffer._tempBuffer);
  36640. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36641. };
  36642. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36643. this._currentEffect.setVector4(name, vector);
  36644. };
  36645. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36646. vector.toArray(UniformBuffer._tempBuffer);
  36647. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36648. };
  36649. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36650. if (suffix === void 0) { suffix = ""; }
  36651. this._currentEffect.setColor3(name + suffix, color);
  36652. };
  36653. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36654. if (suffix === void 0) { suffix = ""; }
  36655. color.toArray(UniformBuffer._tempBuffer);
  36656. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36657. };
  36658. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36659. if (suffix === void 0) { suffix = ""; }
  36660. this._currentEffect.setColor4(name + suffix, color, alpha);
  36661. };
  36662. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36663. if (suffix === void 0) { suffix = ""; }
  36664. color.toArray(UniformBuffer._tempBuffer);
  36665. UniformBuffer._tempBuffer[3] = alpha;
  36666. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36667. };
  36668. /**
  36669. * Sets a sampler uniform on the effect.
  36670. * @param {string} name Name of the sampler.
  36671. * @param {Texture} texture
  36672. */
  36673. UniformBuffer.prototype.setTexture = function (name, texture) {
  36674. this._currentEffect.setTexture(name, texture);
  36675. };
  36676. /**
  36677. * Directly updates the value of the uniform in the cache AND on the GPU.
  36678. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36679. * @param {number[]|Float32Array} data Flattened data
  36680. */
  36681. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36682. this.updateUniform(uniformName, data, data.length);
  36683. this.update();
  36684. };
  36685. /**
  36686. * Binds this uniform buffer to an effect.
  36687. * @param {Effect} effect
  36688. * @param {string} name Name of the uniform block in the shader.
  36689. */
  36690. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36691. this._currentEffect = effect;
  36692. if (this._noUBO || !this._buffer) {
  36693. return;
  36694. }
  36695. effect.bindUniformBuffer(this._buffer, name);
  36696. };
  36697. /**
  36698. * Disposes the uniform buffer.
  36699. */
  36700. UniformBuffer.prototype.dispose = function () {
  36701. if (this._noUBO) {
  36702. return;
  36703. }
  36704. var index = this._engine._uniformBuffers.indexOf(this);
  36705. if (index !== -1) {
  36706. this._engine._uniformBuffers.splice(index, 1);
  36707. }
  36708. if (!this._buffer) {
  36709. return;
  36710. }
  36711. if (this._engine._releaseBuffer(this._buffer)) {
  36712. this._buffer = null;
  36713. }
  36714. };
  36715. // Pool for avoiding memory leaks
  36716. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36717. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36718. return UniformBuffer;
  36719. }());
  36720. BABYLON.UniformBuffer = UniformBuffer;
  36721. })(BABYLON || (BABYLON = {}));
  36722. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36723. var BABYLON;
  36724. (function (BABYLON) {
  36725. /**
  36726. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36727. */
  36728. var VertexData = /** @class */ (function () {
  36729. function VertexData() {
  36730. }
  36731. /**
  36732. * Uses the passed data array to set the set the values for the specified kind of data
  36733. * @param data a linear array of floating numbers
  36734. * @param kind the type of data that is being set, eg positions, colors etc
  36735. */
  36736. VertexData.prototype.set = function (data, kind) {
  36737. switch (kind) {
  36738. case BABYLON.VertexBuffer.PositionKind:
  36739. this.positions = data;
  36740. break;
  36741. case BABYLON.VertexBuffer.NormalKind:
  36742. this.normals = data;
  36743. break;
  36744. case BABYLON.VertexBuffer.TangentKind:
  36745. this.tangents = data;
  36746. break;
  36747. case BABYLON.VertexBuffer.UVKind:
  36748. this.uvs = data;
  36749. break;
  36750. case BABYLON.VertexBuffer.UV2Kind:
  36751. this.uvs2 = data;
  36752. break;
  36753. case BABYLON.VertexBuffer.UV3Kind:
  36754. this.uvs3 = data;
  36755. break;
  36756. case BABYLON.VertexBuffer.UV4Kind:
  36757. this.uvs4 = data;
  36758. break;
  36759. case BABYLON.VertexBuffer.UV5Kind:
  36760. this.uvs5 = data;
  36761. break;
  36762. case BABYLON.VertexBuffer.UV6Kind:
  36763. this.uvs6 = data;
  36764. break;
  36765. case BABYLON.VertexBuffer.ColorKind:
  36766. this.colors = data;
  36767. break;
  36768. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36769. this.matricesIndices = data;
  36770. break;
  36771. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36772. this.matricesWeights = data;
  36773. break;
  36774. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36775. this.matricesIndicesExtra = data;
  36776. break;
  36777. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36778. this.matricesWeightsExtra = data;
  36779. break;
  36780. }
  36781. };
  36782. /**
  36783. * Associates the vertexData to the passed Mesh.
  36784. * Sets it as updatable or not (default `false`)
  36785. * @param mesh the mesh the vertexData is applied to
  36786. * @param updatable when used and having the value true allows new data to update the vertexData
  36787. * @returns the VertexData
  36788. */
  36789. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36790. this._applyTo(mesh, updatable);
  36791. return this;
  36792. };
  36793. /**
  36794. * Associates the vertexData to the passed Geometry.
  36795. * Sets it as updatable or not (default `false`)
  36796. * @param geometry the geometry the vertexData is applied to
  36797. * @param updatable when used and having the value true allows new data to update the vertexData
  36798. * @returns VertexData
  36799. */
  36800. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36801. this._applyTo(geometry, updatable);
  36802. return this;
  36803. };
  36804. /**
  36805. * Updates the associated mesh
  36806. * @param mesh the mesh to be updated
  36807. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36808. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36809. * @returns VertexData
  36810. */
  36811. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36812. this._update(mesh);
  36813. return this;
  36814. };
  36815. /**
  36816. * Updates the associated geometry
  36817. * @param geometry the geometry to be updated
  36818. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36819. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36820. * @returns VertexData.
  36821. */
  36822. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36823. this._update(geometry);
  36824. return this;
  36825. };
  36826. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36827. if (updatable === void 0) { updatable = false; }
  36828. if (this.positions) {
  36829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36830. }
  36831. if (this.normals) {
  36832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36833. }
  36834. if (this.tangents) {
  36835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36836. }
  36837. if (this.uvs) {
  36838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36839. }
  36840. if (this.uvs2) {
  36841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36842. }
  36843. if (this.uvs3) {
  36844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36845. }
  36846. if (this.uvs4) {
  36847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36848. }
  36849. if (this.uvs5) {
  36850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36851. }
  36852. if (this.uvs6) {
  36853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36854. }
  36855. if (this.colors) {
  36856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36857. }
  36858. if (this.matricesIndices) {
  36859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36860. }
  36861. if (this.matricesWeights) {
  36862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36863. }
  36864. if (this.matricesIndicesExtra) {
  36865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36866. }
  36867. if (this.matricesWeightsExtra) {
  36868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36869. }
  36870. if (this.indices) {
  36871. meshOrGeometry.setIndices(this.indices, null, updatable);
  36872. }
  36873. else {
  36874. meshOrGeometry.setIndices([], null);
  36875. }
  36876. return this;
  36877. };
  36878. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36879. if (this.positions) {
  36880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36881. }
  36882. if (this.normals) {
  36883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36884. }
  36885. if (this.tangents) {
  36886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36887. }
  36888. if (this.uvs) {
  36889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36890. }
  36891. if (this.uvs2) {
  36892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36893. }
  36894. if (this.uvs3) {
  36895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36896. }
  36897. if (this.uvs4) {
  36898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36899. }
  36900. if (this.uvs5) {
  36901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36902. }
  36903. if (this.uvs6) {
  36904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36905. }
  36906. if (this.colors) {
  36907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36908. }
  36909. if (this.matricesIndices) {
  36910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36911. }
  36912. if (this.matricesWeights) {
  36913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36914. }
  36915. if (this.matricesIndicesExtra) {
  36916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36917. }
  36918. if (this.matricesWeightsExtra) {
  36919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36920. }
  36921. if (this.indices) {
  36922. meshOrGeometry.setIndices(this.indices, null);
  36923. }
  36924. return this;
  36925. };
  36926. /**
  36927. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36928. * @param matrix the transforming matrix
  36929. * @returns the VertexData
  36930. */
  36931. VertexData.prototype.transform = function (matrix) {
  36932. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36933. var transformed = BABYLON.Vector3.Zero();
  36934. var index;
  36935. if (this.positions) {
  36936. var position = BABYLON.Vector3.Zero();
  36937. for (index = 0; index < this.positions.length; index += 3) {
  36938. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36939. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36940. this.positions[index] = transformed.x;
  36941. this.positions[index + 1] = transformed.y;
  36942. this.positions[index + 2] = transformed.z;
  36943. }
  36944. }
  36945. if (this.normals) {
  36946. var normal = BABYLON.Vector3.Zero();
  36947. for (index = 0; index < this.normals.length; index += 3) {
  36948. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36949. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36950. this.normals[index] = transformed.x;
  36951. this.normals[index + 1] = transformed.y;
  36952. this.normals[index + 2] = transformed.z;
  36953. }
  36954. }
  36955. if (this.tangents) {
  36956. var tangent = BABYLON.Vector4.Zero();
  36957. var tangentTransformed = BABYLON.Vector4.Zero();
  36958. for (index = 0; index < this.tangents.length; index += 4) {
  36959. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36960. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36961. this.tangents[index] = tangentTransformed.x;
  36962. this.tangents[index + 1] = tangentTransformed.y;
  36963. this.tangents[index + 2] = tangentTransformed.z;
  36964. this.tangents[index + 3] = tangentTransformed.w;
  36965. }
  36966. }
  36967. if (flip && this.indices) {
  36968. for (index = 0; index < this.indices.length; index += 3) {
  36969. var tmp = this.indices[index + 1];
  36970. this.indices[index + 1] = this.indices[index + 2];
  36971. this.indices[index + 2] = tmp;
  36972. }
  36973. }
  36974. return this;
  36975. };
  36976. /**
  36977. * Merges the passed VertexData into the current one
  36978. * @param other the VertexData to be merged into the current one
  36979. * @returns the modified VertexData
  36980. */
  36981. VertexData.prototype.merge = function (other) {
  36982. this._validate();
  36983. other._validate();
  36984. if (!this.normals !== !other.normals ||
  36985. !this.tangents !== !other.tangents ||
  36986. !this.uvs !== !other.uvs ||
  36987. !this.uvs2 !== !other.uvs2 ||
  36988. !this.uvs3 !== !other.uvs3 ||
  36989. !this.uvs4 !== !other.uvs4 ||
  36990. !this.uvs5 !== !other.uvs5 ||
  36991. !this.uvs6 !== !other.uvs6 ||
  36992. !this.colors !== !other.colors ||
  36993. !this.matricesIndices !== !other.matricesIndices ||
  36994. !this.matricesWeights !== !other.matricesWeights ||
  36995. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36996. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36997. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36998. }
  36999. if (other.indices) {
  37000. if (!this.indices) {
  37001. this.indices = [];
  37002. }
  37003. var offset = this.positions ? this.positions.length / 3 : 0;
  37004. for (var index = 0; index < other.indices.length; index++) {
  37005. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  37006. this.indices.push(other.indices[index] + offset);
  37007. }
  37008. }
  37009. this.positions = this._mergeElement(this.positions, other.positions);
  37010. this.normals = this._mergeElement(this.normals, other.normals);
  37011. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37012. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37013. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37014. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37015. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37016. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37017. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37018. this.colors = this._mergeElement(this.colors, other.colors);
  37019. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37020. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37021. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37022. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37023. return this;
  37024. };
  37025. VertexData.prototype._mergeElement = function (source, other) {
  37026. if (!source) {
  37027. return other;
  37028. }
  37029. if (!other) {
  37030. return source;
  37031. }
  37032. var len = other.length + source.length;
  37033. var isSrcTypedArray = source instanceof Float32Array;
  37034. var isOthTypedArray = other instanceof Float32Array;
  37035. // use non-loop method when the source is Float32Array
  37036. if (isSrcTypedArray) {
  37037. var ret32 = new Float32Array(len);
  37038. ret32.set(source);
  37039. ret32.set(other, source.length);
  37040. return ret32;
  37041. // source is number[], when other is also use concat
  37042. }
  37043. else if (!isOthTypedArray) {
  37044. return source.concat(other);
  37045. // source is a number[], but other is a Float32Array, loop required
  37046. }
  37047. else {
  37048. var ret = source.slice(0); // copy source to a separate array
  37049. for (var i = 0, len = other.length; i < len; i++) {
  37050. ret.push(other[i]);
  37051. }
  37052. return ret;
  37053. }
  37054. };
  37055. VertexData.prototype._validate = function () {
  37056. if (!this.positions) {
  37057. throw new Error("Positions are required");
  37058. }
  37059. var getElementCount = function (kind, values) {
  37060. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37061. if ((values.length % stride) !== 0) {
  37062. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37063. }
  37064. return values.length / stride;
  37065. };
  37066. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37067. var validateElementCount = function (kind, values) {
  37068. var elementCount = getElementCount(kind, values);
  37069. if (elementCount !== positionsElementCount) {
  37070. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37071. }
  37072. };
  37073. if (this.normals)
  37074. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37075. if (this.tangents)
  37076. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37077. if (this.uvs)
  37078. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37079. if (this.uvs2)
  37080. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37081. if (this.uvs3)
  37082. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37083. if (this.uvs4)
  37084. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37085. if (this.uvs5)
  37086. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37087. if (this.uvs6)
  37088. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37089. if (this.colors)
  37090. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37091. if (this.matricesIndices)
  37092. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37093. if (this.matricesWeights)
  37094. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37095. if (this.matricesIndicesExtra)
  37096. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37097. if (this.matricesWeightsExtra)
  37098. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37099. };
  37100. /**
  37101. * Serializes the VertexData
  37102. * @returns a serialized object
  37103. */
  37104. VertexData.prototype.serialize = function () {
  37105. var serializationObject = this.serialize();
  37106. if (this.positions) {
  37107. serializationObject.positions = this.positions;
  37108. }
  37109. if (this.normals) {
  37110. serializationObject.normals = this.normals;
  37111. }
  37112. if (this.tangents) {
  37113. serializationObject.tangents = this.tangents;
  37114. }
  37115. if (this.uvs) {
  37116. serializationObject.uvs = this.uvs;
  37117. }
  37118. if (this.uvs2) {
  37119. serializationObject.uvs2 = this.uvs2;
  37120. }
  37121. if (this.uvs3) {
  37122. serializationObject.uvs3 = this.uvs3;
  37123. }
  37124. if (this.uvs4) {
  37125. serializationObject.uvs4 = this.uvs4;
  37126. }
  37127. if (this.uvs5) {
  37128. serializationObject.uvs5 = this.uvs5;
  37129. }
  37130. if (this.uvs6) {
  37131. serializationObject.uvs6 = this.uvs6;
  37132. }
  37133. if (this.colors) {
  37134. serializationObject.colors = this.colors;
  37135. }
  37136. if (this.matricesIndices) {
  37137. serializationObject.matricesIndices = this.matricesIndices;
  37138. serializationObject.matricesIndices._isExpanded = true;
  37139. }
  37140. if (this.matricesWeights) {
  37141. serializationObject.matricesWeights = this.matricesWeights;
  37142. }
  37143. if (this.matricesIndicesExtra) {
  37144. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37145. serializationObject.matricesIndicesExtra._isExpanded = true;
  37146. }
  37147. if (this.matricesWeightsExtra) {
  37148. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37149. }
  37150. serializationObject.indices = this.indices;
  37151. return serializationObject;
  37152. };
  37153. // Statics
  37154. /**
  37155. * Extracts the vertexData from a mesh
  37156. * @param mesh the mesh from which to extract the VertexData
  37157. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37158. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37159. * @returns the object VertexData associated to the passed mesh
  37160. */
  37161. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37162. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37163. };
  37164. /**
  37165. * Extracts the vertexData from the geometry
  37166. * @param geometry the geometry from which to extract the VertexData
  37167. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37168. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37169. * @returns the object VertexData associated to the passed mesh
  37170. */
  37171. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37172. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37173. };
  37174. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37175. var result = new VertexData();
  37176. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37177. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37178. }
  37179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37180. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37181. }
  37182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37183. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37184. }
  37185. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37186. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37187. }
  37188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37189. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37190. }
  37191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37192. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37193. }
  37194. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37195. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37196. }
  37197. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37198. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37199. }
  37200. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37201. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37202. }
  37203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37204. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37205. }
  37206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37207. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37208. }
  37209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37210. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37211. }
  37212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37213. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37214. }
  37215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37216. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37217. }
  37218. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37219. return result;
  37220. };
  37221. /**
  37222. * Creates the VertexData for a Ribbon
  37223. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37224. * * pathArray array of paths, each of which an array of successive Vector3
  37225. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37226. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37227. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  37228. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37229. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37230. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37231. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37232. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37233. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37234. * @returns the VertexData of the ribbon
  37235. */
  37236. VertexData.CreateRibbon = function (options) {
  37237. var pathArray = options.pathArray;
  37238. var closeArray = options.closeArray || false;
  37239. var closePath = options.closePath || false;
  37240. var invertUV = options.invertUV || false;
  37241. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37242. var offset = options.offset || defaultOffset;
  37243. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37244. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37245. var customUV = options.uvs;
  37246. var customColors = options.colors;
  37247. var positions = [];
  37248. var indices = [];
  37249. var normals = [];
  37250. var uvs = [];
  37251. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37252. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37253. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37254. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37255. var minlg; // minimal length among all paths from pathArray
  37256. var lg = []; // array of path lengths : nb of vertex per path
  37257. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37258. var p; // path iterator
  37259. var i; // point iterator
  37260. var j; // point iterator
  37261. // if single path in pathArray
  37262. if (pathArray.length < 2) {
  37263. var ar1 = [];
  37264. var ar2 = [];
  37265. for (i = 0; i < pathArray[0].length - offset; i++) {
  37266. ar1.push(pathArray[0][i]);
  37267. ar2.push(pathArray[0][i + offset]);
  37268. }
  37269. pathArray = [ar1, ar2];
  37270. }
  37271. // positions and horizontal distances (u)
  37272. var idc = 0;
  37273. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37274. var path;
  37275. var l;
  37276. minlg = pathArray[0].length;
  37277. var vectlg;
  37278. var dist;
  37279. for (p = 0; p < pathArray.length; p++) {
  37280. uTotalDistance[p] = 0;
  37281. us[p] = [0];
  37282. path = pathArray[p];
  37283. l = path.length;
  37284. minlg = (minlg < l) ? minlg : l;
  37285. j = 0;
  37286. while (j < l) {
  37287. positions.push(path[j].x, path[j].y, path[j].z);
  37288. if (j > 0) {
  37289. vectlg = path[j].subtract(path[j - 1]).length();
  37290. dist = vectlg + uTotalDistance[p];
  37291. us[p].push(dist);
  37292. uTotalDistance[p] = dist;
  37293. }
  37294. j++;
  37295. }
  37296. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37297. j--;
  37298. positions.push(path[0].x, path[0].y, path[0].z);
  37299. vectlg = path[j].subtract(path[0]).length();
  37300. dist = vectlg + uTotalDistance[p];
  37301. us[p].push(dist);
  37302. uTotalDistance[p] = dist;
  37303. }
  37304. lg[p] = l + closePathCorr;
  37305. idx[p] = idc;
  37306. idc += (l + closePathCorr);
  37307. }
  37308. // vertical distances (v)
  37309. var path1;
  37310. var path2;
  37311. var vertex1 = null;
  37312. var vertex2 = null;
  37313. for (i = 0; i < minlg + closePathCorr; i++) {
  37314. vTotalDistance[i] = 0;
  37315. vs[i] = [0];
  37316. for (p = 0; p < pathArray.length - 1; p++) {
  37317. path1 = pathArray[p];
  37318. path2 = pathArray[p + 1];
  37319. if (i === minlg) { // closePath
  37320. vertex1 = path1[0];
  37321. vertex2 = path2[0];
  37322. }
  37323. else {
  37324. vertex1 = path1[i];
  37325. vertex2 = path2[i];
  37326. }
  37327. vectlg = vertex2.subtract(vertex1).length();
  37328. dist = vectlg + vTotalDistance[i];
  37329. vs[i].push(dist);
  37330. vTotalDistance[i] = dist;
  37331. }
  37332. if (closeArray && vertex2 && vertex1) {
  37333. path1 = pathArray[p];
  37334. path2 = pathArray[0];
  37335. if (i === minlg) { // closePath
  37336. vertex2 = path2[0];
  37337. }
  37338. vectlg = vertex2.subtract(vertex1).length();
  37339. dist = vectlg + vTotalDistance[i];
  37340. vTotalDistance[i] = dist;
  37341. }
  37342. }
  37343. // uvs
  37344. var u;
  37345. var v;
  37346. if (customUV) {
  37347. for (p = 0; p < customUV.length; p++) {
  37348. uvs.push(customUV[p].x, customUV[p].y);
  37349. }
  37350. }
  37351. else {
  37352. for (p = 0; p < pathArray.length; p++) {
  37353. for (i = 0; i < minlg + closePathCorr; i++) {
  37354. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37355. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37356. if (invertUV) {
  37357. uvs.push(v, u);
  37358. }
  37359. else {
  37360. uvs.push(u, v);
  37361. }
  37362. }
  37363. }
  37364. }
  37365. // indices
  37366. p = 0; // path index
  37367. var pi = 0; // positions array index
  37368. var l1 = lg[p] - 1; // path1 length
  37369. var l2 = lg[p + 1] - 1; // path2 length
  37370. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37371. var shft = idx[1] - idx[0]; // shift
  37372. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37373. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37374. // 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
  37375. indices.push(pi, pi + shft, pi + 1);
  37376. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37377. pi += 1;
  37378. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37379. p++;
  37380. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37381. shft = idx[0] - idx[p];
  37382. l1 = lg[p] - 1;
  37383. l2 = lg[0] - 1;
  37384. }
  37385. else {
  37386. shft = idx[p + 1] - idx[p];
  37387. l1 = lg[p] - 1;
  37388. l2 = lg[p + 1] - 1;
  37389. }
  37390. pi = idx[p];
  37391. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37392. }
  37393. }
  37394. // normals
  37395. VertexData.ComputeNormals(positions, indices, normals);
  37396. if (closePath) { // update both the first and last vertex normals to their average value
  37397. var indexFirst = 0;
  37398. var indexLast = 0;
  37399. for (p = 0; p < pathArray.length; p++) {
  37400. indexFirst = idx[p] * 3;
  37401. if (p + 1 < pathArray.length) {
  37402. indexLast = (idx[p + 1] - 1) * 3;
  37403. }
  37404. else {
  37405. indexLast = normals.length - 3;
  37406. }
  37407. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37408. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37409. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37410. normals[indexLast] = normals[indexFirst];
  37411. normals[indexLast + 1] = normals[indexFirst + 1];
  37412. normals[indexLast + 2] = normals[indexFirst + 2];
  37413. }
  37414. }
  37415. // sides
  37416. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37417. // Colors
  37418. var colors = null;
  37419. if (customColors) {
  37420. colors = new Float32Array(customColors.length * 4);
  37421. for (var c = 0; c < customColors.length; c++) {
  37422. colors[c * 4] = customColors[c].r;
  37423. colors[c * 4 + 1] = customColors[c].g;
  37424. colors[c * 4 + 2] = customColors[c].b;
  37425. colors[c * 4 + 3] = customColors[c].a;
  37426. }
  37427. }
  37428. // Result
  37429. var vertexData = new VertexData();
  37430. var positions32 = new Float32Array(positions);
  37431. var normals32 = new Float32Array(normals);
  37432. var uvs32 = new Float32Array(uvs);
  37433. vertexData.indices = indices;
  37434. vertexData.positions = positions32;
  37435. vertexData.normals = normals32;
  37436. vertexData.uvs = uvs32;
  37437. if (colors) {
  37438. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37439. }
  37440. if (closePath) {
  37441. vertexData._idx = idx;
  37442. }
  37443. return vertexData;
  37444. };
  37445. /**
  37446. * Creates the VertexData for a box
  37447. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37448. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37449. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37450. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37451. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37452. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37453. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37454. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37455. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37456. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37457. * @returns the VertexData of the box
  37458. */
  37459. VertexData.CreateBox = function (options) {
  37460. var normalsSource = [
  37461. new BABYLON.Vector3(0, 0, 1),
  37462. new BABYLON.Vector3(0, 0, -1),
  37463. new BABYLON.Vector3(1, 0, 0),
  37464. new BABYLON.Vector3(-1, 0, 0),
  37465. new BABYLON.Vector3(0, 1, 0),
  37466. new BABYLON.Vector3(0, -1, 0)
  37467. ];
  37468. var indices = [];
  37469. var positions = [];
  37470. var normals = [];
  37471. var uvs = [];
  37472. var width = options.width || options.size || 1;
  37473. var height = options.height || options.size || 1;
  37474. var depth = options.depth || options.size || 1;
  37475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37476. var faceUV = options.faceUV || new Array(6);
  37477. var faceColors = options.faceColors;
  37478. var colors = [];
  37479. // default face colors and UV if undefined
  37480. for (var f = 0; f < 6; f++) {
  37481. if (faceUV[f] === undefined) {
  37482. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37483. }
  37484. if (faceColors && faceColors[f] === undefined) {
  37485. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37486. }
  37487. }
  37488. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37489. // Create each face in turn.
  37490. for (var index = 0; index < normalsSource.length; index++) {
  37491. var normal = normalsSource[index];
  37492. // Get two vectors perpendicular to the face normal and to each other.
  37493. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37494. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37495. // Six indices (two triangles) per face.
  37496. var verticesLength = positions.length / 3;
  37497. indices.push(verticesLength);
  37498. indices.push(verticesLength + 1);
  37499. indices.push(verticesLength + 2);
  37500. indices.push(verticesLength);
  37501. indices.push(verticesLength + 2);
  37502. indices.push(verticesLength + 3);
  37503. // Four vertices per face.
  37504. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37505. positions.push(vertex.x, vertex.y, vertex.z);
  37506. normals.push(normal.x, normal.y, normal.z);
  37507. uvs.push(faceUV[index].z, faceUV[index].w);
  37508. if (faceColors) {
  37509. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37510. }
  37511. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37512. positions.push(vertex.x, vertex.y, vertex.z);
  37513. normals.push(normal.x, normal.y, normal.z);
  37514. uvs.push(faceUV[index].x, faceUV[index].w);
  37515. if (faceColors) {
  37516. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37517. }
  37518. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37519. positions.push(vertex.x, vertex.y, vertex.z);
  37520. normals.push(normal.x, normal.y, normal.z);
  37521. uvs.push(faceUV[index].x, faceUV[index].y);
  37522. if (faceColors) {
  37523. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37524. }
  37525. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37526. positions.push(vertex.x, vertex.y, vertex.z);
  37527. normals.push(normal.x, normal.y, normal.z);
  37528. uvs.push(faceUV[index].z, faceUV[index].y);
  37529. if (faceColors) {
  37530. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37531. }
  37532. }
  37533. // sides
  37534. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37535. // Result
  37536. var vertexData = new VertexData();
  37537. vertexData.indices = indices;
  37538. vertexData.positions = positions;
  37539. vertexData.normals = normals;
  37540. vertexData.uvs = uvs;
  37541. if (faceColors) {
  37542. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37543. vertexData.colors = totalColors;
  37544. }
  37545. return vertexData;
  37546. };
  37547. /**
  37548. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37549. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37550. * * segments sets the number of horizontal strips optional, default 32
  37551. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37552. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37553. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37554. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37555. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37556. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37557. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37558. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37559. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37560. * @returns the VertexData of the ellipsoid
  37561. */
  37562. VertexData.CreateSphere = function (options) {
  37563. var segments = options.segments || 32;
  37564. var diameterX = options.diameterX || options.diameter || 1;
  37565. var diameterY = options.diameterY || options.diameter || 1;
  37566. var diameterZ = options.diameterZ || options.diameter || 1;
  37567. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37568. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37569. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37570. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37571. var totalZRotationSteps = 2 + segments;
  37572. var totalYRotationSteps = 2 * totalZRotationSteps;
  37573. var indices = [];
  37574. var positions = [];
  37575. var normals = [];
  37576. var uvs = [];
  37577. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37578. var normalizedZ = zRotationStep / totalZRotationSteps;
  37579. var angleZ = normalizedZ * Math.PI * slice;
  37580. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37581. var normalizedY = yRotationStep / totalYRotationSteps;
  37582. var angleY = normalizedY * Math.PI * 2 * arc;
  37583. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37584. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37585. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37586. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37587. var vertex = complete.multiply(radius);
  37588. var normal = complete.divide(radius).normalize();
  37589. positions.push(vertex.x, vertex.y, vertex.z);
  37590. normals.push(normal.x, normal.y, normal.z);
  37591. uvs.push(normalizedY, normalizedZ);
  37592. }
  37593. if (zRotationStep > 0) {
  37594. var verticesCount = positions.length / 3;
  37595. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37596. indices.push((firstIndex));
  37597. indices.push((firstIndex + 1));
  37598. indices.push(firstIndex + totalYRotationSteps + 1);
  37599. indices.push((firstIndex + totalYRotationSteps + 1));
  37600. indices.push((firstIndex + 1));
  37601. indices.push((firstIndex + totalYRotationSteps + 2));
  37602. }
  37603. }
  37604. }
  37605. // Sides
  37606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37607. // Result
  37608. var vertexData = new VertexData();
  37609. vertexData.indices = indices;
  37610. vertexData.positions = positions;
  37611. vertexData.normals = normals;
  37612. vertexData.uvs = uvs;
  37613. return vertexData;
  37614. };
  37615. /**
  37616. * Creates the VertexData for a cylinder, cone or prism
  37617. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37618. * * height sets the height (y direction) of the cylinder, optional, default 2
  37619. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37620. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37621. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37622. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37623. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37624. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37625. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37626. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37627. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37628. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37629. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37630. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37631. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37632. * @returns the VertexData of the cylinder, cone or prism
  37633. */
  37634. VertexData.CreateCylinder = function (options) {
  37635. var height = options.height || 2;
  37636. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37637. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37638. var tessellation = options.tessellation || 24;
  37639. var subdivisions = options.subdivisions || 1;
  37640. var hasRings = options.hasRings ? true : false;
  37641. var enclose = options.enclose ? true : false;
  37642. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37644. var faceUV = options.faceUV || new Array(3);
  37645. var faceColors = options.faceColors;
  37646. // default face colors and UV if undefined
  37647. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37648. var ringNb = (hasRings) ? subdivisions : 1;
  37649. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37650. var f;
  37651. for (f = 0; f < surfaceNb; f++) {
  37652. if (faceColors && faceColors[f] === undefined) {
  37653. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37654. }
  37655. }
  37656. for (f = 0; f < surfaceNb; f++) {
  37657. if (faceUV && faceUV[f] === undefined) {
  37658. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37659. }
  37660. }
  37661. var indices = new Array();
  37662. var positions = new Array();
  37663. var normals = new Array();
  37664. var uvs = new Array();
  37665. var colors = new Array();
  37666. var angle_step = Math.PI * 2 * arc / tessellation;
  37667. var angle;
  37668. var h;
  37669. var radius;
  37670. var tan = (diameterBottom - diameterTop) / 2 / height;
  37671. var ringVertex = BABYLON.Vector3.Zero();
  37672. var ringNormal = BABYLON.Vector3.Zero();
  37673. var ringFirstVertex = BABYLON.Vector3.Zero();
  37674. var ringFirstNormal = BABYLON.Vector3.Zero();
  37675. var quadNormal = BABYLON.Vector3.Zero();
  37676. var Y = BABYLON.Axis.Y;
  37677. // positions, normals, uvs
  37678. var i;
  37679. var j;
  37680. var r;
  37681. var ringIdx = 1;
  37682. var s = 1; // surface index
  37683. var cs = 0;
  37684. var v = 0;
  37685. for (i = 0; i <= subdivisions; i++) {
  37686. h = i / subdivisions;
  37687. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37688. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37689. for (r = 0; r < ringIdx; r++) {
  37690. if (hasRings) {
  37691. s += r;
  37692. }
  37693. if (enclose) {
  37694. s += 2 * r;
  37695. }
  37696. for (j = 0; j <= tessellation; j++) {
  37697. angle = j * angle_step;
  37698. // position
  37699. ringVertex.x = Math.cos(-angle) * radius;
  37700. ringVertex.y = -height / 2 + h * height;
  37701. ringVertex.z = Math.sin(-angle) * radius;
  37702. // normal
  37703. if (diameterTop === 0 && i === subdivisions) {
  37704. // if no top cap, reuse former normals
  37705. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37706. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37707. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37708. }
  37709. else {
  37710. ringNormal.x = ringVertex.x;
  37711. ringNormal.z = ringVertex.z;
  37712. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37713. ringNormal.normalize();
  37714. }
  37715. // keep first ring vertex values for enclose
  37716. if (j === 0) {
  37717. ringFirstVertex.copyFrom(ringVertex);
  37718. ringFirstNormal.copyFrom(ringNormal);
  37719. }
  37720. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37721. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37722. if (hasRings) {
  37723. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37724. }
  37725. else {
  37726. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37727. }
  37728. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37729. if (faceColors) {
  37730. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37731. }
  37732. }
  37733. // if enclose, add four vertices and their dedicated normals
  37734. if (arc !== 1 && enclose) {
  37735. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37736. positions.push(0, ringVertex.y, 0);
  37737. positions.push(0, ringVertex.y, 0);
  37738. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37739. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37740. quadNormal.normalize();
  37741. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37742. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37743. quadNormal.normalize();
  37744. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37745. if (hasRings) {
  37746. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37747. }
  37748. else {
  37749. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37750. }
  37751. uvs.push(faceUV[s + 1].x, v);
  37752. uvs.push(faceUV[s + 1].z, v);
  37753. if (hasRings) {
  37754. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37755. }
  37756. else {
  37757. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37758. }
  37759. uvs.push(faceUV[s + 2].x, v);
  37760. uvs.push(faceUV[s + 2].z, v);
  37761. if (faceColors) {
  37762. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37763. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37764. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37765. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37766. }
  37767. }
  37768. if (cs !== s) {
  37769. cs = s;
  37770. }
  37771. }
  37772. }
  37773. // indices
  37774. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37775. var s;
  37776. i = 0;
  37777. for (s = 0; s < subdivisions; s++) {
  37778. var i0 = 0;
  37779. var i1 = 0;
  37780. var i2 = 0;
  37781. var i3 = 0;
  37782. for (j = 0; j < tessellation; j++) {
  37783. i0 = i * (e + 1) + j;
  37784. i1 = (i + 1) * (e + 1) + j;
  37785. i2 = i * (e + 1) + (j + 1);
  37786. i3 = (i + 1) * (e + 1) + (j + 1);
  37787. indices.push(i0, i1, i2);
  37788. indices.push(i3, i2, i1);
  37789. }
  37790. if (arc !== 1 && enclose) { // if enclose, add two quads
  37791. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37792. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37793. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37794. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37795. }
  37796. i = (hasRings) ? (i + 2) : (i + 1);
  37797. }
  37798. // Caps
  37799. var createCylinderCap = function (isTop) {
  37800. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37801. if (radius === 0) {
  37802. return;
  37803. }
  37804. // Cap positions, normals & uvs
  37805. var angle;
  37806. var circleVector;
  37807. var i;
  37808. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37809. var c = null;
  37810. if (faceColors) {
  37811. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37812. }
  37813. // cap center
  37814. var vbase = positions.length / 3;
  37815. var offset = isTop ? height / 2 : -height / 2;
  37816. var center = new BABYLON.Vector3(0, offset, 0);
  37817. positions.push(center.x, center.y, center.z);
  37818. normals.push(0, isTop ? 1 : -1, 0);
  37819. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37820. if (c) {
  37821. colors.push(c.r, c.g, c.b, c.a);
  37822. }
  37823. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37824. for (i = 0; i <= tessellation; i++) {
  37825. angle = Math.PI * 2 * i * arc / tessellation;
  37826. var cos = Math.cos(-angle);
  37827. var sin = Math.sin(-angle);
  37828. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37829. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37830. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37831. normals.push(0, isTop ? 1 : -1, 0);
  37832. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37833. if (c) {
  37834. colors.push(c.r, c.g, c.b, c.a);
  37835. }
  37836. }
  37837. // Cap indices
  37838. for (i = 0; i < tessellation; i++) {
  37839. if (!isTop) {
  37840. indices.push(vbase);
  37841. indices.push(vbase + (i + 1));
  37842. indices.push(vbase + (i + 2));
  37843. }
  37844. else {
  37845. indices.push(vbase);
  37846. indices.push(vbase + (i + 2));
  37847. indices.push(vbase + (i + 1));
  37848. }
  37849. }
  37850. };
  37851. // add caps to geometry
  37852. createCylinderCap(false);
  37853. createCylinderCap(true);
  37854. // Sides
  37855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37856. var vertexData = new VertexData();
  37857. vertexData.indices = indices;
  37858. vertexData.positions = positions;
  37859. vertexData.normals = normals;
  37860. vertexData.uvs = uvs;
  37861. if (faceColors) {
  37862. vertexData.colors = colors;
  37863. }
  37864. return vertexData;
  37865. };
  37866. /**
  37867. * Creates the VertexData for a torus
  37868. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37869. * * diameter the diameter of the torus, optional default 1
  37870. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37871. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37872. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37873. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37874. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37875. * @returns the VertexData of the torus
  37876. */
  37877. VertexData.CreateTorus = function (options) {
  37878. var indices = [];
  37879. var positions = [];
  37880. var normals = [];
  37881. var uvs = [];
  37882. var diameter = options.diameter || 1;
  37883. var thickness = options.thickness || 0.5;
  37884. var tessellation = options.tessellation || 16;
  37885. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37886. var stride = tessellation + 1;
  37887. for (var i = 0; i <= tessellation; i++) {
  37888. var u = i / tessellation;
  37889. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37890. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37891. for (var j = 0; j <= tessellation; j++) {
  37892. var v = 1 - j / tessellation;
  37893. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37894. var dx = Math.cos(innerAngle);
  37895. var dy = Math.sin(innerAngle);
  37896. // Create a vertex.
  37897. var normal = new BABYLON.Vector3(dx, dy, 0);
  37898. var position = normal.scale(thickness / 2);
  37899. var textureCoordinate = new BABYLON.Vector2(u, v);
  37900. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37901. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37902. positions.push(position.x, position.y, position.z);
  37903. normals.push(normal.x, normal.y, normal.z);
  37904. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37905. // And create indices for two triangles.
  37906. var nextI = (i + 1) % stride;
  37907. var nextJ = (j + 1) % stride;
  37908. indices.push(i * stride + j);
  37909. indices.push(i * stride + nextJ);
  37910. indices.push(nextI * stride + j);
  37911. indices.push(i * stride + nextJ);
  37912. indices.push(nextI * stride + nextJ);
  37913. indices.push(nextI * stride + j);
  37914. }
  37915. }
  37916. // Sides
  37917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37918. // Result
  37919. var vertexData = new VertexData();
  37920. vertexData.indices = indices;
  37921. vertexData.positions = positions;
  37922. vertexData.normals = normals;
  37923. vertexData.uvs = uvs;
  37924. return vertexData;
  37925. };
  37926. /**
  37927. * Creates the VertexData of the LineSystem
  37928. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37929. * - lines an array of lines, each line being an array of successive Vector3
  37930. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37931. * @returns the VertexData of the LineSystem
  37932. */
  37933. VertexData.CreateLineSystem = function (options) {
  37934. var indices = [];
  37935. var positions = [];
  37936. var lines = options.lines;
  37937. var colors = options.colors;
  37938. var vertexColors = [];
  37939. var idx = 0;
  37940. for (var l = 0; l < lines.length; l++) {
  37941. var points = lines[l];
  37942. for (var index = 0; index < points.length; index++) {
  37943. positions.push(points[index].x, points[index].y, points[index].z);
  37944. if (colors) {
  37945. var color = colors[l];
  37946. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37947. }
  37948. if (index > 0) {
  37949. indices.push(idx - 1);
  37950. indices.push(idx);
  37951. }
  37952. idx++;
  37953. }
  37954. }
  37955. var vertexData = new VertexData();
  37956. vertexData.indices = indices;
  37957. vertexData.positions = positions;
  37958. if (colors) {
  37959. vertexData.colors = vertexColors;
  37960. }
  37961. return vertexData;
  37962. };
  37963. /**
  37964. * Create the VertexData for a DashedLines
  37965. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37966. * - points an array successive Vector3
  37967. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37968. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37969. * - dashNb the intended total number of dashes, optional, default 200
  37970. * @returns the VertexData for the DashedLines
  37971. */
  37972. VertexData.CreateDashedLines = function (options) {
  37973. var dashSize = options.dashSize || 3;
  37974. var gapSize = options.gapSize || 1;
  37975. var dashNb = options.dashNb || 200;
  37976. var points = options.points;
  37977. var positions = new Array();
  37978. var indices = new Array();
  37979. var curvect = BABYLON.Vector3.Zero();
  37980. var lg = 0;
  37981. var nb = 0;
  37982. var shft = 0;
  37983. var dashshft = 0;
  37984. var curshft = 0;
  37985. var idx = 0;
  37986. var i = 0;
  37987. for (i = 0; i < points.length - 1; i++) {
  37988. points[i + 1].subtractToRef(points[i], curvect);
  37989. lg += curvect.length();
  37990. }
  37991. shft = lg / dashNb;
  37992. dashshft = dashSize * shft / (dashSize + gapSize);
  37993. for (i = 0; i < points.length - 1; i++) {
  37994. points[i + 1].subtractToRef(points[i], curvect);
  37995. nb = Math.floor(curvect.length() / shft);
  37996. curvect.normalize();
  37997. for (var j = 0; j < nb; j++) {
  37998. curshft = shft * j;
  37999. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38000. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38001. indices.push(idx, idx + 1);
  38002. idx += 2;
  38003. }
  38004. }
  38005. // Result
  38006. var vertexData = new VertexData();
  38007. vertexData.positions = positions;
  38008. vertexData.indices = indices;
  38009. return vertexData;
  38010. };
  38011. /**
  38012. * Creates the VertexData for a Ground
  38013. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38014. * - width the width (x direction) of the ground, optional, default 1
  38015. * - height the height (z direction) of the ground, optional, default 1
  38016. * - subdivisions the number of subdivisions per side, optional, default 1
  38017. * @returns the VertexData of the Ground
  38018. */
  38019. VertexData.CreateGround = function (options) {
  38020. var indices = [];
  38021. var positions = [];
  38022. var normals = [];
  38023. var uvs = [];
  38024. var row, col;
  38025. var width = options.width || 1;
  38026. var height = options.height || 1;
  38027. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38028. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38029. for (row = 0; row <= subdivisionsY; row++) {
  38030. for (col = 0; col <= subdivisionsX; col++) {
  38031. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38032. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38033. positions.push(position.x, position.y, position.z);
  38034. normals.push(normal.x, normal.y, normal.z);
  38035. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38036. }
  38037. }
  38038. for (row = 0; row < subdivisionsY; row++) {
  38039. for (col = 0; col < subdivisionsX; col++) {
  38040. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38041. indices.push(col + 1 + row * (subdivisionsX + 1));
  38042. indices.push(col + row * (subdivisionsX + 1));
  38043. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38044. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38045. indices.push(col + row * (subdivisionsX + 1));
  38046. }
  38047. }
  38048. // Result
  38049. var vertexData = new VertexData();
  38050. vertexData.indices = indices;
  38051. vertexData.positions = positions;
  38052. vertexData.normals = normals;
  38053. vertexData.uvs = uvs;
  38054. return vertexData;
  38055. };
  38056. /**
  38057. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38058. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38059. * * xmin the ground minimum X coordinate, optional, default -1
  38060. * * zmin the ground minimum Z coordinate, optional, default -1
  38061. * * xmax the ground maximum X coordinate, optional, default 1
  38062. * * zmax the ground maximum Z coordinate, optional, default 1
  38063. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  38064. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  38065. * @returns the VertexData of the TiledGround
  38066. */
  38067. VertexData.CreateTiledGround = function (options) {
  38068. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38069. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38070. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38071. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38072. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38073. var precision = options.precision || { w: 1, h: 1 };
  38074. var indices = new Array();
  38075. var positions = new Array();
  38076. var normals = new Array();
  38077. var uvs = new Array();
  38078. var row, col, tileRow, tileCol;
  38079. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38080. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38081. precision.w = (precision.w < 1) ? 1 : precision.w;
  38082. precision.h = (precision.h < 1) ? 1 : precision.h;
  38083. var tileSize = {
  38084. 'w': (xmax - xmin) / subdivisions.w,
  38085. 'h': (zmax - zmin) / subdivisions.h
  38086. };
  38087. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38088. // Indices
  38089. var base = positions.length / 3;
  38090. var rowLength = precision.w + 1;
  38091. for (row = 0; row < precision.h; row++) {
  38092. for (col = 0; col < precision.w; col++) {
  38093. var square = [
  38094. base + col + row * rowLength,
  38095. base + (col + 1) + row * rowLength,
  38096. base + (col + 1) + (row + 1) * rowLength,
  38097. base + col + (row + 1) * rowLength
  38098. ];
  38099. indices.push(square[1]);
  38100. indices.push(square[2]);
  38101. indices.push(square[3]);
  38102. indices.push(square[0]);
  38103. indices.push(square[1]);
  38104. indices.push(square[3]);
  38105. }
  38106. }
  38107. // Position, normals and uvs
  38108. var position = BABYLON.Vector3.Zero();
  38109. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38110. for (row = 0; row <= precision.h; row++) {
  38111. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38112. for (col = 0; col <= precision.w; col++) {
  38113. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38114. position.y = 0;
  38115. positions.push(position.x, position.y, position.z);
  38116. normals.push(normal.x, normal.y, normal.z);
  38117. uvs.push(col / precision.w, row / precision.h);
  38118. }
  38119. }
  38120. }
  38121. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38122. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38123. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38124. }
  38125. }
  38126. // Result
  38127. var vertexData = new VertexData();
  38128. vertexData.indices = indices;
  38129. vertexData.positions = positions;
  38130. vertexData.normals = normals;
  38131. vertexData.uvs = uvs;
  38132. return vertexData;
  38133. };
  38134. /**
  38135. * Creates the VertexData of the Ground designed from a heightmap
  38136. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38137. * * width the width (x direction) of the ground
  38138. * * height the height (z direction) of the ground
  38139. * * subdivisions the number of subdivisions per side
  38140. * * minHeight the minimum altitude on the ground, optional, default 0
  38141. * * maxHeight the maximum altitude on the ground, optional default 1
  38142. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38143. * * buffer the array holding the image color data
  38144. * * bufferWidth the width of image
  38145. * * bufferHeight the height of image
  38146. * @returns the VertexData of the Ground designed from a heightmap
  38147. */
  38148. VertexData.CreateGroundFromHeightMap = function (options) {
  38149. var indices = [];
  38150. var positions = [];
  38151. var normals = [];
  38152. var uvs = [];
  38153. var row, col;
  38154. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38155. // Vertices
  38156. for (row = 0; row <= options.subdivisions; row++) {
  38157. for (col = 0; col <= options.subdivisions; col++) {
  38158. 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));
  38159. // Compute height
  38160. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38161. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38162. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38163. var r = options.buffer[pos] / 255.0;
  38164. var g = options.buffer[pos + 1] / 255.0;
  38165. var b = options.buffer[pos + 2] / 255.0;
  38166. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38167. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38168. // Add vertex
  38169. positions.push(position.x, position.y, position.z);
  38170. normals.push(0, 0, 0);
  38171. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38172. }
  38173. }
  38174. // Indices
  38175. for (row = 0; row < options.subdivisions; row++) {
  38176. for (col = 0; col < options.subdivisions; col++) {
  38177. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38178. indices.push(col + 1 + row * (options.subdivisions + 1));
  38179. indices.push(col + row * (options.subdivisions + 1));
  38180. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38181. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38182. indices.push(col + row * (options.subdivisions + 1));
  38183. }
  38184. }
  38185. // Normals
  38186. VertexData.ComputeNormals(positions, indices, normals);
  38187. // Result
  38188. var vertexData = new VertexData();
  38189. vertexData.indices = indices;
  38190. vertexData.positions = positions;
  38191. vertexData.normals = normals;
  38192. vertexData.uvs = uvs;
  38193. return vertexData;
  38194. };
  38195. /**
  38196. * Creates the VertexData for a Plane
  38197. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38198. * * size sets the width and height of the plane to the value of size, optional default 1
  38199. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38200. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38201. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38202. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38203. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38204. * @returns the VertexData of the box
  38205. */
  38206. VertexData.CreatePlane = function (options) {
  38207. var indices = [];
  38208. var positions = [];
  38209. var normals = [];
  38210. var uvs = [];
  38211. var width = options.width || options.size || 1;
  38212. var height = options.height || options.size || 1;
  38213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38214. // Vertices
  38215. var halfWidth = width / 2.0;
  38216. var halfHeight = height / 2.0;
  38217. positions.push(-halfWidth, -halfHeight, 0);
  38218. normals.push(0, 0, -1.0);
  38219. uvs.push(0.0, 0.0);
  38220. positions.push(halfWidth, -halfHeight, 0);
  38221. normals.push(0, 0, -1.0);
  38222. uvs.push(1.0, 0.0);
  38223. positions.push(halfWidth, halfHeight, 0);
  38224. normals.push(0, 0, -1.0);
  38225. uvs.push(1.0, 1.0);
  38226. positions.push(-halfWidth, halfHeight, 0);
  38227. normals.push(0, 0, -1.0);
  38228. uvs.push(0.0, 1.0);
  38229. // Indices
  38230. indices.push(0);
  38231. indices.push(1);
  38232. indices.push(2);
  38233. indices.push(0);
  38234. indices.push(2);
  38235. indices.push(3);
  38236. // Sides
  38237. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38238. // Result
  38239. var vertexData = new VertexData();
  38240. vertexData.indices = indices;
  38241. vertexData.positions = positions;
  38242. vertexData.normals = normals;
  38243. vertexData.uvs = uvs;
  38244. return vertexData;
  38245. };
  38246. /**
  38247. * Creates the VertexData of the Disc or regular Polygon
  38248. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38249. * * radius the radius of the disc, optional default 0.5
  38250. * * tessellation the number of polygon sides, optional, default 64
  38251. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  38252. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38253. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38254. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38255. * @returns the VertexData of the box
  38256. */
  38257. VertexData.CreateDisc = function (options) {
  38258. var positions = new Array();
  38259. var indices = new Array();
  38260. var normals = new Array();
  38261. var uvs = new Array();
  38262. var radius = options.radius || 0.5;
  38263. var tessellation = options.tessellation || 64;
  38264. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38266. // positions and uvs
  38267. positions.push(0, 0, 0); // disc center first
  38268. uvs.push(0.5, 0.5);
  38269. var theta = Math.PI * 2 * arc;
  38270. var step = theta / tessellation;
  38271. for (var a = 0; a < theta; a += step) {
  38272. var x = Math.cos(a);
  38273. var y = Math.sin(a);
  38274. var u = (x + 1) / 2;
  38275. var v = (1 - y) / 2;
  38276. positions.push(radius * x, radius * y, 0);
  38277. uvs.push(u, v);
  38278. }
  38279. if (arc === 1) {
  38280. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38281. uvs.push(uvs[2], uvs[3]);
  38282. }
  38283. //indices
  38284. var vertexNb = positions.length / 3;
  38285. for (var i = 1; i < vertexNb - 1; i++) {
  38286. indices.push(i + 1, 0, i);
  38287. }
  38288. // result
  38289. VertexData.ComputeNormals(positions, indices, normals);
  38290. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38291. var vertexData = new VertexData();
  38292. vertexData.indices = indices;
  38293. vertexData.positions = positions;
  38294. vertexData.normals = normals;
  38295. vertexData.uvs = uvs;
  38296. return vertexData;
  38297. };
  38298. /**
  38299. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38300. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38301. * @param polygon a mesh built from polygonTriangulation.build()
  38302. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38303. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38304. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38305. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38306. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38307. * @returns the VertexData of the Polygon
  38308. */
  38309. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38310. var faceUV = fUV || new Array(3);
  38311. var faceColors = fColors;
  38312. var colors = [];
  38313. // default face colors and UV if undefined
  38314. for (var f = 0; f < 3; f++) {
  38315. if (faceUV[f] === undefined) {
  38316. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38317. }
  38318. if (faceColors && faceColors[f] === undefined) {
  38319. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38320. }
  38321. }
  38322. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38323. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38324. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38325. var indices = polygon.getIndices();
  38326. // set face colours and textures
  38327. var idx = 0;
  38328. var face = 0;
  38329. for (var index = 0; index < normals.length; index += 3) {
  38330. //Edge Face no. 1
  38331. if (Math.abs(normals[index + 1]) < 0.001) {
  38332. face = 1;
  38333. }
  38334. //Top Face no. 0
  38335. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38336. face = 0;
  38337. }
  38338. //Bottom Face no. 2
  38339. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38340. face = 2;
  38341. }
  38342. idx = index / 3;
  38343. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38344. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38345. if (faceColors) {
  38346. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38347. }
  38348. }
  38349. // sides
  38350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38351. // Result
  38352. var vertexData = new VertexData();
  38353. vertexData.indices = indices;
  38354. vertexData.positions = positions;
  38355. vertexData.normals = normals;
  38356. vertexData.uvs = uvs;
  38357. if (faceColors) {
  38358. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38359. vertexData.colors = totalColors;
  38360. }
  38361. return vertexData;
  38362. };
  38363. /**
  38364. * Creates the VertexData of the IcoSphere
  38365. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38366. * * radius the radius of the IcoSphere, optional default 1
  38367. * * radiusX allows stretching in the x direction, optional, default radius
  38368. * * radiusY allows stretching in the y direction, optional, default radius
  38369. * * radiusZ allows stretching in the z direction, optional, default radius
  38370. * * flat when true creates a flat shaded mesh, optional, default true
  38371. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38372. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38373. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38374. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38375. * @returns the VertexData of the IcoSphere
  38376. */
  38377. VertexData.CreateIcoSphere = function (options) {
  38378. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38379. var radius = options.radius || 1;
  38380. var flat = (options.flat === undefined) ? true : options.flat;
  38381. var subdivisions = options.subdivisions || 4;
  38382. var radiusX = options.radiusX || radius;
  38383. var radiusY = options.radiusY || radius;
  38384. var radiusZ = options.radiusZ || radius;
  38385. var t = (1 + Math.sqrt(5)) / 2;
  38386. // 12 vertex x,y,z
  38387. var ico_vertices = [
  38388. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38389. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38390. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38391. ];
  38392. // index of 3 vertex makes a face of icopshere
  38393. var ico_indices = [
  38394. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38395. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38396. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38397. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38398. ];
  38399. // vertex for uv have aliased position, not for UV
  38400. var vertices_unalias_id = [
  38401. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38402. // vertex alias
  38403. 0,
  38404. 2,
  38405. 3,
  38406. 3,
  38407. 3,
  38408. 4,
  38409. 7,
  38410. 8,
  38411. 9,
  38412. 9,
  38413. 10,
  38414. 11 // 23: B + 12
  38415. ];
  38416. // uv as integer step (not pixels !)
  38417. var ico_vertexuv = [
  38418. 5, 1, 3, 1, 6, 4, 0, 0,
  38419. 5, 3, 4, 2, 2, 2, 4, 0,
  38420. 2, 0, 1, 1, 6, 0, 6, 2,
  38421. // vertex alias (for same vertex on different faces)
  38422. 0, 4,
  38423. 3, 3,
  38424. 4, 4,
  38425. 3, 1,
  38426. 4, 2,
  38427. 4, 4,
  38428. 0, 2,
  38429. 1, 1,
  38430. 2, 2,
  38431. 3, 3,
  38432. 1, 3,
  38433. 2, 4 // 23: B + 12
  38434. ];
  38435. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38436. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38437. // First island of uv mapping
  38438. // v = 4h 3+ 2
  38439. // v = 3h 9+ 4
  38440. // v = 2h 9+ 5 B
  38441. // v = 1h 9 1 0
  38442. // v = 0h 3 8 7 A
  38443. // u = 0 1 2 3 4 5 6 *a
  38444. // Second island of uv mapping
  38445. // v = 4h 0+ B+ 4+
  38446. // v = 3h A+ 2+
  38447. // v = 2h 7+ 6 3+
  38448. // v = 1h 8+ 3+
  38449. // v = 0h
  38450. // u = 0 1 2 3 4 5 6 *a
  38451. // Face layout on texture UV mapping
  38452. // ============
  38453. // \ 4 /\ 16 / ======
  38454. // \ / \ / /\ 11 /
  38455. // \/ 7 \/ / \ /
  38456. // ======= / 10 \/
  38457. // /\ 17 /\ =======
  38458. // / \ / \ \ 15 /\
  38459. // / 8 \/ 12 \ \ / \
  38460. // ============ \/ 6 \
  38461. // \ 18 /\ ============
  38462. // \ / \ \ 5 /\ 0 /
  38463. // \/ 13 \ \ / \ /
  38464. // ======= \/ 1 \/
  38465. // =============
  38466. // /\ 19 /\ 2 /\
  38467. // / \ / \ / \
  38468. // / 14 \/ 9 \/ 3 \
  38469. // ===================
  38470. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38471. var ustep = 138 / 1024;
  38472. var vstep = 239 / 1024;
  38473. var uoffset = 60 / 1024;
  38474. var voffset = 26 / 1024;
  38475. // Second island should have margin, not to touch the first island
  38476. // avoid any borderline artefact in pixel rounding
  38477. var island_u_offset = -40 / 1024;
  38478. var island_v_offset = +20 / 1024;
  38479. // face is either island 0 or 1 :
  38480. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38481. var island = [
  38482. 0, 0, 0, 0, 1,
  38483. 0, 0, 1, 1, 0,
  38484. 0, 0, 1, 1, 0,
  38485. 0, 1, 1, 1, 0 // 15 - 19
  38486. ];
  38487. var indices = new Array();
  38488. var positions = new Array();
  38489. var normals = new Array();
  38490. var uvs = new Array();
  38491. var current_indice = 0;
  38492. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38493. var face_vertex_pos = new Array(3);
  38494. var face_vertex_uv = new Array(3);
  38495. var v012;
  38496. for (v012 = 0; v012 < 3; v012++) {
  38497. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38498. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38499. }
  38500. // create all with normals
  38501. for (var face = 0; face < 20; face++) {
  38502. // 3 vertex per face
  38503. for (v012 = 0; v012 < 3; v012++) {
  38504. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38505. var v_id = ico_indices[3 * face + v012];
  38506. // vertex have 3D position (x,y,z)
  38507. 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]);
  38508. // Normalize to get normal, then scale to radius
  38509. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38510. // uv Coordinates from vertex ID
  38511. 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);
  38512. }
  38513. // Subdivide the face (interpolate pos, norm, uv)
  38514. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38515. // - norm is linear interpolation of vertex corner normal
  38516. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38517. // - uv is linear interpolation
  38518. //
  38519. // Topology is as below for sub-divide by 2
  38520. // vertex shown as v0,v1,v2
  38521. // interp index is i1 to progress in range [v0,v1[
  38522. // interp index is i2 to progress in range [v0,v2[
  38523. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38524. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38525. //
  38526. //
  38527. // i2 v2
  38528. // ^ ^
  38529. // / / \
  38530. // / / \
  38531. // / / \
  38532. // / / (0,1) \
  38533. // / #---------\
  38534. // / / \ (0,0)'/ \
  38535. // / / \ / \
  38536. // / / \ / \
  38537. // / / (0,0) \ / (1,0) \
  38538. // / #---------#---------\
  38539. // v0 v1
  38540. //
  38541. // --------------------> i1
  38542. //
  38543. // interp of (i1,i2):
  38544. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38545. // along i1 : lerp(x0,x1, i1/(S-i2))
  38546. //
  38547. // centroid of triangle is needed to get help normal computation
  38548. // (c1,c2) are used for centroid location
  38549. var interp_vertex = function (i1, i2, c1, c2) {
  38550. // vertex is interpolated from
  38551. // - face_vertex_pos[0..2]
  38552. // - face_vertex_uv[0..2]
  38553. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38554. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38555. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38556. pos_interp.normalize();
  38557. var vertex_normal;
  38558. if (flat) {
  38559. // in flat mode, recalculate normal as face centroid normal
  38560. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38561. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38562. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38563. }
  38564. else {
  38565. // in smooth mode, recalculate normal from each single vertex position
  38566. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38567. }
  38568. // Vertex normal need correction due to X,Y,Z radius scaling
  38569. vertex_normal.x /= radiusX;
  38570. vertex_normal.y /= radiusY;
  38571. vertex_normal.z /= radiusZ;
  38572. vertex_normal.normalize();
  38573. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38574. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38575. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38576. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38577. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38578. uvs.push(uv_interp.x, uv_interp.y);
  38579. // push each vertex has member of a face
  38580. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38581. indices.push(current_indice);
  38582. current_indice++;
  38583. };
  38584. for (var i2 = 0; i2 < subdivisions; i2++) {
  38585. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38586. // face : (i1,i2) for /\ :
  38587. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38588. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38589. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38590. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38591. if (i1 + i2 + 1 < subdivisions) {
  38592. // face : (i1,i2)' for \/ :
  38593. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38594. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38595. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38596. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38597. }
  38598. }
  38599. }
  38600. }
  38601. // Sides
  38602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38603. // Result
  38604. var vertexData = new VertexData();
  38605. vertexData.indices = indices;
  38606. vertexData.positions = positions;
  38607. vertexData.normals = normals;
  38608. vertexData.uvs = uvs;
  38609. return vertexData;
  38610. };
  38611. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38612. /**
  38613. * Creates the VertexData for a Polyhedron
  38614. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38615. * * type provided types are:
  38616. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38617. * * 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)
  38618. * * size the size of the IcoSphere, optional default 1
  38619. * * sizeX allows stretching in the x direction, optional, default size
  38620. * * sizeY allows stretching in the y direction, optional, default size
  38621. * * sizeZ allows stretching in the z direction, optional, default size
  38622. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38623. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38624. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38625. * * flat when true creates a flat shaded mesh, optional, default true
  38626. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38627. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38628. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38629. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38630. * @returns the VertexData of the Polyhedron
  38631. */
  38632. VertexData.CreatePolyhedron = function (options) {
  38633. // provided polyhedron types :
  38634. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38635. // 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)
  38636. var polyhedra = [];
  38637. 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]] };
  38638. 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]] };
  38639. polyhedra[2] = {
  38640. 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]],
  38641. 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]]
  38642. };
  38643. polyhedra[3] = {
  38644. 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]],
  38645. 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]]
  38646. };
  38647. polyhedra[4] = {
  38648. 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]],
  38649. 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]]
  38650. };
  38651. 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]] };
  38652. 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]] };
  38653. 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]] };
  38654. 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]] };
  38655. 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]] };
  38656. 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]] };
  38657. 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]] };
  38658. 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]] };
  38659. 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]] };
  38660. polyhedra[14] = {
  38661. 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]],
  38662. 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]]
  38663. };
  38664. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38665. var size = options.size;
  38666. var sizeX = options.sizeX || size || 1;
  38667. var sizeY = options.sizeY || size || 1;
  38668. var sizeZ = options.sizeZ || size || 1;
  38669. var data = options.custom || polyhedra[type];
  38670. var nbfaces = data.face.length;
  38671. var faceUV = options.faceUV || new Array(nbfaces);
  38672. var faceColors = options.faceColors;
  38673. var flat = (options.flat === undefined) ? true : options.flat;
  38674. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38675. var positions = new Array();
  38676. var indices = new Array();
  38677. var normals = new Array();
  38678. var uvs = new Array();
  38679. var colors = new Array();
  38680. var index = 0;
  38681. var faceIdx = 0; // face cursor in the array "indexes"
  38682. var indexes = new Array();
  38683. var i = 0;
  38684. var f = 0;
  38685. var u, v, ang, x, y, tmp;
  38686. // default face colors and UV if undefined
  38687. if (flat) {
  38688. for (f = 0; f < nbfaces; f++) {
  38689. if (faceColors && faceColors[f] === undefined) {
  38690. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38691. }
  38692. if (faceUV && faceUV[f] === undefined) {
  38693. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38694. }
  38695. }
  38696. }
  38697. if (!flat) {
  38698. for (i = 0; i < data.vertex.length; i++) {
  38699. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38700. uvs.push(0, 0);
  38701. }
  38702. for (f = 0; f < nbfaces; f++) {
  38703. for (i = 0; i < data.face[f].length - 2; i++) {
  38704. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38705. }
  38706. }
  38707. }
  38708. else {
  38709. for (f = 0; f < nbfaces; f++) {
  38710. var fl = data.face[f].length; // number of vertices of the current face
  38711. ang = 2 * Math.PI / fl;
  38712. x = 0.5 * Math.tan(ang / 2);
  38713. y = 0.5;
  38714. // positions, uvs, colors
  38715. for (i = 0; i < fl; i++) {
  38716. // positions
  38717. 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);
  38718. indexes.push(index);
  38719. index++;
  38720. // uvs
  38721. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38722. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38723. uvs.push(u, v);
  38724. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38725. y = x * Math.sin(ang) + y * Math.cos(ang);
  38726. x = tmp;
  38727. // colors
  38728. if (faceColors) {
  38729. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38730. }
  38731. }
  38732. // indices from indexes
  38733. for (i = 0; i < fl - 2; i++) {
  38734. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38735. }
  38736. faceIdx += fl;
  38737. }
  38738. }
  38739. VertexData.ComputeNormals(positions, indices, normals);
  38740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38741. var vertexData = new VertexData();
  38742. vertexData.positions = positions;
  38743. vertexData.indices = indices;
  38744. vertexData.normals = normals;
  38745. vertexData.uvs = uvs;
  38746. if (faceColors && flat) {
  38747. vertexData.colors = colors;
  38748. }
  38749. return vertexData;
  38750. };
  38751. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38752. /**
  38753. * Creates the VertexData for a TorusKnot
  38754. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38755. * * radius the radius of the torus knot, optional, default 2
  38756. * * tube the thickness of the tube, optional, default 0.5
  38757. * * radialSegments the number of sides on each tube segments, optional, default 32
  38758. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38759. * * p the number of windings around the z axis, optional, default 2
  38760. * * q the number of windings around the x axis, optional, default 3
  38761. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38762. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38763. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38764. * @returns the VertexData of the Torus Knot
  38765. */
  38766. VertexData.CreateTorusKnot = function (options) {
  38767. var indices = new Array();
  38768. var positions = new Array();
  38769. var normals = new Array();
  38770. var uvs = new Array();
  38771. var radius = options.radius || 2;
  38772. var tube = options.tube || 0.5;
  38773. var radialSegments = options.radialSegments || 32;
  38774. var tubularSegments = options.tubularSegments || 32;
  38775. var p = options.p || 2;
  38776. var q = options.q || 3;
  38777. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38778. // Helper
  38779. var getPos = function (angle) {
  38780. var cu = Math.cos(angle);
  38781. var su = Math.sin(angle);
  38782. var quOverP = q / p * angle;
  38783. var cs = Math.cos(quOverP);
  38784. var tx = radius * (2 + cs) * 0.5 * cu;
  38785. var ty = radius * (2 + cs) * su * 0.5;
  38786. var tz = radius * Math.sin(quOverP) * 0.5;
  38787. return new BABYLON.Vector3(tx, ty, tz);
  38788. };
  38789. // Vertices
  38790. var i;
  38791. var j;
  38792. for (i = 0; i <= radialSegments; i++) {
  38793. var modI = i % radialSegments;
  38794. var u = modI / radialSegments * 2 * p * Math.PI;
  38795. var p1 = getPos(u);
  38796. var p2 = getPos(u + 0.01);
  38797. var tang = p2.subtract(p1);
  38798. var n = p2.add(p1);
  38799. var bitan = BABYLON.Vector3.Cross(tang, n);
  38800. n = BABYLON.Vector3.Cross(bitan, tang);
  38801. bitan.normalize();
  38802. n.normalize();
  38803. for (j = 0; j < tubularSegments; j++) {
  38804. var modJ = j % tubularSegments;
  38805. var v = modJ / tubularSegments * 2 * Math.PI;
  38806. var cx = -tube * Math.cos(v);
  38807. var cy = tube * Math.sin(v);
  38808. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38809. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38810. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38811. uvs.push(i / radialSegments);
  38812. uvs.push(j / tubularSegments);
  38813. }
  38814. }
  38815. for (i = 0; i < radialSegments; i++) {
  38816. for (j = 0; j < tubularSegments; j++) {
  38817. var jNext = (j + 1) % tubularSegments;
  38818. var a = i * tubularSegments + j;
  38819. var b = (i + 1) * tubularSegments + j;
  38820. var c = (i + 1) * tubularSegments + jNext;
  38821. var d = i * tubularSegments + jNext;
  38822. indices.push(d);
  38823. indices.push(b);
  38824. indices.push(a);
  38825. indices.push(d);
  38826. indices.push(c);
  38827. indices.push(b);
  38828. }
  38829. }
  38830. // Normals
  38831. VertexData.ComputeNormals(positions, indices, normals);
  38832. // Sides
  38833. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38834. // Result
  38835. var vertexData = new VertexData();
  38836. vertexData.indices = indices;
  38837. vertexData.positions = positions;
  38838. vertexData.normals = normals;
  38839. vertexData.uvs = uvs;
  38840. return vertexData;
  38841. };
  38842. // Tools
  38843. /**
  38844. * Compute normals for given positions and indices
  38845. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38846. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38847. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38848. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38849. * * facetNormals : optional array of facet normals (vector3)
  38850. * * facetPositions : optional array of facet positions (vector3)
  38851. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38852. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38853. * * bInfo : optional bounding info, required for facetPartitioning computation
  38854. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38855. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38856. * * useRightHandedSystem: optional boolean to for right handed system computation
  38857. * * depthSort : optional boolean to enable the facet depth sort computation
  38858. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38859. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38860. */
  38861. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38862. // temporary scalar variables
  38863. var index = 0; // facet index
  38864. var p1p2x = 0.0; // p1p2 vector x coordinate
  38865. var p1p2y = 0.0; // p1p2 vector y coordinate
  38866. var p1p2z = 0.0; // p1p2 vector z coordinate
  38867. var p3p2x = 0.0; // p3p2 vector x coordinate
  38868. var p3p2y = 0.0; // p3p2 vector y coordinate
  38869. var p3p2z = 0.0; // p3p2 vector z coordinate
  38870. var faceNormalx = 0.0; // facet normal x coordinate
  38871. var faceNormaly = 0.0; // facet normal y coordinate
  38872. var faceNormalz = 0.0; // facet normal z coordinate
  38873. var length = 0.0; // facet normal length before normalization
  38874. var v1x = 0; // vector1 x index in the positions array
  38875. var v1y = 0; // vector1 y index in the positions array
  38876. var v1z = 0; // vector1 z index in the positions array
  38877. var v2x = 0; // vector2 x index in the positions array
  38878. var v2y = 0; // vector2 y index in the positions array
  38879. var v2z = 0; // vector2 z index in the positions array
  38880. var v3x = 0; // vector3 x index in the positions array
  38881. var v3y = 0; // vector3 y index in the positions array
  38882. var v3z = 0; // vector3 z index in the positions array
  38883. var computeFacetNormals = false;
  38884. var computeFacetPositions = false;
  38885. var computeFacetPartitioning = false;
  38886. var computeDepthSort = false;
  38887. var faceNormalSign = 1;
  38888. var ratio = 0;
  38889. var distanceTo = null;
  38890. if (options) {
  38891. computeFacetNormals = (options.facetNormals) ? true : false;
  38892. computeFacetPositions = (options.facetPositions) ? true : false;
  38893. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38894. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38895. ratio = options.ratio || 0;
  38896. computeDepthSort = (options.depthSort) ? true : false;
  38897. distanceTo = (options.distanceTo);
  38898. if (computeDepthSort) {
  38899. if (distanceTo === undefined) {
  38900. distanceTo = BABYLON.Vector3.Zero();
  38901. }
  38902. var depthSortedFacets = options.depthSortedFacets;
  38903. }
  38904. }
  38905. // facetPartitioning reinit if needed
  38906. var xSubRatio = 0;
  38907. var ySubRatio = 0;
  38908. var zSubRatio = 0;
  38909. var subSq = 0;
  38910. if (computeFacetPartitioning && options && options.bbSize) {
  38911. var ox = 0; // X partitioning index for facet position
  38912. var oy = 0; // Y partinioning index for facet position
  38913. var oz = 0; // Z partinioning index for facet position
  38914. var b1x = 0; // X partitioning index for facet v1 vertex
  38915. var b1y = 0; // Y partitioning index for facet v1 vertex
  38916. var b1z = 0; // z partitioning index for facet v1 vertex
  38917. var b2x = 0; // X partitioning index for facet v2 vertex
  38918. var b2y = 0; // Y partitioning index for facet v2 vertex
  38919. var b2z = 0; // Z partitioning index for facet v2 vertex
  38920. var b3x = 0; // X partitioning index for facet v3 vertex
  38921. var b3y = 0; // Y partitioning index for facet v3 vertex
  38922. var b3z = 0; // Z partitioning index for facet v3 vertex
  38923. var block_idx_o = 0; // facet barycenter block index
  38924. var block_idx_v1 = 0; // v1 vertex block index
  38925. var block_idx_v2 = 0; // v2 vertex block index
  38926. var block_idx_v3 = 0; // v3 vertex block index
  38927. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38928. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38929. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38930. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38931. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38932. subSq = options.subDiv.max * options.subDiv.max;
  38933. options.facetPartitioning.length = 0;
  38934. }
  38935. // reset the normals
  38936. for (index = 0; index < positions.length; index++) {
  38937. normals[index] = 0.0;
  38938. }
  38939. // Loop : 1 indice triplet = 1 facet
  38940. var nbFaces = (indices.length / 3) | 0;
  38941. for (index = 0; index < nbFaces; index++) {
  38942. // get the indexes of the coordinates of each vertex of the facet
  38943. v1x = indices[index * 3] * 3;
  38944. v1y = v1x + 1;
  38945. v1z = v1x + 2;
  38946. v2x = indices[index * 3 + 1] * 3;
  38947. v2y = v2x + 1;
  38948. v2z = v2x + 2;
  38949. v3x = indices[index * 3 + 2] * 3;
  38950. v3y = v3x + 1;
  38951. v3z = v3x + 2;
  38952. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38953. p1p2y = positions[v1y] - positions[v2y];
  38954. p1p2z = positions[v1z] - positions[v2z];
  38955. p3p2x = positions[v3x] - positions[v2x];
  38956. p3p2y = positions[v3y] - positions[v2y];
  38957. p3p2z = positions[v3z] - positions[v2z];
  38958. // compute the face normal with the cross product
  38959. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38960. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38961. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38962. // normalize this normal and store it in the array facetData
  38963. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38964. length = (length === 0) ? 1.0 : length;
  38965. faceNormalx /= length;
  38966. faceNormaly /= length;
  38967. faceNormalz /= length;
  38968. if (computeFacetNormals && options) {
  38969. options.facetNormals[index].x = faceNormalx;
  38970. options.facetNormals[index].y = faceNormaly;
  38971. options.facetNormals[index].z = faceNormalz;
  38972. }
  38973. if (computeFacetPositions && options) {
  38974. // compute and the facet barycenter coordinates in the array facetPositions
  38975. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38976. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38977. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38978. }
  38979. if (computeFacetPartitioning && options) {
  38980. // store the facet indexes in arrays in the main facetPartitioning array :
  38981. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38982. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38983. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38984. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38985. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38986. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38987. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38988. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38989. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38990. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38991. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38992. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38993. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38994. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38995. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38996. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38997. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38998. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38999. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39000. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39001. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39002. // push each facet index in each block containing the vertex
  39003. options.facetPartitioning[block_idx_v1].push(index);
  39004. if (block_idx_v2 != block_idx_v1) {
  39005. options.facetPartitioning[block_idx_v2].push(index);
  39006. }
  39007. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39008. options.facetPartitioning[block_idx_v3].push(index);
  39009. }
  39010. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39011. options.facetPartitioning[block_idx_o].push(index);
  39012. }
  39013. }
  39014. if (computeDepthSort && options && options.facetPositions) {
  39015. var dsf = depthSortedFacets[index];
  39016. dsf.ind = index * 3;
  39017. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39018. }
  39019. // compute the normals anyway
  39020. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39021. normals[v1y] += faceNormaly;
  39022. normals[v1z] += faceNormalz;
  39023. normals[v2x] += faceNormalx;
  39024. normals[v2y] += faceNormaly;
  39025. normals[v2z] += faceNormalz;
  39026. normals[v3x] += faceNormalx;
  39027. normals[v3y] += faceNormaly;
  39028. normals[v3z] += faceNormalz;
  39029. }
  39030. // last normalization of each normal
  39031. for (index = 0; index < normals.length / 3; index++) {
  39032. faceNormalx = normals[index * 3];
  39033. faceNormaly = normals[index * 3 + 1];
  39034. faceNormalz = normals[index * 3 + 2];
  39035. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39036. length = (length === 0) ? 1.0 : length;
  39037. faceNormalx /= length;
  39038. faceNormaly /= length;
  39039. faceNormalz /= length;
  39040. normals[index * 3] = faceNormalx;
  39041. normals[index * 3 + 1] = faceNormaly;
  39042. normals[index * 3 + 2] = faceNormalz;
  39043. }
  39044. };
  39045. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39046. var li = indices.length;
  39047. var ln = normals.length;
  39048. var i;
  39049. var n;
  39050. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39051. switch (sideOrientation) {
  39052. case BABYLON.Mesh.FRONTSIDE:
  39053. // nothing changed
  39054. break;
  39055. case BABYLON.Mesh.BACKSIDE:
  39056. var tmp;
  39057. // indices
  39058. for (i = 0; i < li; i += 3) {
  39059. tmp = indices[i];
  39060. indices[i] = indices[i + 2];
  39061. indices[i + 2] = tmp;
  39062. }
  39063. // normals
  39064. for (n = 0; n < ln; n++) {
  39065. normals[n] = -normals[n];
  39066. }
  39067. break;
  39068. case BABYLON.Mesh.DOUBLESIDE:
  39069. // positions
  39070. var lp = positions.length;
  39071. var l = lp / 3;
  39072. for (var p = 0; p < lp; p++) {
  39073. positions[lp + p] = positions[p];
  39074. }
  39075. // indices
  39076. for (i = 0; i < li; i += 3) {
  39077. indices[i + li] = indices[i + 2] + l;
  39078. indices[i + 1 + li] = indices[i + 1] + l;
  39079. indices[i + 2 + li] = indices[i] + l;
  39080. }
  39081. // normals
  39082. for (n = 0; n < ln; n++) {
  39083. normals[ln + n] = -normals[n];
  39084. }
  39085. // uvs
  39086. var lu = uvs.length;
  39087. var u = 0;
  39088. for (u = 0; u < lu; u++) {
  39089. uvs[u + lu] = uvs[u];
  39090. }
  39091. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39092. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39093. u = 0;
  39094. for (i = 0; i < lu / 2; i++) {
  39095. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39096. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39097. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39098. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39099. u += 2;
  39100. }
  39101. break;
  39102. }
  39103. };
  39104. /**
  39105. * Applies VertexData created from the imported parameters to the geometry
  39106. * @param parsedVertexData the parsed data from an imported file
  39107. * @param geometry the geometry to apply the VertexData to
  39108. */
  39109. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39110. var vertexData = new VertexData();
  39111. // positions
  39112. var positions = parsedVertexData.positions;
  39113. if (positions) {
  39114. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39115. }
  39116. // normals
  39117. var normals = parsedVertexData.normals;
  39118. if (normals) {
  39119. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39120. }
  39121. // tangents
  39122. var tangents = parsedVertexData.tangents;
  39123. if (tangents) {
  39124. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39125. }
  39126. // uvs
  39127. var uvs = parsedVertexData.uvs;
  39128. if (uvs) {
  39129. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39130. }
  39131. // uv2s
  39132. var uv2s = parsedVertexData.uv2s;
  39133. if (uv2s) {
  39134. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39135. }
  39136. // uv3s
  39137. var uv3s = parsedVertexData.uv3s;
  39138. if (uv3s) {
  39139. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39140. }
  39141. // uv4s
  39142. var uv4s = parsedVertexData.uv4s;
  39143. if (uv4s) {
  39144. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39145. }
  39146. // uv5s
  39147. var uv5s = parsedVertexData.uv5s;
  39148. if (uv5s) {
  39149. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39150. }
  39151. // uv6s
  39152. var uv6s = parsedVertexData.uv6s;
  39153. if (uv6s) {
  39154. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39155. }
  39156. // colors
  39157. var colors = parsedVertexData.colors;
  39158. if (colors) {
  39159. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39160. }
  39161. // matricesIndices
  39162. var matricesIndices = parsedVertexData.matricesIndices;
  39163. if (matricesIndices) {
  39164. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39165. }
  39166. // matricesWeights
  39167. var matricesWeights = parsedVertexData.matricesWeights;
  39168. if (matricesWeights) {
  39169. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39170. }
  39171. // indices
  39172. var indices = parsedVertexData.indices;
  39173. if (indices) {
  39174. vertexData.indices = indices;
  39175. }
  39176. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39177. };
  39178. return VertexData;
  39179. }());
  39180. BABYLON.VertexData = VertexData;
  39181. })(BABYLON || (BABYLON = {}));
  39182. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39183. var BABYLON;
  39184. (function (BABYLON) {
  39185. /**
  39186. * Class used to store geometry data (vertex buffers + index buffer)
  39187. */
  39188. var Geometry = /** @class */ (function () {
  39189. /**
  39190. * Creates a new geometry
  39191. * @param id defines the unique ID
  39192. * @param scene defines the hosting scene
  39193. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39194. * @param updatable defines if geometry must be updatable (false by default)
  39195. * @param mesh defines the mesh that will be associated with the geometry
  39196. */
  39197. function Geometry(id, scene, vertexData, updatable, mesh) {
  39198. if (updatable === void 0) { updatable = false; }
  39199. if (mesh === void 0) { mesh = null; }
  39200. /**
  39201. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39202. */
  39203. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39204. this._totalVertices = 0;
  39205. this._isDisposed = false;
  39206. this._indexBufferIsUpdatable = false;
  39207. this.id = id;
  39208. this._engine = scene.getEngine();
  39209. this._meshes = [];
  39210. this._scene = scene;
  39211. //Init vertex buffer cache
  39212. this._vertexBuffers = {};
  39213. this._indices = [];
  39214. this._updatable = updatable;
  39215. // vertexData
  39216. if (vertexData) {
  39217. this.setAllVerticesData(vertexData, updatable);
  39218. }
  39219. else {
  39220. this._totalVertices = 0;
  39221. this._indices = [];
  39222. }
  39223. if (this._engine.getCaps().vertexArrayObject) {
  39224. this._vertexArrayObjects = {};
  39225. }
  39226. // applyToMesh
  39227. if (mesh) {
  39228. if (mesh.getClassName() === "LinesMesh") {
  39229. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39230. this._updateExtend();
  39231. }
  39232. this.applyToMesh(mesh);
  39233. mesh.computeWorldMatrix(true);
  39234. }
  39235. }
  39236. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39237. /**
  39238. * 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
  39239. */
  39240. get: function () {
  39241. return this._boundingBias;
  39242. },
  39243. /**
  39244. * 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
  39245. */
  39246. set: function (value) {
  39247. if (this._boundingBias && this._boundingBias.equals(value)) {
  39248. return;
  39249. }
  39250. this._boundingBias = value.clone();
  39251. this._updateBoundingInfo(true, null);
  39252. },
  39253. enumerable: true,
  39254. configurable: true
  39255. });
  39256. /**
  39257. * Static function used to attach a new empty geometry to a mesh
  39258. * @param mesh defines the mesh to attach the geometry to
  39259. * @returns the new {BABYLON.Geometry}
  39260. */
  39261. Geometry.CreateGeometryForMesh = function (mesh) {
  39262. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39263. geometry.applyToMesh(mesh);
  39264. return geometry;
  39265. };
  39266. Object.defineProperty(Geometry.prototype, "extend", {
  39267. /**
  39268. * Gets the current extend of the geometry
  39269. */
  39270. get: function () {
  39271. return this._extend;
  39272. },
  39273. enumerable: true,
  39274. configurable: true
  39275. });
  39276. /**
  39277. * Gets the hosting scene
  39278. * @returns the hosting {BABYLON.Scene}
  39279. */
  39280. Geometry.prototype.getScene = function () {
  39281. return this._scene;
  39282. };
  39283. /**
  39284. * Gets the hosting engine
  39285. * @returns the hosting {BABYLON.Engine}
  39286. */
  39287. Geometry.prototype.getEngine = function () {
  39288. return this._engine;
  39289. };
  39290. /**
  39291. * Defines if the geometry is ready to use
  39292. * @returns true if the geometry is ready to be used
  39293. */
  39294. Geometry.prototype.isReady = function () {
  39295. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39296. };
  39297. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39298. /**
  39299. * Gets a value indicating that the geometry should not be serialized
  39300. */
  39301. get: function () {
  39302. for (var index = 0; index < this._meshes.length; index++) {
  39303. if (!this._meshes[index].doNotSerialize) {
  39304. return false;
  39305. }
  39306. }
  39307. return true;
  39308. },
  39309. enumerable: true,
  39310. configurable: true
  39311. });
  39312. /** @hidden */
  39313. Geometry.prototype._rebuild = function () {
  39314. if (this._vertexArrayObjects) {
  39315. this._vertexArrayObjects = {};
  39316. }
  39317. // Index buffer
  39318. if (this._meshes.length !== 0 && this._indices) {
  39319. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39320. }
  39321. // Vertex buffers
  39322. for (var key in this._vertexBuffers) {
  39323. var vertexBuffer = this._vertexBuffers[key];
  39324. vertexBuffer._rebuild();
  39325. }
  39326. };
  39327. /**
  39328. * Affects all geometry data in one call
  39329. * @param vertexData defines the geometry data
  39330. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39331. */
  39332. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39333. vertexData.applyToGeometry(this, updatable);
  39334. this.notifyUpdate();
  39335. };
  39336. /**
  39337. * Set specific vertex data
  39338. * @param kind defines the data kind (Position, normal, etc...)
  39339. * @param data defines the vertex data to use
  39340. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39341. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39342. */
  39343. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39344. if (updatable === void 0) { updatable = false; }
  39345. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39346. this.setVerticesBuffer(buffer);
  39347. };
  39348. /**
  39349. * Removes a specific vertex data
  39350. * @param kind defines the data kind (Position, normal, etc...)
  39351. */
  39352. Geometry.prototype.removeVerticesData = function (kind) {
  39353. if (this._vertexBuffers[kind]) {
  39354. this._vertexBuffers[kind].dispose();
  39355. delete this._vertexBuffers[kind];
  39356. }
  39357. };
  39358. /**
  39359. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39360. * @param buffer defines the vertex buffer to use
  39361. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39362. */
  39363. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39364. if (totalVertices === void 0) { totalVertices = null; }
  39365. var kind = buffer.getKind();
  39366. if (this._vertexBuffers[kind]) {
  39367. this._vertexBuffers[kind].dispose();
  39368. }
  39369. this._vertexBuffers[kind] = buffer;
  39370. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39371. var data = buffer.getData();
  39372. if (totalVertices != null) {
  39373. this._totalVertices = totalVertices;
  39374. }
  39375. else {
  39376. if (data != null) {
  39377. this._totalVertices = data.length / (buffer.byteStride / 4);
  39378. }
  39379. }
  39380. this._updateExtend(data);
  39381. this._resetPointsArrayCache();
  39382. var meshes = this._meshes;
  39383. var numOfMeshes = meshes.length;
  39384. for (var index = 0; index < numOfMeshes; index++) {
  39385. var mesh = meshes[index];
  39386. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39387. mesh._createGlobalSubMesh(false);
  39388. mesh.computeWorldMatrix(true);
  39389. }
  39390. }
  39391. this.notifyUpdate(kind);
  39392. if (this._vertexArrayObjects) {
  39393. this._disposeVertexArrayObjects();
  39394. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39395. }
  39396. };
  39397. /**
  39398. * Update a specific vertex buffer
  39399. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39400. * It will do nothing if the buffer is not updatable
  39401. * @param kind defines the data kind (Position, normal, etc...)
  39402. * @param data defines the data to use
  39403. * @param offset defines the offset in the target buffer where to store the data
  39404. * @param useBytes set to true if the offset is in bytes
  39405. */
  39406. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39407. if (useBytes === void 0) { useBytes = false; }
  39408. var vertexBuffer = this.getVertexBuffer(kind);
  39409. if (!vertexBuffer) {
  39410. return;
  39411. }
  39412. vertexBuffer.updateDirectly(data, offset, useBytes);
  39413. this.notifyUpdate(kind);
  39414. };
  39415. /**
  39416. * Update a specific vertex buffer
  39417. * This function will create a new buffer if the current one is not updatable
  39418. * @param kind defines the data kind (Position, normal, etc...)
  39419. * @param data defines the data to use
  39420. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39421. */
  39422. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39423. if (updateExtends === void 0) { updateExtends = false; }
  39424. var vertexBuffer = this.getVertexBuffer(kind);
  39425. if (!vertexBuffer) {
  39426. return;
  39427. }
  39428. vertexBuffer.update(data);
  39429. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39430. this._updateBoundingInfo(updateExtends, data);
  39431. }
  39432. this.notifyUpdate(kind);
  39433. };
  39434. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39435. if (updateExtends) {
  39436. this._updateExtend(data);
  39437. }
  39438. var meshes = this._meshes;
  39439. var numOfMeshes = meshes.length;
  39440. this._resetPointsArrayCache();
  39441. for (var index = 0; index < numOfMeshes; index++) {
  39442. var mesh = meshes[index];
  39443. if (updateExtends) {
  39444. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39445. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39446. var subMesh = mesh.subMeshes[subIndex];
  39447. subMesh.refreshBoundingInfo();
  39448. }
  39449. }
  39450. }
  39451. };
  39452. /** @hidden */
  39453. Geometry.prototype._bind = function (effect, indexToBind) {
  39454. if (!effect) {
  39455. return;
  39456. }
  39457. if (indexToBind === undefined) {
  39458. indexToBind = this._indexBuffer;
  39459. }
  39460. var vbs = this.getVertexBuffers();
  39461. if (!vbs) {
  39462. return;
  39463. }
  39464. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39465. this._engine.bindBuffers(vbs, indexToBind, effect);
  39466. return;
  39467. }
  39468. // Using VAO
  39469. if (!this._vertexArrayObjects[effect.key]) {
  39470. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39471. }
  39472. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39473. };
  39474. /**
  39475. * Gets total number of vertices
  39476. * @returns the total number of vertices
  39477. */
  39478. Geometry.prototype.getTotalVertices = function () {
  39479. if (!this.isReady()) {
  39480. return 0;
  39481. }
  39482. return this._totalVertices;
  39483. };
  39484. /**
  39485. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39486. * @param kind defines the data kind (Position, normal, etc...)
  39487. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39488. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39489. * @returns a float array containing vertex data
  39490. */
  39491. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39492. var vertexBuffer = this.getVertexBuffer(kind);
  39493. if (!vertexBuffer) {
  39494. return null;
  39495. }
  39496. var data = vertexBuffer.getData();
  39497. if (!data) {
  39498. return null;
  39499. }
  39500. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39501. var count = this._totalVertices * vertexBuffer.getSize();
  39502. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39503. var copy_1 = new Array(count);
  39504. vertexBuffer.forEach(count, function (value, index) {
  39505. copy_1[index] = value;
  39506. });
  39507. return copy_1;
  39508. }
  39509. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39510. if (data instanceof Array) {
  39511. var offset = vertexBuffer.byteOffset / 4;
  39512. return BABYLON.Tools.Slice(data, offset, offset + count);
  39513. }
  39514. else if (data instanceof ArrayBuffer) {
  39515. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39516. }
  39517. else {
  39518. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39519. }
  39520. }
  39521. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39522. return BABYLON.Tools.Slice(data);
  39523. }
  39524. return data;
  39525. };
  39526. /**
  39527. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39528. * @param kind defines the data kind (Position, normal, etc...)
  39529. * @returns true if the vertex buffer with the specified kind is updatable
  39530. */
  39531. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39532. var vb = this._vertexBuffers[kind];
  39533. if (!vb) {
  39534. return false;
  39535. }
  39536. return vb.isUpdatable();
  39537. };
  39538. /**
  39539. * Gets a specific vertex buffer
  39540. * @param kind defines the data kind (Position, normal, etc...)
  39541. * @returns a {BABYLON.VertexBuffer}
  39542. */
  39543. Geometry.prototype.getVertexBuffer = function (kind) {
  39544. if (!this.isReady()) {
  39545. return null;
  39546. }
  39547. return this._vertexBuffers[kind];
  39548. };
  39549. /**
  39550. * Returns all vertex buffers
  39551. * @return an object holding all vertex buffers indexed by kind
  39552. */
  39553. Geometry.prototype.getVertexBuffers = function () {
  39554. if (!this.isReady()) {
  39555. return null;
  39556. }
  39557. return this._vertexBuffers;
  39558. };
  39559. /**
  39560. * Gets a boolean indicating if specific vertex buffer is present
  39561. * @param kind defines the data kind (Position, normal, etc...)
  39562. * @returns true if data is present
  39563. */
  39564. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39565. if (!this._vertexBuffers) {
  39566. if (this._delayInfo) {
  39567. return this._delayInfo.indexOf(kind) !== -1;
  39568. }
  39569. return false;
  39570. }
  39571. return this._vertexBuffers[kind] !== undefined;
  39572. };
  39573. /**
  39574. * Gets a list of all attached data kinds (Position, normal, etc...)
  39575. * @returns a list of string containing all kinds
  39576. */
  39577. Geometry.prototype.getVerticesDataKinds = function () {
  39578. var result = [];
  39579. var kind;
  39580. if (!this._vertexBuffers && this._delayInfo) {
  39581. for (kind in this._delayInfo) {
  39582. result.push(kind);
  39583. }
  39584. }
  39585. else {
  39586. for (kind in this._vertexBuffers) {
  39587. result.push(kind);
  39588. }
  39589. }
  39590. return result;
  39591. };
  39592. /**
  39593. * Update index buffer
  39594. * @param indices defines the indices to store in the index buffer
  39595. * @param offset defines the offset in the target buffer where to store the data
  39596. */
  39597. Geometry.prototype.updateIndices = function (indices, offset) {
  39598. if (!this._indexBuffer) {
  39599. return;
  39600. }
  39601. if (!this._indexBufferIsUpdatable) {
  39602. this.setIndices(indices, null, true);
  39603. }
  39604. else {
  39605. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39606. }
  39607. };
  39608. /**
  39609. * Creates a new index buffer
  39610. * @param indices defines the indices to store in the index buffer
  39611. * @param totalVertices defines the total number of vertices (could be null)
  39612. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39613. */
  39614. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39615. if (totalVertices === void 0) { totalVertices = null; }
  39616. if (updatable === void 0) { updatable = false; }
  39617. if (this._indexBuffer) {
  39618. this._engine._releaseBuffer(this._indexBuffer);
  39619. }
  39620. this._disposeVertexArrayObjects();
  39621. this._indices = indices;
  39622. this._indexBufferIsUpdatable = updatable;
  39623. if (this._meshes.length !== 0 && this._indices) {
  39624. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39625. }
  39626. if (totalVertices != undefined) { // including null and undefined
  39627. this._totalVertices = totalVertices;
  39628. }
  39629. var meshes = this._meshes;
  39630. var numOfMeshes = meshes.length;
  39631. for (var index = 0; index < numOfMeshes; index++) {
  39632. meshes[index]._createGlobalSubMesh(true);
  39633. }
  39634. this.notifyUpdate();
  39635. };
  39636. /**
  39637. * Return the total number of indices
  39638. * @returns the total number of indices
  39639. */
  39640. Geometry.prototype.getTotalIndices = function () {
  39641. if (!this.isReady()) {
  39642. return 0;
  39643. }
  39644. return this._indices.length;
  39645. };
  39646. /**
  39647. * Gets the index buffer array
  39648. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39649. * @returns the index buffer array
  39650. */
  39651. Geometry.prototype.getIndices = function (copyWhenShared) {
  39652. if (!this.isReady()) {
  39653. return null;
  39654. }
  39655. var orig = this._indices;
  39656. if (!copyWhenShared || this._meshes.length === 1) {
  39657. return orig;
  39658. }
  39659. else {
  39660. var len = orig.length;
  39661. var copy = [];
  39662. for (var i = 0; i < len; i++) {
  39663. copy.push(orig[i]);
  39664. }
  39665. return copy;
  39666. }
  39667. };
  39668. /**
  39669. * Gets the index buffer
  39670. * @return the index buffer
  39671. */
  39672. Geometry.prototype.getIndexBuffer = function () {
  39673. if (!this.isReady()) {
  39674. return null;
  39675. }
  39676. return this._indexBuffer;
  39677. };
  39678. /** @hidden */
  39679. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39680. if (effect === void 0) { effect = null; }
  39681. if (!effect || !this._vertexArrayObjects) {
  39682. return;
  39683. }
  39684. if (this._vertexArrayObjects[effect.key]) {
  39685. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39686. delete this._vertexArrayObjects[effect.key];
  39687. }
  39688. };
  39689. /**
  39690. * Release the associated resources for a specific mesh
  39691. * @param mesh defines the source mesh
  39692. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39693. */
  39694. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39695. var meshes = this._meshes;
  39696. var index = meshes.indexOf(mesh);
  39697. if (index === -1) {
  39698. return;
  39699. }
  39700. meshes.splice(index, 1);
  39701. mesh._geometry = null;
  39702. if (meshes.length === 0 && shouldDispose) {
  39703. this.dispose();
  39704. }
  39705. };
  39706. /**
  39707. * Apply current geometry to a given mesh
  39708. * @param mesh defines the mesh to apply geometry to
  39709. */
  39710. Geometry.prototype.applyToMesh = function (mesh) {
  39711. if (mesh._geometry === this) {
  39712. return;
  39713. }
  39714. var previousGeometry = mesh._geometry;
  39715. if (previousGeometry) {
  39716. previousGeometry.releaseForMesh(mesh);
  39717. }
  39718. var meshes = this._meshes;
  39719. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39720. mesh._geometry = this;
  39721. this._scene.pushGeometry(this);
  39722. meshes.push(mesh);
  39723. if (this.isReady()) {
  39724. this._applyToMesh(mesh);
  39725. }
  39726. else {
  39727. mesh._boundingInfo = this._boundingInfo;
  39728. }
  39729. };
  39730. Geometry.prototype._updateExtend = function (data) {
  39731. if (data === void 0) { data = null; }
  39732. if (!data) {
  39733. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39734. }
  39735. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39736. };
  39737. Geometry.prototype._applyToMesh = function (mesh) {
  39738. var numOfMeshes = this._meshes.length;
  39739. // vertexBuffers
  39740. for (var kind in this._vertexBuffers) {
  39741. if (numOfMeshes === 1) {
  39742. this._vertexBuffers[kind].create();
  39743. }
  39744. var buffer = this._vertexBuffers[kind].getBuffer();
  39745. if (buffer)
  39746. buffer.references = numOfMeshes;
  39747. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39748. if (!this._extend) {
  39749. this._updateExtend();
  39750. }
  39751. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39752. mesh._createGlobalSubMesh(false);
  39753. //bounding info was just created again, world matrix should be applied again.
  39754. mesh._updateBoundingInfo();
  39755. }
  39756. }
  39757. // indexBuffer
  39758. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39759. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39760. }
  39761. if (this._indexBuffer) {
  39762. this._indexBuffer.references = numOfMeshes;
  39763. }
  39764. };
  39765. Geometry.prototype.notifyUpdate = function (kind) {
  39766. if (this.onGeometryUpdated) {
  39767. this.onGeometryUpdated(this, kind);
  39768. }
  39769. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39770. var mesh = _a[_i];
  39771. mesh._markSubMeshesAsAttributesDirty();
  39772. }
  39773. };
  39774. /**
  39775. * Load the geometry if it was flagged as delay loaded
  39776. * @param scene defines the hosting scene
  39777. * @param onLoaded defines a callback called when the geometry is loaded
  39778. */
  39779. Geometry.prototype.load = function (scene, onLoaded) {
  39780. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39781. return;
  39782. }
  39783. if (this.isReady()) {
  39784. if (onLoaded) {
  39785. onLoaded();
  39786. }
  39787. return;
  39788. }
  39789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39790. this._queueLoad(scene, onLoaded);
  39791. };
  39792. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39793. var _this = this;
  39794. if (!this.delayLoadingFile) {
  39795. return;
  39796. }
  39797. scene._addPendingData(this);
  39798. scene._loadFile(this.delayLoadingFile, function (data) {
  39799. if (!_this._delayLoadingFunction) {
  39800. return;
  39801. }
  39802. _this._delayLoadingFunction(JSON.parse(data), _this);
  39803. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39804. _this._delayInfo = [];
  39805. scene._removePendingData(_this);
  39806. var meshes = _this._meshes;
  39807. var numOfMeshes = meshes.length;
  39808. for (var index = 0; index < numOfMeshes; index++) {
  39809. _this._applyToMesh(meshes[index]);
  39810. }
  39811. if (onLoaded) {
  39812. onLoaded();
  39813. }
  39814. }, undefined, true);
  39815. };
  39816. /**
  39817. * Invert the geometry to move from a right handed system to a left handed one.
  39818. */
  39819. Geometry.prototype.toLeftHanded = function () {
  39820. // Flip faces
  39821. var tIndices = this.getIndices(false);
  39822. if (tIndices != null && tIndices.length > 0) {
  39823. for (var i = 0; i < tIndices.length; i += 3) {
  39824. var tTemp = tIndices[i + 0];
  39825. tIndices[i + 0] = tIndices[i + 2];
  39826. tIndices[i + 2] = tTemp;
  39827. }
  39828. this.setIndices(tIndices);
  39829. }
  39830. // Negate position.z
  39831. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39832. if (tPositions != null && tPositions.length > 0) {
  39833. for (var i = 0; i < tPositions.length; i += 3) {
  39834. tPositions[i + 2] = -tPositions[i + 2];
  39835. }
  39836. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39837. }
  39838. // Negate normal.z
  39839. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39840. if (tNormals != null && tNormals.length > 0) {
  39841. for (var i = 0; i < tNormals.length; i += 3) {
  39842. tNormals[i + 2] = -tNormals[i + 2];
  39843. }
  39844. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39845. }
  39846. };
  39847. // Cache
  39848. /** @hidden */
  39849. Geometry.prototype._resetPointsArrayCache = function () {
  39850. this._positions = null;
  39851. };
  39852. /** @hidden */
  39853. Geometry.prototype._generatePointsArray = function () {
  39854. if (this._positions)
  39855. return true;
  39856. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39857. if (!data || data.length === 0) {
  39858. return false;
  39859. }
  39860. this._positions = [];
  39861. for (var index = 0; index < data.length; index += 3) {
  39862. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39863. }
  39864. return true;
  39865. };
  39866. /**
  39867. * Gets a value indicating if the geometry is disposed
  39868. * @returns true if the geometry was disposed
  39869. */
  39870. Geometry.prototype.isDisposed = function () {
  39871. return this._isDisposed;
  39872. };
  39873. Geometry.prototype._disposeVertexArrayObjects = function () {
  39874. if (this._vertexArrayObjects) {
  39875. for (var kind in this._vertexArrayObjects) {
  39876. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39877. }
  39878. this._vertexArrayObjects = {};
  39879. }
  39880. };
  39881. /**
  39882. * Free all associated resources
  39883. */
  39884. Geometry.prototype.dispose = function () {
  39885. var meshes = this._meshes;
  39886. var numOfMeshes = meshes.length;
  39887. var index;
  39888. for (index = 0; index < numOfMeshes; index++) {
  39889. this.releaseForMesh(meshes[index]);
  39890. }
  39891. this._meshes = [];
  39892. this._disposeVertexArrayObjects();
  39893. for (var kind in this._vertexBuffers) {
  39894. this._vertexBuffers[kind].dispose();
  39895. }
  39896. this._vertexBuffers = {};
  39897. this._totalVertices = 0;
  39898. if (this._indexBuffer) {
  39899. this._engine._releaseBuffer(this._indexBuffer);
  39900. }
  39901. this._indexBuffer = null;
  39902. this._indices = [];
  39903. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39904. this.delayLoadingFile = null;
  39905. this._delayLoadingFunction = null;
  39906. this._delayInfo = [];
  39907. this._boundingInfo = null;
  39908. this._scene.removeGeometry(this);
  39909. this._isDisposed = true;
  39910. };
  39911. /**
  39912. * Clone the current geometry into a new geometry
  39913. * @param id defines the unique ID of the new geometry
  39914. * @returns a new geometry object
  39915. */
  39916. Geometry.prototype.copy = function (id) {
  39917. var vertexData = new BABYLON.VertexData();
  39918. vertexData.indices = [];
  39919. var indices = this.getIndices();
  39920. if (indices) {
  39921. for (var index = 0; index < indices.length; index++) {
  39922. vertexData.indices.push(indices[index]);
  39923. }
  39924. }
  39925. var updatable = false;
  39926. var stopChecking = false;
  39927. var kind;
  39928. for (kind in this._vertexBuffers) {
  39929. // using slice() to make a copy of the array and not just reference it
  39930. var data = this.getVerticesData(kind);
  39931. if (data instanceof Float32Array) {
  39932. vertexData.set(new Float32Array(data), kind);
  39933. }
  39934. else {
  39935. vertexData.set(data.slice(0), kind);
  39936. }
  39937. if (!stopChecking) {
  39938. var vb = this.getVertexBuffer(kind);
  39939. if (vb) {
  39940. updatable = vb.isUpdatable();
  39941. stopChecking = !updatable;
  39942. }
  39943. }
  39944. }
  39945. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39946. geometry.delayLoadState = this.delayLoadState;
  39947. geometry.delayLoadingFile = this.delayLoadingFile;
  39948. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39949. for (kind in this._delayInfo) {
  39950. geometry._delayInfo = geometry._delayInfo || [];
  39951. geometry._delayInfo.push(kind);
  39952. }
  39953. // Bounding info
  39954. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39955. return geometry;
  39956. };
  39957. /**
  39958. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39959. * @return a JSON representation of the current geometry data (without the vertices data)
  39960. */
  39961. Geometry.prototype.serialize = function () {
  39962. var serializationObject = {};
  39963. serializationObject.id = this.id;
  39964. serializationObject.updatable = this._updatable;
  39965. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39966. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39967. }
  39968. return serializationObject;
  39969. };
  39970. Geometry.prototype.toNumberArray = function (origin) {
  39971. if (Array.isArray(origin)) {
  39972. return origin;
  39973. }
  39974. else {
  39975. return Array.prototype.slice.call(origin);
  39976. }
  39977. };
  39978. /**
  39979. * Serialize all vertices data into a JSON oject
  39980. * @returns a JSON representation of the current geometry data
  39981. */
  39982. Geometry.prototype.serializeVerticeData = function () {
  39983. var serializationObject = this.serialize();
  39984. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39985. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39986. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39987. serializationObject.positions._updatable = true;
  39988. }
  39989. }
  39990. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39991. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39992. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39993. serializationObject.normals._updatable = true;
  39994. }
  39995. }
  39996. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39997. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39998. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39999. serializationObject.tangets._updatable = true;
  40000. }
  40001. }
  40002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40003. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40004. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40005. serializationObject.uvs._updatable = true;
  40006. }
  40007. }
  40008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40009. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40010. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40011. serializationObject.uv2s._updatable = true;
  40012. }
  40013. }
  40014. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40015. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40016. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40017. serializationObject.uv3s._updatable = true;
  40018. }
  40019. }
  40020. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40021. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40022. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40023. serializationObject.uv4s._updatable = true;
  40024. }
  40025. }
  40026. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40027. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40028. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40029. serializationObject.uv5s._updatable = true;
  40030. }
  40031. }
  40032. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40033. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40034. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40035. serializationObject.uv6s._updatable = true;
  40036. }
  40037. }
  40038. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40039. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40040. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40041. serializationObject.colors._updatable = true;
  40042. }
  40043. }
  40044. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40045. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40046. serializationObject.matricesIndices._isExpanded = true;
  40047. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40048. serializationObject.matricesIndices._updatable = true;
  40049. }
  40050. }
  40051. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40052. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40053. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40054. serializationObject.matricesWeights._updatable = true;
  40055. }
  40056. }
  40057. serializationObject.indices = this.toNumberArray(this.getIndices());
  40058. return serializationObject;
  40059. };
  40060. // Statics
  40061. /**
  40062. * Extracts a clone of a mesh geometry
  40063. * @param mesh defines the source mesh
  40064. * @param id defines the unique ID of the new geometry object
  40065. * @returns the new geometry object
  40066. */
  40067. Geometry.ExtractFromMesh = function (mesh, id) {
  40068. var geometry = mesh._geometry;
  40069. if (!geometry) {
  40070. return null;
  40071. }
  40072. return geometry.copy(id);
  40073. };
  40074. /**
  40075. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40076. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40077. * Be aware Math.random() could cause collisions, but:
  40078. * "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"
  40079. * @returns a string containing a new GUID
  40080. */
  40081. Geometry.RandomId = function () {
  40082. return BABYLON.Tools.RandomId();
  40083. };
  40084. /** @hidden */
  40085. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40086. var scene = mesh.getScene();
  40087. // Geometry
  40088. var geometryId = parsedGeometry.geometryId;
  40089. if (geometryId) {
  40090. var geometry = scene.getGeometryByID(geometryId);
  40091. if (geometry) {
  40092. geometry.applyToMesh(mesh);
  40093. }
  40094. }
  40095. else if (parsedGeometry instanceof ArrayBuffer) {
  40096. var binaryInfo = mesh._binaryInfo;
  40097. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40098. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40099. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40100. }
  40101. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40102. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40103. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40104. }
  40105. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40106. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40107. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40108. }
  40109. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40110. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40111. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40112. }
  40113. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40114. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40115. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40116. }
  40117. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40118. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40119. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40120. }
  40121. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40122. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40123. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40124. }
  40125. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40126. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40127. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40128. }
  40129. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40130. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40131. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40132. }
  40133. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40134. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40135. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40136. }
  40137. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40138. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40140. }
  40141. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40142. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40143. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40144. }
  40145. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40146. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40147. mesh.setIndices(indicesData, null);
  40148. }
  40149. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40150. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40151. mesh.subMeshes = [];
  40152. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40153. var materialIndex = subMeshesData[(i * 5) + 0];
  40154. var verticesStart = subMeshesData[(i * 5) + 1];
  40155. var verticesCount = subMeshesData[(i * 5) + 2];
  40156. var indexStart = subMeshesData[(i * 5) + 3];
  40157. var indexCount = subMeshesData[(i * 5) + 4];
  40158. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40159. }
  40160. }
  40161. }
  40162. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40163. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40164. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40165. if (parsedGeometry.tangents) {
  40166. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40167. }
  40168. if (parsedGeometry.uvs) {
  40169. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40170. }
  40171. if (parsedGeometry.uvs2) {
  40172. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40173. }
  40174. if (parsedGeometry.uvs3) {
  40175. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40176. }
  40177. if (parsedGeometry.uvs4) {
  40178. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40179. }
  40180. if (parsedGeometry.uvs5) {
  40181. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40182. }
  40183. if (parsedGeometry.uvs6) {
  40184. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40185. }
  40186. if (parsedGeometry.colors) {
  40187. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40188. }
  40189. if (parsedGeometry.matricesIndices) {
  40190. if (!parsedGeometry.matricesIndices._isExpanded) {
  40191. var floatIndices = [];
  40192. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40193. var matricesIndex = parsedGeometry.matricesIndices[i];
  40194. floatIndices.push(matricesIndex & 0x000000FF);
  40195. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40196. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40197. floatIndices.push(matricesIndex >> 24);
  40198. }
  40199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40200. }
  40201. else {
  40202. delete parsedGeometry.matricesIndices._isExpanded;
  40203. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40204. }
  40205. }
  40206. if (parsedGeometry.matricesIndicesExtra) {
  40207. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40208. var floatIndices = [];
  40209. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40210. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40211. floatIndices.push(matricesIndex & 0x000000FF);
  40212. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40213. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40214. floatIndices.push(matricesIndex >> 24);
  40215. }
  40216. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40217. }
  40218. else {
  40219. delete parsedGeometry.matricesIndices._isExpanded;
  40220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40221. }
  40222. }
  40223. if (parsedGeometry.matricesWeights) {
  40224. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40225. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40226. }
  40227. if (parsedGeometry.matricesWeightsExtra) {
  40228. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40229. }
  40230. mesh.setIndices(parsedGeometry.indices, null);
  40231. }
  40232. // SubMeshes
  40233. if (parsedGeometry.subMeshes) {
  40234. mesh.subMeshes = [];
  40235. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40236. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40237. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40238. }
  40239. }
  40240. // Flat shading
  40241. if (mesh._shouldGenerateFlatShading) {
  40242. mesh.convertToFlatShadedMesh();
  40243. delete mesh._shouldGenerateFlatShading;
  40244. }
  40245. // Update
  40246. mesh.computeWorldMatrix(true);
  40247. // Octree
  40248. var sceneOctree = scene.selectionOctree;
  40249. if (sceneOctree !== undefined && sceneOctree !== null) {
  40250. sceneOctree.addMesh(mesh);
  40251. }
  40252. };
  40253. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40254. var epsilon = 1e-3;
  40255. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40256. return;
  40257. }
  40258. var noInfluenceBoneIndex = 0.0;
  40259. if (parsedGeometry.skeletonId > -1) {
  40260. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40261. if (!skeleton) {
  40262. return;
  40263. }
  40264. noInfluenceBoneIndex = skeleton.bones.length;
  40265. }
  40266. else {
  40267. return;
  40268. }
  40269. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40270. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40271. var matricesWeights = parsedGeometry.matricesWeights;
  40272. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40273. var influencers = parsedGeometry.numBoneInfluencer;
  40274. var size = matricesWeights.length;
  40275. for (var i = 0; i < size; i += 4) {
  40276. var weight = 0.0;
  40277. var firstZeroWeight = -1;
  40278. for (var j = 0; j < 4; j++) {
  40279. var w = matricesWeights[i + j];
  40280. weight += w;
  40281. if (w < epsilon && firstZeroWeight < 0) {
  40282. firstZeroWeight = j;
  40283. }
  40284. }
  40285. if (matricesWeightsExtra) {
  40286. for (var j = 0; j < 4; j++) {
  40287. var w = matricesWeightsExtra[i + j];
  40288. weight += w;
  40289. if (w < epsilon && firstZeroWeight < 0) {
  40290. firstZeroWeight = j + 4;
  40291. }
  40292. }
  40293. }
  40294. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40295. firstZeroWeight = influencers - 1;
  40296. }
  40297. if (weight > epsilon) {
  40298. var mweight = 1.0 / weight;
  40299. for (var j = 0; j < 4; j++) {
  40300. matricesWeights[i + j] *= mweight;
  40301. }
  40302. if (matricesWeightsExtra) {
  40303. for (var j = 0; j < 4; j++) {
  40304. matricesWeightsExtra[i + j] *= mweight;
  40305. }
  40306. }
  40307. }
  40308. else {
  40309. if (firstZeroWeight >= 4) {
  40310. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40311. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40312. }
  40313. else {
  40314. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40315. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40316. }
  40317. }
  40318. }
  40319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40320. if (parsedGeometry.matricesWeightsExtra) {
  40321. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40322. }
  40323. };
  40324. /**
  40325. * Create a new geometry from persisted data (Using .babylon file format)
  40326. * @param parsedVertexData defines the persisted data
  40327. * @param scene defines the hosting scene
  40328. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40329. * @returns the new geometry object
  40330. */
  40331. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40332. if (scene.getGeometryByID(parsedVertexData.id)) {
  40333. return null; // null since geometry could be something else than a box...
  40334. }
  40335. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40336. if (BABYLON.Tags) {
  40337. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40338. }
  40339. if (parsedVertexData.delayLoadingFile) {
  40340. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40341. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40342. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40343. geometry._delayInfo = [];
  40344. if (parsedVertexData.hasUVs) {
  40345. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40346. }
  40347. if (parsedVertexData.hasUVs2) {
  40348. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40349. }
  40350. if (parsedVertexData.hasUVs3) {
  40351. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40352. }
  40353. if (parsedVertexData.hasUVs4) {
  40354. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40355. }
  40356. if (parsedVertexData.hasUVs5) {
  40357. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40358. }
  40359. if (parsedVertexData.hasUVs6) {
  40360. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40361. }
  40362. if (parsedVertexData.hasColors) {
  40363. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40364. }
  40365. if (parsedVertexData.hasMatricesIndices) {
  40366. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40367. }
  40368. if (parsedVertexData.hasMatricesWeights) {
  40369. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40370. }
  40371. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40372. }
  40373. else {
  40374. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40375. }
  40376. scene.pushGeometry(geometry, true);
  40377. return geometry;
  40378. };
  40379. return Geometry;
  40380. }());
  40381. BABYLON.Geometry = Geometry;
  40382. // Primitives
  40383. /// Abstract class
  40384. /**
  40385. * Abstract class used to provide common services for all typed geometries
  40386. * @hidden
  40387. */
  40388. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40389. __extends(_PrimitiveGeometry, _super);
  40390. /**
  40391. * Creates a new typed geometry
  40392. * @param id defines the unique ID of the geometry
  40393. * @param scene defines the hosting scene
  40394. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40395. * @param mesh defines the hosting mesh (can be null)
  40396. */
  40397. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40398. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40399. if (mesh === void 0) { mesh = null; }
  40400. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40401. _this._canBeRegenerated = _canBeRegenerated;
  40402. _this._beingRegenerated = true;
  40403. _this.regenerate();
  40404. _this._beingRegenerated = false;
  40405. return _this;
  40406. }
  40407. /**
  40408. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40409. * @returns true if the geometry can be regenerated
  40410. */
  40411. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40412. return this._canBeRegenerated;
  40413. };
  40414. /**
  40415. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40416. */
  40417. _PrimitiveGeometry.prototype.regenerate = function () {
  40418. if (!this._canBeRegenerated) {
  40419. return;
  40420. }
  40421. this._beingRegenerated = true;
  40422. this.setAllVerticesData(this._regenerateVertexData(), false);
  40423. this._beingRegenerated = false;
  40424. };
  40425. /**
  40426. * Clone the geometry
  40427. * @param id defines the unique ID of the new geometry
  40428. * @returns the new geometry
  40429. */
  40430. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40431. return _super.prototype.copy.call(this, id);
  40432. };
  40433. // overrides
  40434. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40435. if (!this._beingRegenerated) {
  40436. return;
  40437. }
  40438. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40439. };
  40440. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40441. if (!this._beingRegenerated) {
  40442. return;
  40443. }
  40444. _super.prototype.setVerticesData.call(this, kind, data, false);
  40445. };
  40446. // to override
  40447. /** @hidden */
  40448. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40449. throw new Error("Abstract method");
  40450. };
  40451. _PrimitiveGeometry.prototype.copy = function (id) {
  40452. throw new Error("Must be overriden in sub-classes.");
  40453. };
  40454. _PrimitiveGeometry.prototype.serialize = function () {
  40455. var serializationObject = _super.prototype.serialize.call(this);
  40456. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40457. return serializationObject;
  40458. };
  40459. return _PrimitiveGeometry;
  40460. }(Geometry));
  40461. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40462. /**
  40463. * Creates a ribbon geometry
  40464. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40465. */
  40466. var RibbonGeometry = /** @class */ (function (_super) {
  40467. __extends(RibbonGeometry, _super);
  40468. /**
  40469. * Creates a ribbon geometry
  40470. * @param id defines the unique ID of the geometry
  40471. * @param scene defines the hosting scene
  40472. * @param pathArray defines the array of paths to use
  40473. * @param closeArray defines if the last path and the first path must be joined
  40474. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40475. * @param offset defines the offset between points
  40476. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40477. * @param mesh defines the hosting mesh (can be null)
  40478. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40479. */
  40480. function RibbonGeometry(id, scene,
  40481. /**
  40482. * Defines the array of paths to use
  40483. */
  40484. pathArray,
  40485. /**
  40486. * Defines if the last and first points of each path in your pathArray must be joined
  40487. */
  40488. closeArray,
  40489. /**
  40490. * Defines if the last and first points of each path in your pathArray must be joined
  40491. */
  40492. closePath,
  40493. /**
  40494. * Defines the offset between points
  40495. */
  40496. offset, canBeRegenerated, mesh,
  40497. /**
  40498. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40499. */
  40500. side) {
  40501. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40502. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40503. _this.pathArray = pathArray;
  40504. _this.closeArray = closeArray;
  40505. _this.closePath = closePath;
  40506. _this.offset = offset;
  40507. _this.side = side;
  40508. return _this;
  40509. }
  40510. /** @hidden */
  40511. RibbonGeometry.prototype._regenerateVertexData = function () {
  40512. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40513. };
  40514. RibbonGeometry.prototype.copy = function (id) {
  40515. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40516. };
  40517. return RibbonGeometry;
  40518. }(_PrimitiveGeometry));
  40519. BABYLON.RibbonGeometry = RibbonGeometry;
  40520. /**
  40521. * Creates a box geometry
  40522. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40523. */
  40524. var BoxGeometry = /** @class */ (function (_super) {
  40525. __extends(BoxGeometry, _super);
  40526. /**
  40527. * Creates a box geometry
  40528. * @param id defines the unique ID of the geometry
  40529. * @param scene defines the hosting scene
  40530. * @param size defines the zise of the box (width, height and depth are the same)
  40531. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40532. * @param mesh defines the hosting mesh (can be null)
  40533. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40534. */
  40535. function BoxGeometry(id, scene,
  40536. /**
  40537. * Defines the zise of the box (width, height and depth are the same)
  40538. */
  40539. size, canBeRegenerated, mesh,
  40540. /**
  40541. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40542. */
  40543. side) {
  40544. if (mesh === void 0) { mesh = null; }
  40545. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40546. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40547. _this.size = size;
  40548. _this.side = side;
  40549. return _this;
  40550. }
  40551. BoxGeometry.prototype._regenerateVertexData = function () {
  40552. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40553. };
  40554. BoxGeometry.prototype.copy = function (id) {
  40555. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40556. };
  40557. BoxGeometry.prototype.serialize = function () {
  40558. var serializationObject = _super.prototype.serialize.call(this);
  40559. serializationObject.size = this.size;
  40560. return serializationObject;
  40561. };
  40562. BoxGeometry.Parse = function (parsedBox, scene) {
  40563. if (scene.getGeometryByID(parsedBox.id)) {
  40564. return null; // null since geometry could be something else than a box...
  40565. }
  40566. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40567. if (BABYLON.Tags) {
  40568. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40569. }
  40570. scene.pushGeometry(box, true);
  40571. return box;
  40572. };
  40573. return BoxGeometry;
  40574. }(_PrimitiveGeometry));
  40575. BABYLON.BoxGeometry = BoxGeometry;
  40576. /**
  40577. * Creates a sphere geometry
  40578. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40579. */
  40580. var SphereGeometry = /** @class */ (function (_super) {
  40581. __extends(SphereGeometry, _super);
  40582. /**
  40583. * Create a new sphere geometry
  40584. * @param id defines the unique ID of the geometry
  40585. * @param scene defines the hosting scene
  40586. * @param segments defines the number of segments to use to create the sphere
  40587. * @param diameter defines the diameter of the sphere
  40588. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40589. * @param mesh defines the hosting mesh (can be null)
  40590. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40591. */
  40592. function SphereGeometry(id, scene,
  40593. /**
  40594. * Defines the number of segments to use to create the sphere
  40595. */
  40596. segments,
  40597. /**
  40598. * Defines the diameter of the sphere
  40599. */
  40600. diameter, canBeRegenerated, mesh,
  40601. /**
  40602. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40603. */
  40604. side) {
  40605. if (mesh === void 0) { mesh = null; }
  40606. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40607. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40608. _this.segments = segments;
  40609. _this.diameter = diameter;
  40610. _this.side = side;
  40611. return _this;
  40612. }
  40613. SphereGeometry.prototype._regenerateVertexData = function () {
  40614. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40615. };
  40616. SphereGeometry.prototype.copy = function (id) {
  40617. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40618. };
  40619. SphereGeometry.prototype.serialize = function () {
  40620. var serializationObject = _super.prototype.serialize.call(this);
  40621. serializationObject.segments = this.segments;
  40622. serializationObject.diameter = this.diameter;
  40623. return serializationObject;
  40624. };
  40625. SphereGeometry.Parse = function (parsedSphere, scene) {
  40626. if (scene.getGeometryByID(parsedSphere.id)) {
  40627. return null; // null since geometry could be something else than a sphere...
  40628. }
  40629. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40630. if (BABYLON.Tags) {
  40631. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40632. }
  40633. scene.pushGeometry(sphere, true);
  40634. return sphere;
  40635. };
  40636. return SphereGeometry;
  40637. }(_PrimitiveGeometry));
  40638. BABYLON.SphereGeometry = SphereGeometry;
  40639. /**
  40640. * Creates a disc geometry
  40641. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40642. */
  40643. var DiscGeometry = /** @class */ (function (_super) {
  40644. __extends(DiscGeometry, _super);
  40645. /**
  40646. * Creates a new disc geometry
  40647. * @param id defines the unique ID of the geometry
  40648. * @param scene defines the hosting scene
  40649. * @param radius defines the radius of the disc
  40650. * @param tessellation defines the tesselation factor to apply to the disc
  40651. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40652. * @param mesh defines the hosting mesh (can be null)
  40653. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40654. */
  40655. function DiscGeometry(id, scene,
  40656. /**
  40657. * Defines the radius of the disc
  40658. */
  40659. radius,
  40660. /**
  40661. * Defines the tesselation factor to apply to the disc
  40662. */
  40663. tessellation, canBeRegenerated, mesh,
  40664. /**
  40665. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40666. */
  40667. side) {
  40668. if (mesh === void 0) { mesh = null; }
  40669. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40670. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40671. _this.radius = radius;
  40672. _this.tessellation = tessellation;
  40673. _this.side = side;
  40674. return _this;
  40675. }
  40676. DiscGeometry.prototype._regenerateVertexData = function () {
  40677. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40678. };
  40679. DiscGeometry.prototype.copy = function (id) {
  40680. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40681. };
  40682. return DiscGeometry;
  40683. }(_PrimitiveGeometry));
  40684. BABYLON.DiscGeometry = DiscGeometry;
  40685. /**
  40686. * Creates a new cylinder geometry
  40687. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40688. */
  40689. var CylinderGeometry = /** @class */ (function (_super) {
  40690. __extends(CylinderGeometry, _super);
  40691. /**
  40692. * Creates a new cylinder geometry
  40693. * @param id defines the unique ID of the geometry
  40694. * @param scene defines the hosting scene
  40695. * @param height defines the height of the cylinder
  40696. * @param diameterTop defines the diameter of the cylinder's top cap
  40697. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40698. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40699. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40700. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40701. * @param mesh defines the hosting mesh (can be null)
  40702. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40703. */
  40704. function CylinderGeometry(id, scene,
  40705. /**
  40706. * Defines the height of the cylinder
  40707. */
  40708. height,
  40709. /**
  40710. * Defines the diameter of the cylinder's top cap
  40711. */
  40712. diameterTop,
  40713. /**
  40714. * Defines the diameter of the cylinder's bottom cap
  40715. */
  40716. diameterBottom,
  40717. /**
  40718. * Defines the tessellation factor to apply to the cylinder
  40719. */
  40720. tessellation,
  40721. /**
  40722. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40723. */
  40724. subdivisions, canBeRegenerated, mesh,
  40725. /**
  40726. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40727. */
  40728. side) {
  40729. if (subdivisions === void 0) { subdivisions = 1; }
  40730. if (mesh === void 0) { mesh = null; }
  40731. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40732. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40733. _this.height = height;
  40734. _this.diameterTop = diameterTop;
  40735. _this.diameterBottom = diameterBottom;
  40736. _this.tessellation = tessellation;
  40737. _this.subdivisions = subdivisions;
  40738. _this.side = side;
  40739. return _this;
  40740. }
  40741. CylinderGeometry.prototype._regenerateVertexData = function () {
  40742. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40743. };
  40744. CylinderGeometry.prototype.copy = function (id) {
  40745. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40746. };
  40747. CylinderGeometry.prototype.serialize = function () {
  40748. var serializationObject = _super.prototype.serialize.call(this);
  40749. serializationObject.height = this.height;
  40750. serializationObject.diameterTop = this.diameterTop;
  40751. serializationObject.diameterBottom = this.diameterBottom;
  40752. serializationObject.tessellation = this.tessellation;
  40753. return serializationObject;
  40754. };
  40755. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40756. if (scene.getGeometryByID(parsedCylinder.id)) {
  40757. return null; // null since geometry could be something else than a cylinder...
  40758. }
  40759. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40760. if (BABYLON.Tags) {
  40761. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40762. }
  40763. scene.pushGeometry(cylinder, true);
  40764. return cylinder;
  40765. };
  40766. return CylinderGeometry;
  40767. }(_PrimitiveGeometry));
  40768. BABYLON.CylinderGeometry = CylinderGeometry;
  40769. /**
  40770. * Creates a new torus geometry
  40771. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40772. */
  40773. var TorusGeometry = /** @class */ (function (_super) {
  40774. __extends(TorusGeometry, _super);
  40775. /**
  40776. * Creates a new torus geometry
  40777. * @param id defines the unique ID of the geometry
  40778. * @param scene defines the hosting scene
  40779. * @param diameter defines the diameter of the torus
  40780. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40781. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40782. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40783. * @param mesh defines the hosting mesh (can be null)
  40784. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40785. */
  40786. function TorusGeometry(id, scene,
  40787. /**
  40788. * Defines the diameter of the torus
  40789. */
  40790. diameter,
  40791. /**
  40792. * Defines the thickness of the torus (ie. internal diameter)
  40793. */
  40794. thickness,
  40795. /**
  40796. * Defines the tesselation factor to apply to the torus
  40797. */
  40798. tessellation, canBeRegenerated, mesh,
  40799. /**
  40800. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40801. */
  40802. side) {
  40803. if (mesh === void 0) { mesh = null; }
  40804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40806. _this.diameter = diameter;
  40807. _this.thickness = thickness;
  40808. _this.tessellation = tessellation;
  40809. _this.side = side;
  40810. return _this;
  40811. }
  40812. TorusGeometry.prototype._regenerateVertexData = function () {
  40813. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40814. };
  40815. TorusGeometry.prototype.copy = function (id) {
  40816. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40817. };
  40818. TorusGeometry.prototype.serialize = function () {
  40819. var serializationObject = _super.prototype.serialize.call(this);
  40820. serializationObject.diameter = this.diameter;
  40821. serializationObject.thickness = this.thickness;
  40822. serializationObject.tessellation = this.tessellation;
  40823. return serializationObject;
  40824. };
  40825. TorusGeometry.Parse = function (parsedTorus, scene) {
  40826. if (scene.getGeometryByID(parsedTorus.id)) {
  40827. return null; // null since geometry could be something else than a torus...
  40828. }
  40829. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40830. if (BABYLON.Tags) {
  40831. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40832. }
  40833. scene.pushGeometry(torus, true);
  40834. return torus;
  40835. };
  40836. return TorusGeometry;
  40837. }(_PrimitiveGeometry));
  40838. BABYLON.TorusGeometry = TorusGeometry;
  40839. /**
  40840. * Creates a new ground geometry
  40841. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40842. */
  40843. var GroundGeometry = /** @class */ (function (_super) {
  40844. __extends(GroundGeometry, _super);
  40845. /**
  40846. * Creates a new ground geometry
  40847. * @param id defines the unique ID of the geometry
  40848. * @param scene defines the hosting scene
  40849. * @param width defines the width of the ground
  40850. * @param height defines the height of the ground
  40851. * @param subdivisions defines the subdivisions to apply to the ground
  40852. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40853. * @param mesh defines the hosting mesh (can be null)
  40854. */
  40855. function GroundGeometry(id, scene,
  40856. /**
  40857. * Defines the width of the ground
  40858. */
  40859. width,
  40860. /**
  40861. * Defines the height of the ground
  40862. */
  40863. height,
  40864. /**
  40865. * Defines the subdivisions to apply to the ground
  40866. */
  40867. subdivisions, canBeRegenerated, mesh) {
  40868. if (mesh === void 0) { mesh = null; }
  40869. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40870. _this.width = width;
  40871. _this.height = height;
  40872. _this.subdivisions = subdivisions;
  40873. return _this;
  40874. }
  40875. GroundGeometry.prototype._regenerateVertexData = function () {
  40876. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40877. };
  40878. GroundGeometry.prototype.copy = function (id) {
  40879. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40880. };
  40881. GroundGeometry.prototype.serialize = function () {
  40882. var serializationObject = _super.prototype.serialize.call(this);
  40883. serializationObject.width = this.width;
  40884. serializationObject.height = this.height;
  40885. serializationObject.subdivisions = this.subdivisions;
  40886. return serializationObject;
  40887. };
  40888. GroundGeometry.Parse = function (parsedGround, scene) {
  40889. if (scene.getGeometryByID(parsedGround.id)) {
  40890. return null; // null since geometry could be something else than a ground...
  40891. }
  40892. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40893. if (BABYLON.Tags) {
  40894. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40895. }
  40896. scene.pushGeometry(ground, true);
  40897. return ground;
  40898. };
  40899. return GroundGeometry;
  40900. }(_PrimitiveGeometry));
  40901. BABYLON.GroundGeometry = GroundGeometry;
  40902. /**
  40903. * Creates a tiled ground geometry
  40904. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40905. */
  40906. var TiledGroundGeometry = /** @class */ (function (_super) {
  40907. __extends(TiledGroundGeometry, _super);
  40908. /**
  40909. * Creates a tiled ground geometry
  40910. * @param id defines the unique ID of the geometry
  40911. * @param scene defines the hosting scene
  40912. * @param xmin defines the minimum value on X axis
  40913. * @param zmin defines the minimum value on Z axis
  40914. * @param xmax defines the maximum value on X axis
  40915. * @param zmax defines the maximum value on Z axis
  40916. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40917. * @param precision defines the precision to use when computing the tiles
  40918. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40919. * @param mesh defines the hosting mesh (can be null)
  40920. */
  40921. function TiledGroundGeometry(id, scene,
  40922. /**
  40923. * Defines the minimum value on X axis
  40924. */
  40925. xmin,
  40926. /**
  40927. * Defines the minimum value on Z axis
  40928. */
  40929. zmin,
  40930. /**
  40931. * Defines the maximum value on X axis
  40932. */
  40933. xmax,
  40934. /**
  40935. * Defines the maximum value on Z axis
  40936. */
  40937. zmax,
  40938. /**
  40939. * Defines the subdivisions to apply to the ground
  40940. */
  40941. subdivisions,
  40942. /**
  40943. * Defines the precision to use when computing the tiles
  40944. */
  40945. precision, canBeRegenerated, mesh) {
  40946. if (mesh === void 0) { mesh = null; }
  40947. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40948. _this.xmin = xmin;
  40949. _this.zmin = zmin;
  40950. _this.xmax = xmax;
  40951. _this.zmax = zmax;
  40952. _this.subdivisions = subdivisions;
  40953. _this.precision = precision;
  40954. return _this;
  40955. }
  40956. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40957. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40958. };
  40959. TiledGroundGeometry.prototype.copy = function (id) {
  40960. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40961. };
  40962. return TiledGroundGeometry;
  40963. }(_PrimitiveGeometry));
  40964. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40965. /**
  40966. * Creates a plane geometry
  40967. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40968. */
  40969. var PlaneGeometry = /** @class */ (function (_super) {
  40970. __extends(PlaneGeometry, _super);
  40971. /**
  40972. * Creates a plane geometry
  40973. * @param id defines the unique ID of the geometry
  40974. * @param scene defines the hosting scene
  40975. * @param size defines the size of the plane (width === height)
  40976. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40977. * @param mesh defines the hosting mesh (can be null)
  40978. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40979. */
  40980. function PlaneGeometry(id, scene,
  40981. /**
  40982. * Defines the size of the plane (width === height)
  40983. */
  40984. size, canBeRegenerated, mesh,
  40985. /**
  40986. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40987. */
  40988. side) {
  40989. if (mesh === void 0) { mesh = null; }
  40990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40992. _this.size = size;
  40993. _this.side = side;
  40994. return _this;
  40995. }
  40996. PlaneGeometry.prototype._regenerateVertexData = function () {
  40997. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40998. };
  40999. PlaneGeometry.prototype.copy = function (id) {
  41000. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41001. };
  41002. PlaneGeometry.prototype.serialize = function () {
  41003. var serializationObject = _super.prototype.serialize.call(this);
  41004. serializationObject.size = this.size;
  41005. return serializationObject;
  41006. };
  41007. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41008. if (scene.getGeometryByID(parsedPlane.id)) {
  41009. return null; // null since geometry could be something else than a ground...
  41010. }
  41011. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41012. if (BABYLON.Tags) {
  41013. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41014. }
  41015. scene.pushGeometry(plane, true);
  41016. return plane;
  41017. };
  41018. return PlaneGeometry;
  41019. }(_PrimitiveGeometry));
  41020. BABYLON.PlaneGeometry = PlaneGeometry;
  41021. /**
  41022. * Creates a torus knot geometry
  41023. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41024. */
  41025. var TorusKnotGeometry = /** @class */ (function (_super) {
  41026. __extends(TorusKnotGeometry, _super);
  41027. /**
  41028. * Creates a torus knot geometry
  41029. * @param id defines the unique ID of the geometry
  41030. * @param scene defines the hosting scene
  41031. * @param radius defines the radius of the torus knot
  41032. * @param tube defines the thickness of the torus knot tube
  41033. * @param radialSegments defines the number of radial segments
  41034. * @param tubularSegments defines the number of tubular segments
  41035. * @param p defines the first number of windings
  41036. * @param q defines the second number of windings
  41037. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41038. * @param mesh defines the hosting mesh (can be null)
  41039. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41040. */
  41041. function TorusKnotGeometry(id, scene,
  41042. /**
  41043. * Defines the radius of the torus knot
  41044. */
  41045. radius,
  41046. /**
  41047. * Defines the thickness of the torus knot tube
  41048. */
  41049. tube,
  41050. /**
  41051. * Defines the number of radial segments
  41052. */
  41053. radialSegments,
  41054. /**
  41055. * Defines the number of tubular segments
  41056. */
  41057. tubularSegments,
  41058. /**
  41059. * Defines the first number of windings
  41060. */
  41061. p,
  41062. /**
  41063. * Defines the second number of windings
  41064. */
  41065. q, canBeRegenerated, mesh,
  41066. /**
  41067. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41068. */
  41069. side) {
  41070. if (mesh === void 0) { mesh = null; }
  41071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41073. _this.radius = radius;
  41074. _this.tube = tube;
  41075. _this.radialSegments = radialSegments;
  41076. _this.tubularSegments = tubularSegments;
  41077. _this.p = p;
  41078. _this.q = q;
  41079. _this.side = side;
  41080. return _this;
  41081. }
  41082. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41083. 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 });
  41084. };
  41085. TorusKnotGeometry.prototype.copy = function (id) {
  41086. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41087. };
  41088. TorusKnotGeometry.prototype.serialize = function () {
  41089. var serializationObject = _super.prototype.serialize.call(this);
  41090. serializationObject.radius = this.radius;
  41091. serializationObject.tube = this.tube;
  41092. serializationObject.radialSegments = this.radialSegments;
  41093. serializationObject.tubularSegments = this.tubularSegments;
  41094. serializationObject.p = this.p;
  41095. serializationObject.q = this.q;
  41096. return serializationObject;
  41097. };
  41098. ;
  41099. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41100. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41101. return null; // null since geometry could be something else than a ground...
  41102. }
  41103. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41104. if (BABYLON.Tags) {
  41105. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41106. }
  41107. scene.pushGeometry(torusKnot, true);
  41108. return torusKnot;
  41109. };
  41110. return TorusKnotGeometry;
  41111. }(_PrimitiveGeometry));
  41112. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41113. //}
  41114. })(BABYLON || (BABYLON = {}));
  41115. //# sourceMappingURL=babylon.geometry.js.map
  41116. var BABYLON;
  41117. (function (BABYLON) {
  41118. /**
  41119. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41120. */
  41121. var PerformanceMonitor = /** @class */ (function () {
  41122. /**
  41123. * constructor
  41124. * @param frameSampleSize The number of samples required to saturate the sliding window
  41125. */
  41126. function PerformanceMonitor(frameSampleSize) {
  41127. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41128. this._enabled = true;
  41129. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41130. }
  41131. /**
  41132. * Samples current frame
  41133. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41134. */
  41135. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41136. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41137. if (!this._enabled)
  41138. return;
  41139. if (this._lastFrameTimeMs != null) {
  41140. var dt = timeMs - this._lastFrameTimeMs;
  41141. this._rollingFrameTime.add(dt);
  41142. }
  41143. this._lastFrameTimeMs = timeMs;
  41144. };
  41145. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41146. /**
  41147. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41148. * @return Average frame time in milliseconds
  41149. */
  41150. get: function () {
  41151. return this._rollingFrameTime.average;
  41152. },
  41153. enumerable: true,
  41154. configurable: true
  41155. });
  41156. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41157. /**
  41158. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41159. * @return Frame time variance in milliseconds squared
  41160. */
  41161. get: function () {
  41162. return this._rollingFrameTime.variance;
  41163. },
  41164. enumerable: true,
  41165. configurable: true
  41166. });
  41167. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41168. /**
  41169. * Returns the frame time of the most recent frame
  41170. * @return Frame time in milliseconds
  41171. */
  41172. get: function () {
  41173. return this._rollingFrameTime.history(0);
  41174. },
  41175. enumerable: true,
  41176. configurable: true
  41177. });
  41178. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41179. /**
  41180. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41181. * @return Framerate in frames per second
  41182. */
  41183. get: function () {
  41184. return 1000.0 / this._rollingFrameTime.average;
  41185. },
  41186. enumerable: true,
  41187. configurable: true
  41188. });
  41189. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41190. /**
  41191. * Returns the average framerate in frames per second using the most recent frame time
  41192. * @return Framerate in frames per second
  41193. */
  41194. get: function () {
  41195. var history = this._rollingFrameTime.history(0);
  41196. if (history === 0) {
  41197. return 0;
  41198. }
  41199. return 1000.0 / history;
  41200. },
  41201. enumerable: true,
  41202. configurable: true
  41203. });
  41204. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41205. /**
  41206. * Returns true if enough samples have been taken to completely fill the sliding window
  41207. * @return true if saturated
  41208. */
  41209. get: function () {
  41210. return this._rollingFrameTime.isSaturated();
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. /**
  41216. * Enables contributions to the sliding window sample set
  41217. */
  41218. PerformanceMonitor.prototype.enable = function () {
  41219. this._enabled = true;
  41220. };
  41221. /**
  41222. * Disables contributions to the sliding window sample set
  41223. * Samples will not be interpolated over the disabled period
  41224. */
  41225. PerformanceMonitor.prototype.disable = function () {
  41226. this._enabled = false;
  41227. //clear last sample to avoid interpolating over the disabled period when next enabled
  41228. this._lastFrameTimeMs = null;
  41229. };
  41230. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41231. /**
  41232. * Returns true if sampling is enabled
  41233. * @return true if enabled
  41234. */
  41235. get: function () {
  41236. return this._enabled;
  41237. },
  41238. enumerable: true,
  41239. configurable: true
  41240. });
  41241. /**
  41242. * Resets performance monitor
  41243. */
  41244. PerformanceMonitor.prototype.reset = function () {
  41245. //clear last sample to avoid interpolating over the disabled period when next enabled
  41246. this._lastFrameTimeMs = null;
  41247. //wipe record
  41248. this._rollingFrameTime.reset();
  41249. };
  41250. return PerformanceMonitor;
  41251. }());
  41252. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41253. /**
  41254. * RollingAverage
  41255. *
  41256. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41257. */
  41258. var RollingAverage = /** @class */ (function () {
  41259. /**
  41260. * constructor
  41261. * @param length The number of samples required to saturate the sliding window
  41262. */
  41263. function RollingAverage(length) {
  41264. this._samples = new Array(length);
  41265. this.reset();
  41266. }
  41267. /**
  41268. * Adds a sample to the sample set
  41269. * @param v The sample value
  41270. */
  41271. RollingAverage.prototype.add = function (v) {
  41272. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41273. var delta;
  41274. //we need to check if we've already wrapped round
  41275. if (this.isSaturated()) {
  41276. //remove bottom of stack from mean
  41277. var bottomValue = this._samples[this._pos];
  41278. delta = bottomValue - this.average;
  41279. this.average -= delta / (this._sampleCount - 1);
  41280. this._m2 -= delta * (bottomValue - this.average);
  41281. }
  41282. else {
  41283. this._sampleCount++;
  41284. }
  41285. //add new value to mean
  41286. delta = v - this.average;
  41287. this.average += delta / (this._sampleCount);
  41288. this._m2 += delta * (v - this.average);
  41289. //set the new variance
  41290. this.variance = this._m2 / (this._sampleCount - 1);
  41291. this._samples[this._pos] = v;
  41292. this._pos++;
  41293. this._pos %= this._samples.length; //positive wrap around
  41294. };
  41295. /**
  41296. * Returns previously added values or null if outside of history or outside the sliding window domain
  41297. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41298. * @return Value previously recorded with add() or null if outside of range
  41299. */
  41300. RollingAverage.prototype.history = function (i) {
  41301. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41302. return 0;
  41303. }
  41304. var i0 = this._wrapPosition(this._pos - 1.0);
  41305. return this._samples[this._wrapPosition(i0 - i)];
  41306. };
  41307. /**
  41308. * Returns true if enough samples have been taken to completely fill the sliding window
  41309. * @return true if sample-set saturated
  41310. */
  41311. RollingAverage.prototype.isSaturated = function () {
  41312. return this._sampleCount >= this._samples.length;
  41313. };
  41314. /**
  41315. * Resets the rolling average (equivalent to 0 samples taken so far)
  41316. */
  41317. RollingAverage.prototype.reset = function () {
  41318. this.average = 0;
  41319. this.variance = 0;
  41320. this._sampleCount = 0;
  41321. this._pos = 0;
  41322. this._m2 = 0;
  41323. };
  41324. /**
  41325. * Wraps a value around the sample range boundaries
  41326. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41327. * @return Wrapped position in sample range
  41328. */
  41329. RollingAverage.prototype._wrapPosition = function (i) {
  41330. var max = this._samples.length;
  41331. return ((i % max) + max) % max;
  41332. };
  41333. return RollingAverage;
  41334. }());
  41335. BABYLON.RollingAverage = RollingAverage;
  41336. })(BABYLON || (BABYLON = {}));
  41337. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41338. var BABYLON;
  41339. (function (BABYLON) {
  41340. /**
  41341. * "Static Class" containing the most commonly used helper while dealing with material for
  41342. * rendering purpose.
  41343. *
  41344. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41345. *
  41346. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41347. */
  41348. var MaterialHelper = /** @class */ (function () {
  41349. function MaterialHelper() {
  41350. }
  41351. /**
  41352. * Bind the current view position to an effect.
  41353. * @param effect The effect to be bound
  41354. * @param scene The scene the eyes position is used from
  41355. */
  41356. MaterialHelper.BindEyePosition = function (effect, scene) {
  41357. if (scene._forcedViewPosition) {
  41358. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41359. return;
  41360. }
  41361. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41362. };
  41363. /**
  41364. * Helps preparing the defines values about the UVs in used in the effect.
  41365. * UVs are shared as much as we can accross chanels in the shaders.
  41366. * @param texture The texture we are preparing the UVs for
  41367. * @param defines The defines to update
  41368. * @param key The chanel key "diffuse", "specular"... used in the shader
  41369. */
  41370. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41371. defines._needUVs = true;
  41372. defines[key] = true;
  41373. if (texture.getTextureMatrix().isIdentity(true)) {
  41374. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41375. if (texture.coordinatesIndex === 0) {
  41376. defines["MAINUV1"] = true;
  41377. }
  41378. else {
  41379. defines["MAINUV2"] = true;
  41380. }
  41381. }
  41382. else {
  41383. defines[key + "DIRECTUV"] = 0;
  41384. }
  41385. };
  41386. /**
  41387. * Binds a texture matrix value to its corrsponding uniform
  41388. * @param texture The texture to bind the matrix for
  41389. * @param uniformBuffer The uniform buffer receivin the data
  41390. * @param key The chanel key "diffuse", "specular"... used in the shader
  41391. */
  41392. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41393. var matrix = texture.getTextureMatrix();
  41394. if (!matrix.isIdentity(true)) {
  41395. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41396. }
  41397. };
  41398. /**
  41399. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41400. * @param mesh defines the current mesh
  41401. * @param scene defines the current scene
  41402. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41403. * @param pointsCloud defines if point cloud rendering has to be turned on
  41404. * @param fogEnabled defines if fog has to be turned on
  41405. * @param alphaTest defines if alpha testing has to be turned on
  41406. * @param defines defines the current list of defines
  41407. */
  41408. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41409. if (defines._areMiscDirty) {
  41410. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41411. defines["POINTSIZE"] = pointsCloud;
  41412. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41413. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41414. defines["ALPHATEST"] = alphaTest;
  41415. }
  41416. };
  41417. /**
  41418. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41419. * @param scene defines the current scene
  41420. * @param engine defines the current engine
  41421. * @param defines specifies the list of active defines
  41422. * @param useInstances defines if instances have to be turned on
  41423. * @param useClipPlane defines if clip plane have to be turned on
  41424. */
  41425. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41426. if (useClipPlane === void 0) { useClipPlane = null; }
  41427. var changed = false;
  41428. if (useClipPlane == null) {
  41429. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41430. }
  41431. if (defines["CLIPPLANE"] !== useClipPlane) {
  41432. defines["CLIPPLANE"] = useClipPlane;
  41433. changed = true;
  41434. }
  41435. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41436. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41437. changed = true;
  41438. }
  41439. if (defines["INSTANCES"] !== useInstances) {
  41440. defines["INSTANCES"] = useInstances;
  41441. changed = true;
  41442. }
  41443. if (changed) {
  41444. defines.markAsUnprocessed();
  41445. }
  41446. };
  41447. /**
  41448. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41449. * @param mesh The mesh containing the geometry data we will draw
  41450. * @param defines The defines to update
  41451. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41452. * @param useBones Precise whether bones should be used or not (override mesh info)
  41453. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41454. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41455. * @returns false if defines are considered not dirty and have not been checked
  41456. */
  41457. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41458. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41459. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41460. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41461. return false;
  41462. }
  41463. defines._normals = defines._needNormals;
  41464. defines._uvs = defines._needUVs;
  41465. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41466. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41467. defines["TANGENT"] = true;
  41468. }
  41469. if (defines._needUVs) {
  41470. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41471. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41472. }
  41473. else {
  41474. defines["UV1"] = false;
  41475. defines["UV2"] = false;
  41476. }
  41477. if (useVertexColor) {
  41478. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41479. defines["VERTEXCOLOR"] = hasVertexColors;
  41480. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41481. }
  41482. if (useBones) {
  41483. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41484. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41485. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41486. }
  41487. else {
  41488. defines["NUM_BONE_INFLUENCERS"] = 0;
  41489. defines["BonesPerMesh"] = 0;
  41490. }
  41491. }
  41492. if (useMorphTargets) {
  41493. var manager = mesh.morphTargetManager;
  41494. if (manager) {
  41495. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41496. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41497. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41498. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41499. }
  41500. else {
  41501. defines["MORPHTARGETS_TANGENT"] = false;
  41502. defines["MORPHTARGETS_NORMAL"] = false;
  41503. defines["MORPHTARGETS"] = false;
  41504. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41505. }
  41506. }
  41507. return true;
  41508. };
  41509. /**
  41510. * Prepares the defines related to the light information passed in parameter
  41511. * @param scene The scene we are intending to draw
  41512. * @param mesh The mesh the effect is compiling for
  41513. * @param defines The defines to update
  41514. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41515. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41516. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41517. * @returns true if normals will be required for the rest of the effect
  41518. */
  41519. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41520. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41521. if (disableLighting === void 0) { disableLighting = false; }
  41522. if (!defines._areLightsDirty) {
  41523. return defines._needNormals;
  41524. }
  41525. var lightIndex = 0;
  41526. var needNormals = false;
  41527. var needRebuild = false;
  41528. var lightmapMode = false;
  41529. var shadowEnabled = false;
  41530. var specularEnabled = false;
  41531. if (scene.lightsEnabled && !disableLighting) {
  41532. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41533. var light = _a[_i];
  41534. needNormals = true;
  41535. if (defines["LIGHT" + lightIndex] === undefined) {
  41536. needRebuild = true;
  41537. }
  41538. defines["LIGHT" + lightIndex] = true;
  41539. defines["SPOTLIGHT" + lightIndex] = false;
  41540. defines["HEMILIGHT" + lightIndex] = false;
  41541. defines["POINTLIGHT" + lightIndex] = false;
  41542. defines["DIRLIGHT" + lightIndex] = false;
  41543. var type;
  41544. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41545. type = "SPOTLIGHT" + lightIndex;
  41546. var spotLight = light;
  41547. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41548. }
  41549. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41550. type = "HEMILIGHT" + lightIndex;
  41551. }
  41552. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41553. type = "POINTLIGHT" + lightIndex;
  41554. }
  41555. else {
  41556. type = "DIRLIGHT" + lightIndex;
  41557. }
  41558. defines[type] = true;
  41559. // Specular
  41560. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41561. specularEnabled = true;
  41562. }
  41563. // Shadows
  41564. defines["SHADOW" + lightIndex] = false;
  41565. defines["SHADOWPCF" + lightIndex] = false;
  41566. defines["SHADOWPCSS" + lightIndex] = false;
  41567. defines["SHADOWPOISSON" + lightIndex] = false;
  41568. defines["SHADOWESM" + lightIndex] = false;
  41569. defines["SHADOWCUBE" + lightIndex] = false;
  41570. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41571. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41572. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41573. var shadowGenerator = light.getShadowGenerator();
  41574. if (shadowGenerator) {
  41575. shadowEnabled = true;
  41576. shadowGenerator.prepareDefines(defines, lightIndex);
  41577. }
  41578. }
  41579. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41580. lightmapMode = true;
  41581. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41582. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41583. }
  41584. else {
  41585. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41586. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41587. }
  41588. lightIndex++;
  41589. if (lightIndex === maxSimultaneousLights)
  41590. break;
  41591. }
  41592. }
  41593. defines["SPECULARTERM"] = specularEnabled;
  41594. defines["SHADOWS"] = shadowEnabled;
  41595. // Resetting all other lights if any
  41596. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41597. if (defines["LIGHT" + index] !== undefined) {
  41598. defines["LIGHT" + index] = false;
  41599. defines["HEMILIGHT" + lightIndex] = false;
  41600. defines["POINTLIGHT" + lightIndex] = false;
  41601. defines["DIRLIGHT" + lightIndex] = false;
  41602. defines["SPOTLIGHT" + lightIndex] = false;
  41603. defines["SHADOW" + lightIndex] = false;
  41604. }
  41605. }
  41606. var caps = scene.getEngine().getCaps();
  41607. if (defines["SHADOWFLOAT"] === undefined) {
  41608. needRebuild = true;
  41609. }
  41610. defines["SHADOWFLOAT"] = shadowEnabled &&
  41611. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41612. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41613. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41614. if (needRebuild) {
  41615. defines.rebuild();
  41616. }
  41617. return needNormals;
  41618. };
  41619. /**
  41620. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41621. * that won t be acctive due to defines being turned off.
  41622. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41623. * @param samplersList The samplers list
  41624. * @param defines The defines helping in the list generation
  41625. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41626. */
  41627. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41628. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41629. var uniformsList;
  41630. var uniformBuffersList = null;
  41631. if (uniformsListOrOptions.uniformsNames) {
  41632. var options = uniformsListOrOptions;
  41633. uniformsList = options.uniformsNames;
  41634. uniformBuffersList = options.uniformBuffersNames;
  41635. samplersList = options.samplers;
  41636. defines = options.defines;
  41637. maxSimultaneousLights = options.maxSimultaneousLights;
  41638. }
  41639. else {
  41640. uniformsList = uniformsListOrOptions;
  41641. if (!samplersList) {
  41642. samplersList = [];
  41643. }
  41644. }
  41645. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41646. if (!defines["LIGHT" + lightIndex]) {
  41647. break;
  41648. }
  41649. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41650. if (uniformBuffersList) {
  41651. uniformBuffersList.push("Light" + lightIndex);
  41652. }
  41653. samplersList.push("shadowSampler" + lightIndex);
  41654. samplersList.push("depthSampler" + lightIndex);
  41655. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41656. samplersList.push("projectionLightSampler" + lightIndex);
  41657. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41658. }
  41659. }
  41660. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41661. uniformsList.push("morphTargetInfluences");
  41662. }
  41663. };
  41664. /**
  41665. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41666. * @param defines The defines to update while falling back
  41667. * @param fallbacks The authorized effect fallbacks
  41668. * @param maxSimultaneousLights The maximum number of lights allowed
  41669. * @param rank the current rank of the Effect
  41670. * @returns The newly affected rank
  41671. */
  41672. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41673. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41674. if (rank === void 0) { rank = 0; }
  41675. var lightFallbackRank = 0;
  41676. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41677. if (!defines["LIGHT" + lightIndex]) {
  41678. break;
  41679. }
  41680. if (lightIndex > 0) {
  41681. lightFallbackRank = rank + lightIndex;
  41682. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41683. }
  41684. if (!defines["SHADOWS"]) {
  41685. if (defines["SHADOW" + lightIndex]) {
  41686. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41687. }
  41688. if (defines["SHADOWPCF" + lightIndex]) {
  41689. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41690. }
  41691. if (defines["SHADOWPCSS" + lightIndex]) {
  41692. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41693. }
  41694. if (defines["SHADOWPOISSON" + lightIndex]) {
  41695. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41696. }
  41697. if (defines["SHADOWESM" + lightIndex]) {
  41698. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41699. }
  41700. }
  41701. }
  41702. return lightFallbackRank++;
  41703. };
  41704. /**
  41705. * Prepares the list of attributes required for morph targets according to the effect defines.
  41706. * @param attribs The current list of supported attribs
  41707. * @param mesh The mesh to prepare the morph targets attributes for
  41708. * @param defines The current Defines of the effect
  41709. */
  41710. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41711. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41712. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41713. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41714. var manager = mesh.morphTargetManager;
  41715. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41716. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41717. for (var index = 0; index < influencers; index++) {
  41718. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41719. if (normal) {
  41720. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41721. }
  41722. if (tangent) {
  41723. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41724. }
  41725. if (attribs.length > maxAttributesCount) {
  41726. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41727. }
  41728. }
  41729. }
  41730. };
  41731. /**
  41732. * Prepares the list of attributes required for bones according to the effect defines.
  41733. * @param attribs The current list of supported attribs
  41734. * @param mesh The mesh to prepare the bones attributes for
  41735. * @param defines The current Defines of the effect
  41736. * @param fallbacks The current efffect fallback strategy
  41737. */
  41738. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41739. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41740. fallbacks.addCPUSkinningFallback(0, mesh);
  41741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41743. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41746. }
  41747. }
  41748. };
  41749. /**
  41750. * Prepares the list of attributes required for instances according to the effect defines.
  41751. * @param attribs The current list of supported attribs
  41752. * @param defines The current Defines of the effect
  41753. */
  41754. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41755. if (defines["INSTANCES"]) {
  41756. attribs.push("world0");
  41757. attribs.push("world1");
  41758. attribs.push("world2");
  41759. attribs.push("world3");
  41760. }
  41761. };
  41762. /**
  41763. * Binds the light shadow information to the effect for the given mesh.
  41764. * @param light The light containing the generator
  41765. * @param scene The scene the lights belongs to
  41766. * @param mesh The mesh we are binding the information to render
  41767. * @param lightIndex The light index in the effect used to render the mesh
  41768. * @param effect The effect we are binding the data to
  41769. */
  41770. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41771. if (light.shadowEnabled && mesh.receiveShadows) {
  41772. var shadowGenerator = light.getShadowGenerator();
  41773. if (shadowGenerator) {
  41774. shadowGenerator.bindShadowLight(lightIndex, effect);
  41775. }
  41776. }
  41777. };
  41778. /**
  41779. * Binds the light information to the effect.
  41780. * @param light The light containing the generator
  41781. * @param effect The effect we are binding the data to
  41782. * @param lightIndex The light index in the effect used to render
  41783. */
  41784. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41785. light.transferToEffect(effect, lightIndex + "");
  41786. };
  41787. /**
  41788. * Binds the lights information from the scene to the effect for the given mesh.
  41789. * @param scene The scene the lights belongs to
  41790. * @param mesh The mesh we are binding the information to render
  41791. * @param effect The effect we are binding the data to
  41792. * @param defines The generated defines for the effect
  41793. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41794. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41795. */
  41796. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41797. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41798. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41799. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41800. for (var i = 0; i < len; i++) {
  41801. var light = mesh._lightSources[i];
  41802. var iAsString = i.toString();
  41803. var scaledIntensity = light.getScaledIntensity();
  41804. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41805. MaterialHelper.BindLightProperties(light, effect, i);
  41806. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41807. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41808. if (defines["SPECULARTERM"]) {
  41809. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41810. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41811. }
  41812. // Shadows
  41813. if (scene.shadowsEnabled) {
  41814. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41815. }
  41816. light._uniformBuffer.update();
  41817. }
  41818. };
  41819. /**
  41820. * Binds the fog information from the scene to the effect for the given mesh.
  41821. * @param scene The scene the lights belongs to
  41822. * @param mesh The mesh we are binding the information to render
  41823. * @param effect The effect we are binding the data to
  41824. */
  41825. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41826. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41827. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41828. effect.setColor3("vFogColor", scene.fogColor);
  41829. }
  41830. };
  41831. /**
  41832. * Binds the bones information from the mesh to the effect.
  41833. * @param mesh The mesh we are binding the information to render
  41834. * @param effect The effect we are binding the data to
  41835. */
  41836. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41837. if (!effect || !mesh) {
  41838. return;
  41839. }
  41840. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41841. mesh.computeBonesUsingShaders = false;
  41842. }
  41843. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41844. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41845. if (matrices) {
  41846. effect.setMatrices("mBones", matrices);
  41847. }
  41848. }
  41849. };
  41850. /**
  41851. * Binds the morph targets information from the mesh to the effect.
  41852. * @param abstractMesh The mesh we are binding the information to render
  41853. * @param effect The effect we are binding the data to
  41854. */
  41855. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41856. var manager = abstractMesh.morphTargetManager;
  41857. if (!abstractMesh || !manager) {
  41858. return;
  41859. }
  41860. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41861. };
  41862. /**
  41863. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41864. * @param defines The generated defines used in the effect
  41865. * @param effect The effect we are binding the data to
  41866. * @param scene The scene we are willing to render with logarithmic scale for
  41867. */
  41868. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41869. if (defines["LOGARITHMICDEPTH"]) {
  41870. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41871. }
  41872. };
  41873. /**
  41874. * Binds the clip plane information from the scene to the effect.
  41875. * @param scene The scene the clip plane information are extracted from
  41876. * @param effect The effect we are binding the data to
  41877. */
  41878. MaterialHelper.BindClipPlane = function (effect, scene) {
  41879. if (scene.clipPlane) {
  41880. var clipPlane = scene.clipPlane;
  41881. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41882. }
  41883. };
  41884. return MaterialHelper;
  41885. }());
  41886. BABYLON.MaterialHelper = MaterialHelper;
  41887. })(BABYLON || (BABYLON = {}));
  41888. //# sourceMappingURL=babylon.materialHelper.js.map
  41889. var BABYLON;
  41890. (function (BABYLON) {
  41891. var PushMaterial = /** @class */ (function (_super) {
  41892. __extends(PushMaterial, _super);
  41893. function PushMaterial(name, scene) {
  41894. var _this = _super.call(this, name, scene) || this;
  41895. _this._normalMatrix = new BABYLON.Matrix();
  41896. _this.storeEffectOnSubMeshes = true;
  41897. return _this;
  41898. }
  41899. PushMaterial.prototype.getEffect = function () {
  41900. return this._activeEffect;
  41901. };
  41902. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41903. if (!mesh) {
  41904. return false;
  41905. }
  41906. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41907. return true;
  41908. }
  41909. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41910. };
  41911. /**
  41912. * Binds the given world matrix to the active effect
  41913. *
  41914. * @param world the matrix to bind
  41915. */
  41916. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41917. this._activeEffect.setMatrix("world", world);
  41918. };
  41919. /**
  41920. * Binds the given normal matrix to the active effect
  41921. *
  41922. * @param normalMatrix the matrix to bind
  41923. */
  41924. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41925. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41926. };
  41927. PushMaterial.prototype.bind = function (world, mesh) {
  41928. if (!mesh) {
  41929. return;
  41930. }
  41931. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41932. };
  41933. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41934. if (effect === void 0) { effect = null; }
  41935. _super.prototype._afterBind.call(this, mesh);
  41936. this.getScene()._cachedEffect = effect;
  41937. };
  41938. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41939. if (visibility === void 0) { visibility = 1; }
  41940. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41941. };
  41942. return PushMaterial;
  41943. }(BABYLON.Material));
  41944. BABYLON.PushMaterial = PushMaterial;
  41945. })(BABYLON || (BABYLON = {}));
  41946. //# sourceMappingURL=babylon.pushMaterial.js.map
  41947. var BABYLON;
  41948. (function (BABYLON) {
  41949. /** @hidden */
  41950. var StandardMaterialDefines = /** @class */ (function (_super) {
  41951. __extends(StandardMaterialDefines, _super);
  41952. function StandardMaterialDefines() {
  41953. var _this = _super.call(this) || this;
  41954. _this.MAINUV1 = false;
  41955. _this.MAINUV2 = false;
  41956. _this.DIFFUSE = false;
  41957. _this.DIFFUSEDIRECTUV = 0;
  41958. _this.AMBIENT = false;
  41959. _this.AMBIENTDIRECTUV = 0;
  41960. _this.OPACITY = false;
  41961. _this.OPACITYDIRECTUV = 0;
  41962. _this.OPACITYRGB = false;
  41963. _this.REFLECTION = false;
  41964. _this.EMISSIVE = false;
  41965. _this.EMISSIVEDIRECTUV = 0;
  41966. _this.SPECULAR = false;
  41967. _this.SPECULARDIRECTUV = 0;
  41968. _this.BUMP = false;
  41969. _this.BUMPDIRECTUV = 0;
  41970. _this.PARALLAX = false;
  41971. _this.PARALLAXOCCLUSION = false;
  41972. _this.SPECULAROVERALPHA = false;
  41973. _this.CLIPPLANE = false;
  41974. _this.ALPHATEST = false;
  41975. _this.DEPTHPREPASS = false;
  41976. _this.ALPHAFROMDIFFUSE = false;
  41977. _this.POINTSIZE = false;
  41978. _this.FOG = false;
  41979. _this.SPECULARTERM = false;
  41980. _this.DIFFUSEFRESNEL = false;
  41981. _this.OPACITYFRESNEL = false;
  41982. _this.REFLECTIONFRESNEL = false;
  41983. _this.REFRACTIONFRESNEL = false;
  41984. _this.EMISSIVEFRESNEL = false;
  41985. _this.FRESNEL = false;
  41986. _this.NORMAL = false;
  41987. _this.UV1 = false;
  41988. _this.UV2 = false;
  41989. _this.VERTEXCOLOR = false;
  41990. _this.VERTEXALPHA = false;
  41991. _this.NUM_BONE_INFLUENCERS = 0;
  41992. _this.BonesPerMesh = 0;
  41993. _this.INSTANCES = false;
  41994. _this.GLOSSINESS = false;
  41995. _this.ROUGHNESS = false;
  41996. _this.EMISSIVEASILLUMINATION = false;
  41997. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41998. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41999. _this.LIGHTMAP = false;
  42000. _this.LIGHTMAPDIRECTUV = 0;
  42001. _this.OBJECTSPACE_NORMALMAP = false;
  42002. _this.USELIGHTMAPASSHADOWMAP = false;
  42003. _this.REFLECTIONMAP_3D = false;
  42004. _this.REFLECTIONMAP_SPHERICAL = false;
  42005. _this.REFLECTIONMAP_PLANAR = false;
  42006. _this.REFLECTIONMAP_CUBIC = false;
  42007. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42008. _this.REFLECTIONMAP_PROJECTION = false;
  42009. _this.REFLECTIONMAP_SKYBOX = false;
  42010. _this.REFLECTIONMAP_EXPLICIT = false;
  42011. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42012. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42013. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42014. _this.INVERTCUBICMAP = false;
  42015. _this.LOGARITHMICDEPTH = false;
  42016. _this.REFRACTION = false;
  42017. _this.REFRACTIONMAP_3D = false;
  42018. _this.REFLECTIONOVERALPHA = false;
  42019. _this.TWOSIDEDLIGHTING = false;
  42020. _this.SHADOWFLOAT = false;
  42021. _this.MORPHTARGETS = false;
  42022. _this.MORPHTARGETS_NORMAL = false;
  42023. _this.MORPHTARGETS_TANGENT = false;
  42024. _this.NUM_MORPH_INFLUENCERS = 0;
  42025. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42026. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42027. _this.IMAGEPROCESSING = false;
  42028. _this.VIGNETTE = false;
  42029. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42030. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42031. _this.TONEMAPPING = false;
  42032. _this.CONTRAST = false;
  42033. _this.COLORCURVES = false;
  42034. _this.COLORGRADING = false;
  42035. _this.COLORGRADING3D = false;
  42036. _this.SAMPLER3DGREENDEPTH = false;
  42037. _this.SAMPLER3DBGRMAP = false;
  42038. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42039. /**
  42040. * If the reflection texture on this material is in linear color space
  42041. * @hidden
  42042. */
  42043. _this.IS_REFLECTION_LINEAR = false;
  42044. /**
  42045. * If the refraction texture on this material is in linear color space
  42046. * @hidden
  42047. */
  42048. _this.IS_REFRACTION_LINEAR = false;
  42049. _this.EXPOSURE = false;
  42050. _this.rebuild();
  42051. return _this;
  42052. }
  42053. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42054. var modes = [
  42055. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42056. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42057. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42058. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42059. ];
  42060. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42061. var mode = modes_1[_i];
  42062. this[mode] = (mode === modeToEnable);
  42063. }
  42064. };
  42065. return StandardMaterialDefines;
  42066. }(BABYLON.MaterialDefines));
  42067. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42068. var StandardMaterial = /** @class */ (function (_super) {
  42069. __extends(StandardMaterial, _super);
  42070. function StandardMaterial(name, scene) {
  42071. var _this = _super.call(this, name, scene) || this;
  42072. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42073. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42074. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42075. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42076. _this.specularPower = 64;
  42077. _this._useAlphaFromDiffuseTexture = false;
  42078. _this._useEmissiveAsIllumination = false;
  42079. _this._linkEmissiveWithDiffuse = false;
  42080. _this._useSpecularOverAlpha = false;
  42081. _this._useReflectionOverAlpha = false;
  42082. _this._disableLighting = false;
  42083. _this._useObjectSpaceNormalMap = false;
  42084. _this._useParallax = false;
  42085. _this._useParallaxOcclusion = false;
  42086. _this.parallaxScaleBias = 0.05;
  42087. _this._roughness = 0;
  42088. _this.indexOfRefraction = 0.98;
  42089. _this.invertRefractionY = true;
  42090. /**
  42091. * Defines the alpha limits in alpha test mode
  42092. */
  42093. _this.alphaCutOff = 0.4;
  42094. _this._useLightmapAsShadowmap = false;
  42095. _this._useReflectionFresnelFromSpecular = false;
  42096. _this._useGlossinessFromSpecularMapAlpha = false;
  42097. _this._maxSimultaneousLights = 4;
  42098. /**
  42099. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42100. */
  42101. _this._invertNormalMapX = false;
  42102. /**
  42103. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42104. */
  42105. _this._invertNormalMapY = false;
  42106. /**
  42107. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42108. */
  42109. _this._twoSidedLighting = false;
  42110. _this._renderTargets = new BABYLON.SmartArray(16);
  42111. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42112. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42113. // Setup the default processing configuration to the scene.
  42114. _this._attachImageProcessingConfiguration(null);
  42115. _this.getRenderTargetTextures = function () {
  42116. _this._renderTargets.reset();
  42117. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42118. _this._renderTargets.push(_this._reflectionTexture);
  42119. }
  42120. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42121. _this._renderTargets.push(_this._refractionTexture);
  42122. }
  42123. return _this._renderTargets;
  42124. };
  42125. return _this;
  42126. }
  42127. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42128. /**
  42129. * Gets the image processing configuration used either in this material.
  42130. */
  42131. get: function () {
  42132. return this._imageProcessingConfiguration;
  42133. },
  42134. /**
  42135. * Sets the Default image processing configuration used either in the this material.
  42136. *
  42137. * If sets to null, the scene one is in use.
  42138. */
  42139. set: function (value) {
  42140. this._attachImageProcessingConfiguration(value);
  42141. // Ensure the effect will be rebuilt.
  42142. this._markAllSubMeshesAsTexturesDirty();
  42143. },
  42144. enumerable: true,
  42145. configurable: true
  42146. });
  42147. /**
  42148. * Attaches a new image processing configuration to the Standard Material.
  42149. * @param configuration
  42150. */
  42151. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42152. var _this = this;
  42153. if (configuration === this._imageProcessingConfiguration) {
  42154. return;
  42155. }
  42156. // Detaches observer.
  42157. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42158. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42159. }
  42160. // Pick the scene configuration if needed.
  42161. if (!configuration) {
  42162. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42163. }
  42164. else {
  42165. this._imageProcessingConfiguration = configuration;
  42166. }
  42167. // Attaches observer.
  42168. if (this._imageProcessingConfiguration) {
  42169. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42170. _this._markAllSubMeshesAsImageProcessingDirty();
  42171. });
  42172. }
  42173. };
  42174. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42175. /**
  42176. * Gets wether the color curves effect is enabled.
  42177. */
  42178. get: function () {
  42179. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42180. },
  42181. /**
  42182. * Sets wether the color curves effect is enabled.
  42183. */
  42184. set: function (value) {
  42185. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42186. },
  42187. enumerable: true,
  42188. configurable: true
  42189. });
  42190. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42191. /**
  42192. * Gets wether the color grading effect is enabled.
  42193. */
  42194. get: function () {
  42195. return this.imageProcessingConfiguration.colorGradingEnabled;
  42196. },
  42197. /**
  42198. * Gets wether the color grading effect is enabled.
  42199. */
  42200. set: function (value) {
  42201. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42202. },
  42203. enumerable: true,
  42204. configurable: true
  42205. });
  42206. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42207. /**
  42208. * Gets wether tonemapping is enabled or not.
  42209. */
  42210. get: function () {
  42211. return this._imageProcessingConfiguration.toneMappingEnabled;
  42212. },
  42213. /**
  42214. * Sets wether tonemapping is enabled or not
  42215. */
  42216. set: function (value) {
  42217. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42218. },
  42219. enumerable: true,
  42220. configurable: true
  42221. });
  42222. ;
  42223. ;
  42224. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42225. /**
  42226. * The camera exposure used on this material.
  42227. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42228. * This corresponds to a photographic exposure.
  42229. */
  42230. get: function () {
  42231. return this._imageProcessingConfiguration.exposure;
  42232. },
  42233. /**
  42234. * The camera exposure used on this material.
  42235. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42236. * This corresponds to a photographic exposure.
  42237. */
  42238. set: function (value) {
  42239. this._imageProcessingConfiguration.exposure = value;
  42240. },
  42241. enumerable: true,
  42242. configurable: true
  42243. });
  42244. ;
  42245. ;
  42246. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42247. /**
  42248. * Gets The camera contrast used on this material.
  42249. */
  42250. get: function () {
  42251. return this._imageProcessingConfiguration.contrast;
  42252. },
  42253. /**
  42254. * Sets The camera contrast used on this material.
  42255. */
  42256. set: function (value) {
  42257. this._imageProcessingConfiguration.contrast = value;
  42258. },
  42259. enumerable: true,
  42260. configurable: true
  42261. });
  42262. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42263. /**
  42264. * Gets the Color Grading 2D Lookup Texture.
  42265. */
  42266. get: function () {
  42267. return this._imageProcessingConfiguration.colorGradingTexture;
  42268. },
  42269. /**
  42270. * Sets the Color Grading 2D Lookup Texture.
  42271. */
  42272. set: function (value) {
  42273. this._imageProcessingConfiguration.colorGradingTexture = value;
  42274. },
  42275. enumerable: true,
  42276. configurable: true
  42277. });
  42278. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42279. /**
  42280. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42281. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42282. * 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;
  42283. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42284. */
  42285. get: function () {
  42286. return this._imageProcessingConfiguration.colorCurves;
  42287. },
  42288. /**
  42289. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42290. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42291. * 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;
  42292. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42293. */
  42294. set: function (value) {
  42295. this._imageProcessingConfiguration.colorCurves = value;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. StandardMaterial.prototype.getClassName = function () {
  42301. return "StandardMaterial";
  42302. };
  42303. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42304. get: function () {
  42305. return this._useLogarithmicDepth;
  42306. },
  42307. set: function (value) {
  42308. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42309. this._markAllSubMeshesAsMiscDirty();
  42310. },
  42311. enumerable: true,
  42312. configurable: true
  42313. });
  42314. StandardMaterial.prototype.needAlphaBlending = function () {
  42315. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42316. };
  42317. StandardMaterial.prototype.needAlphaTesting = function () {
  42318. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42319. };
  42320. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42321. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42322. };
  42323. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42324. return this._diffuseTexture;
  42325. };
  42326. /**
  42327. * Child classes can use it to update shaders
  42328. */
  42329. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42330. if (useInstances === void 0) { useInstances = false; }
  42331. if (subMesh.effect && this.isFrozen) {
  42332. if (this._wasPreviouslyReady && subMesh.effect) {
  42333. return true;
  42334. }
  42335. }
  42336. if (!subMesh._materialDefines) {
  42337. subMesh._materialDefines = new StandardMaterialDefines();
  42338. }
  42339. var scene = this.getScene();
  42340. var defines = subMesh._materialDefines;
  42341. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42342. if (defines._renderId === scene.getRenderId()) {
  42343. return true;
  42344. }
  42345. }
  42346. var engine = scene.getEngine();
  42347. // Lights
  42348. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42349. // Textures
  42350. if (defines._areTexturesDirty) {
  42351. defines._needUVs = false;
  42352. defines.MAINUV1 = false;
  42353. defines.MAINUV2 = false;
  42354. if (scene.texturesEnabled) {
  42355. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42356. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42357. return false;
  42358. }
  42359. else {
  42360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42361. }
  42362. }
  42363. else {
  42364. defines.DIFFUSE = false;
  42365. }
  42366. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42367. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42368. return false;
  42369. }
  42370. else {
  42371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42372. }
  42373. }
  42374. else {
  42375. defines.AMBIENT = false;
  42376. }
  42377. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42378. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42379. return false;
  42380. }
  42381. else {
  42382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42383. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42384. }
  42385. }
  42386. else {
  42387. defines.OPACITY = false;
  42388. }
  42389. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42390. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42391. return false;
  42392. }
  42393. else {
  42394. defines._needNormals = true;
  42395. defines.REFLECTION = true;
  42396. defines.ROUGHNESS = (this._roughness > 0);
  42397. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42398. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42399. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42400. switch (this._reflectionTexture.coordinatesMode) {
  42401. case BABYLON.Texture.EXPLICIT_MODE:
  42402. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42403. break;
  42404. case BABYLON.Texture.PLANAR_MODE:
  42405. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42406. break;
  42407. case BABYLON.Texture.PROJECTION_MODE:
  42408. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42409. break;
  42410. case BABYLON.Texture.SKYBOX_MODE:
  42411. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42412. break;
  42413. case BABYLON.Texture.SPHERICAL_MODE:
  42414. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42415. break;
  42416. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42417. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42418. break;
  42419. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42420. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42421. break;
  42422. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42423. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42424. break;
  42425. case BABYLON.Texture.CUBIC_MODE:
  42426. case BABYLON.Texture.INVCUBIC_MODE:
  42427. default:
  42428. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42429. break;
  42430. }
  42431. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42432. }
  42433. }
  42434. else {
  42435. defines.REFLECTION = false;
  42436. }
  42437. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42438. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42439. return false;
  42440. }
  42441. else {
  42442. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42443. }
  42444. }
  42445. else {
  42446. defines.EMISSIVE = false;
  42447. }
  42448. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42449. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42450. return false;
  42451. }
  42452. else {
  42453. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42454. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42455. }
  42456. }
  42457. else {
  42458. defines.LIGHTMAP = false;
  42459. }
  42460. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42461. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42462. return false;
  42463. }
  42464. else {
  42465. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42466. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42467. }
  42468. }
  42469. else {
  42470. defines.SPECULAR = false;
  42471. }
  42472. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42473. // Bump texure can not be not blocking.
  42474. if (!this._bumpTexture.isReady()) {
  42475. return false;
  42476. }
  42477. else {
  42478. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42479. defines.PARALLAX = this._useParallax;
  42480. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42481. }
  42482. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42483. }
  42484. else {
  42485. defines.BUMP = false;
  42486. }
  42487. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42488. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42489. return false;
  42490. }
  42491. else {
  42492. defines._needUVs = true;
  42493. defines.REFRACTION = true;
  42494. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42495. }
  42496. }
  42497. else {
  42498. defines.REFRACTION = false;
  42499. }
  42500. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42501. }
  42502. else {
  42503. defines.DIFFUSE = false;
  42504. defines.AMBIENT = false;
  42505. defines.OPACITY = false;
  42506. defines.REFLECTION = false;
  42507. defines.EMISSIVE = false;
  42508. defines.LIGHTMAP = false;
  42509. defines.BUMP = false;
  42510. defines.REFRACTION = false;
  42511. }
  42512. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42513. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42514. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42515. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42516. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42517. }
  42518. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42519. if (!this._imageProcessingConfiguration.isReady()) {
  42520. return false;
  42521. }
  42522. this._imageProcessingConfiguration.prepareDefines(defines);
  42523. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42524. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42525. }
  42526. if (defines._areFresnelDirty) {
  42527. if (StandardMaterial.FresnelEnabled) {
  42528. // Fresnel
  42529. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42530. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42531. this._reflectionFresnelParameters) {
  42532. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42533. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42534. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42535. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42536. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42537. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42538. defines._needNormals = true;
  42539. defines.FRESNEL = true;
  42540. }
  42541. }
  42542. else {
  42543. defines.FRESNEL = false;
  42544. }
  42545. }
  42546. // Misc.
  42547. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42548. // Attribs
  42549. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42550. // Values that need to be evaluated on every frame
  42551. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42552. // Get correct effect
  42553. if (defines.isDirty) {
  42554. defines.markAsProcessed();
  42555. scene.resetCachedMaterial();
  42556. // Fallbacks
  42557. var fallbacks = new BABYLON.EffectFallbacks();
  42558. if (defines.REFLECTION) {
  42559. fallbacks.addFallback(0, "REFLECTION");
  42560. }
  42561. if (defines.SPECULAR) {
  42562. fallbacks.addFallback(0, "SPECULAR");
  42563. }
  42564. if (defines.BUMP) {
  42565. fallbacks.addFallback(0, "BUMP");
  42566. }
  42567. if (defines.PARALLAX) {
  42568. fallbacks.addFallback(1, "PARALLAX");
  42569. }
  42570. if (defines.PARALLAXOCCLUSION) {
  42571. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42572. }
  42573. if (defines.SPECULAROVERALPHA) {
  42574. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42575. }
  42576. if (defines.FOG) {
  42577. fallbacks.addFallback(1, "FOG");
  42578. }
  42579. if (defines.POINTSIZE) {
  42580. fallbacks.addFallback(0, "POINTSIZE");
  42581. }
  42582. if (defines.LOGARITHMICDEPTH) {
  42583. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42584. }
  42585. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42586. if (defines.SPECULARTERM) {
  42587. fallbacks.addFallback(0, "SPECULARTERM");
  42588. }
  42589. if (defines.DIFFUSEFRESNEL) {
  42590. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42591. }
  42592. if (defines.OPACITYFRESNEL) {
  42593. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42594. }
  42595. if (defines.REFLECTIONFRESNEL) {
  42596. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42597. }
  42598. if (defines.EMISSIVEFRESNEL) {
  42599. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42600. }
  42601. if (defines.FRESNEL) {
  42602. fallbacks.addFallback(4, "FRESNEL");
  42603. }
  42604. //Attributes
  42605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42606. if (defines.NORMAL) {
  42607. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42608. }
  42609. if (defines.UV1) {
  42610. attribs.push(BABYLON.VertexBuffer.UVKind);
  42611. }
  42612. if (defines.UV2) {
  42613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42614. }
  42615. if (defines.VERTEXCOLOR) {
  42616. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42617. }
  42618. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42619. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42620. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42621. var shaderName = "default";
  42622. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42623. "vFogInfos", "vFogColor", "pointSize",
  42624. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42625. "mBones",
  42626. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42627. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42628. "vReflectionPosition", "vReflectionSize",
  42629. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42630. ];
  42631. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42632. var uniformBuffers = ["Material", "Scene"];
  42633. if (BABYLON.ImageProcessingConfiguration) {
  42634. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42635. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42636. }
  42637. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42638. uniformsNames: uniforms,
  42639. uniformBuffersNames: uniformBuffers,
  42640. samplers: samplers,
  42641. defines: defines,
  42642. maxSimultaneousLights: this._maxSimultaneousLights
  42643. });
  42644. if (this.customShaderNameResolve) {
  42645. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42646. }
  42647. var join = defines.toString();
  42648. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42649. attributes: attribs,
  42650. uniformsNames: uniforms,
  42651. uniformBuffersNames: uniformBuffers,
  42652. samplers: samplers,
  42653. defines: join,
  42654. fallbacks: fallbacks,
  42655. onCompiled: this.onCompiled,
  42656. onError: this.onError,
  42657. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42658. }, engine), defines);
  42659. this.buildUniformLayout();
  42660. }
  42661. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42662. return false;
  42663. }
  42664. defines._renderId = scene.getRenderId();
  42665. this._wasPreviouslyReady = true;
  42666. return true;
  42667. };
  42668. StandardMaterial.prototype.buildUniformLayout = function () {
  42669. // Order is important !
  42670. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42671. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42672. this._uniformBuffer.addUniform("opacityParts", 4);
  42673. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42674. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42675. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42676. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42677. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42678. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42679. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42680. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42681. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42682. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42683. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42684. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42685. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42686. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42687. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42688. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42689. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42690. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42691. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42692. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42693. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42694. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42695. this._uniformBuffer.addUniform("specularMatrix", 16);
  42696. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42697. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42698. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42699. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42700. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42701. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42702. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42703. this._uniformBuffer.addUniform("pointSize", 1);
  42704. this._uniformBuffer.create();
  42705. };
  42706. StandardMaterial.prototype.unbind = function () {
  42707. if (this._activeEffect) {
  42708. var needFlag = false;
  42709. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42710. this._activeEffect.setTexture("reflection2DSampler", null);
  42711. needFlag = true;
  42712. }
  42713. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42714. this._activeEffect.setTexture("refraction2DSampler", null);
  42715. needFlag = true;
  42716. }
  42717. if (needFlag) {
  42718. this._markAllSubMeshesAsTexturesDirty();
  42719. }
  42720. }
  42721. _super.prototype.unbind.call(this);
  42722. };
  42723. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42724. var scene = this.getScene();
  42725. var defines = subMesh._materialDefines;
  42726. if (!defines) {
  42727. return;
  42728. }
  42729. var effect = subMesh.effect;
  42730. if (!effect) {
  42731. return;
  42732. }
  42733. this._activeEffect = effect;
  42734. // Matrices
  42735. this.bindOnlyWorldMatrix(world);
  42736. // Normal Matrix
  42737. if (defines.OBJECTSPACE_NORMALMAP) {
  42738. world.toNormalMatrix(this._normalMatrix);
  42739. this.bindOnlyNormalMatrix(this._normalMatrix);
  42740. }
  42741. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42742. // Bones
  42743. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42744. if (mustRebind) {
  42745. this._uniformBuffer.bindToEffect(effect, "Material");
  42746. this.bindViewProjection(effect);
  42747. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42748. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42749. // Fresnel
  42750. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42751. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42752. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42753. }
  42754. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42755. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42756. }
  42757. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42758. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42759. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42760. }
  42761. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42762. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42763. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42764. }
  42765. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42766. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42767. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42768. }
  42769. }
  42770. // Textures
  42771. if (scene.texturesEnabled) {
  42772. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42773. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42774. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42775. if (this._diffuseTexture.hasAlpha) {
  42776. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42777. }
  42778. }
  42779. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42780. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42781. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42782. }
  42783. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42784. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42785. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42786. }
  42787. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42788. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42789. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42790. if (this._reflectionTexture.boundingBoxSize) {
  42791. var cubeTexture = this._reflectionTexture;
  42792. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42793. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42794. }
  42795. }
  42796. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42797. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42798. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42799. }
  42800. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42801. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42802. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42803. }
  42804. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42805. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42806. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42807. }
  42808. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42809. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42810. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42811. if (scene._mirroredCameraPosition) {
  42812. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42813. }
  42814. else {
  42815. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42816. }
  42817. }
  42818. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42819. var depth = 1.0;
  42820. if (!this._refractionTexture.isCube) {
  42821. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42822. if (this._refractionTexture.depth) {
  42823. depth = this._refractionTexture.depth;
  42824. }
  42825. }
  42826. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42827. }
  42828. }
  42829. // Point size
  42830. if (this.pointsCloud) {
  42831. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42832. }
  42833. if (defines.SPECULARTERM) {
  42834. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42835. }
  42836. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42837. // Diffuse
  42838. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42839. }
  42840. // Textures
  42841. if (scene.texturesEnabled) {
  42842. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42843. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42844. }
  42845. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42846. effect.setTexture("ambientSampler", this._ambientTexture);
  42847. }
  42848. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42849. effect.setTexture("opacitySampler", this._opacityTexture);
  42850. }
  42851. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42852. if (this._reflectionTexture.isCube) {
  42853. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42854. }
  42855. else {
  42856. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42857. }
  42858. }
  42859. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42860. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42861. }
  42862. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42863. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42864. }
  42865. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42866. effect.setTexture("specularSampler", this._specularTexture);
  42867. }
  42868. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42869. effect.setTexture("bumpSampler", this._bumpTexture);
  42870. }
  42871. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42872. var depth = 1.0;
  42873. if (this._refractionTexture.isCube) {
  42874. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42875. }
  42876. else {
  42877. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42878. }
  42879. }
  42880. }
  42881. // Clip plane
  42882. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42883. // Colors
  42884. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42885. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42886. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42887. }
  42888. if (mustRebind || !this.isFrozen) {
  42889. // Lights
  42890. if (scene.lightsEnabled && !this._disableLighting) {
  42891. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42892. }
  42893. // View
  42894. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42895. this.bindView(effect);
  42896. }
  42897. // Fog
  42898. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42899. // Morph targets
  42900. if (defines.NUM_MORPH_INFLUENCERS) {
  42901. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42902. }
  42903. // Log. depth
  42904. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42905. // image processing
  42906. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42907. this._imageProcessingConfiguration.bind(this._activeEffect);
  42908. }
  42909. }
  42910. this._uniformBuffer.update();
  42911. this._afterBind(mesh, this._activeEffect);
  42912. };
  42913. StandardMaterial.prototype.getAnimatables = function () {
  42914. var results = [];
  42915. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42916. results.push(this._diffuseTexture);
  42917. }
  42918. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42919. results.push(this._ambientTexture);
  42920. }
  42921. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42922. results.push(this._opacityTexture);
  42923. }
  42924. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42925. results.push(this._reflectionTexture);
  42926. }
  42927. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42928. results.push(this._emissiveTexture);
  42929. }
  42930. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42931. results.push(this._specularTexture);
  42932. }
  42933. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42934. results.push(this._bumpTexture);
  42935. }
  42936. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42937. results.push(this._lightmapTexture);
  42938. }
  42939. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42940. results.push(this._refractionTexture);
  42941. }
  42942. return results;
  42943. };
  42944. StandardMaterial.prototype.getActiveTextures = function () {
  42945. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42946. if (this._diffuseTexture) {
  42947. activeTextures.push(this._diffuseTexture);
  42948. }
  42949. if (this._ambientTexture) {
  42950. activeTextures.push(this._ambientTexture);
  42951. }
  42952. if (this._opacityTexture) {
  42953. activeTextures.push(this._opacityTexture);
  42954. }
  42955. if (this._reflectionTexture) {
  42956. activeTextures.push(this._reflectionTexture);
  42957. }
  42958. if (this._emissiveTexture) {
  42959. activeTextures.push(this._emissiveTexture);
  42960. }
  42961. if (this._specularTexture) {
  42962. activeTextures.push(this._specularTexture);
  42963. }
  42964. if (this._bumpTexture) {
  42965. activeTextures.push(this._bumpTexture);
  42966. }
  42967. if (this._lightmapTexture) {
  42968. activeTextures.push(this._lightmapTexture);
  42969. }
  42970. if (this._refractionTexture) {
  42971. activeTextures.push(this._refractionTexture);
  42972. }
  42973. return activeTextures;
  42974. };
  42975. StandardMaterial.prototype.hasTexture = function (texture) {
  42976. if (_super.prototype.hasTexture.call(this, texture)) {
  42977. return true;
  42978. }
  42979. if (this._diffuseTexture === texture) {
  42980. return true;
  42981. }
  42982. if (this._ambientTexture === texture) {
  42983. return true;
  42984. }
  42985. if (this._opacityTexture === texture) {
  42986. return true;
  42987. }
  42988. if (this._reflectionTexture === texture) {
  42989. return true;
  42990. }
  42991. if (this._emissiveTexture === texture) {
  42992. return true;
  42993. }
  42994. if (this._specularTexture === texture) {
  42995. return true;
  42996. }
  42997. if (this._bumpTexture === texture) {
  42998. return true;
  42999. }
  43000. if (this._lightmapTexture === texture) {
  43001. return true;
  43002. }
  43003. if (this._refractionTexture === texture) {
  43004. return true;
  43005. }
  43006. return false;
  43007. };
  43008. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43009. if (forceDisposeTextures) {
  43010. if (this._diffuseTexture) {
  43011. this._diffuseTexture.dispose();
  43012. }
  43013. if (this._ambientTexture) {
  43014. this._ambientTexture.dispose();
  43015. }
  43016. if (this._opacityTexture) {
  43017. this._opacityTexture.dispose();
  43018. }
  43019. if (this._reflectionTexture) {
  43020. this._reflectionTexture.dispose();
  43021. }
  43022. if (this._emissiveTexture) {
  43023. this._emissiveTexture.dispose();
  43024. }
  43025. if (this._specularTexture) {
  43026. this._specularTexture.dispose();
  43027. }
  43028. if (this._bumpTexture) {
  43029. this._bumpTexture.dispose();
  43030. }
  43031. if (this._lightmapTexture) {
  43032. this._lightmapTexture.dispose();
  43033. }
  43034. if (this._refractionTexture) {
  43035. this._refractionTexture.dispose();
  43036. }
  43037. }
  43038. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43039. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43040. }
  43041. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43042. };
  43043. StandardMaterial.prototype.clone = function (name) {
  43044. var _this = this;
  43045. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43046. result.name = name;
  43047. result.id = name;
  43048. return result;
  43049. };
  43050. StandardMaterial.prototype.serialize = function () {
  43051. return BABYLON.SerializationHelper.Serialize(this);
  43052. };
  43053. // Statics
  43054. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43055. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43056. };
  43057. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43058. get: function () {
  43059. return StandardMaterial._DiffuseTextureEnabled;
  43060. },
  43061. set: function (value) {
  43062. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43063. return;
  43064. }
  43065. StandardMaterial._DiffuseTextureEnabled = value;
  43066. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43067. },
  43068. enumerable: true,
  43069. configurable: true
  43070. });
  43071. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43072. get: function () {
  43073. return StandardMaterial._AmbientTextureEnabled;
  43074. },
  43075. set: function (value) {
  43076. if (StandardMaterial._AmbientTextureEnabled === value) {
  43077. return;
  43078. }
  43079. StandardMaterial._AmbientTextureEnabled = value;
  43080. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43081. },
  43082. enumerable: true,
  43083. configurable: true
  43084. });
  43085. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43086. get: function () {
  43087. return StandardMaterial._OpacityTextureEnabled;
  43088. },
  43089. set: function (value) {
  43090. if (StandardMaterial._OpacityTextureEnabled === value) {
  43091. return;
  43092. }
  43093. StandardMaterial._OpacityTextureEnabled = value;
  43094. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43095. },
  43096. enumerable: true,
  43097. configurable: true
  43098. });
  43099. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43100. get: function () {
  43101. return StandardMaterial._ReflectionTextureEnabled;
  43102. },
  43103. set: function (value) {
  43104. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43105. return;
  43106. }
  43107. StandardMaterial._ReflectionTextureEnabled = value;
  43108. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43109. },
  43110. enumerable: true,
  43111. configurable: true
  43112. });
  43113. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43114. get: function () {
  43115. return StandardMaterial._EmissiveTextureEnabled;
  43116. },
  43117. set: function (value) {
  43118. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43119. return;
  43120. }
  43121. StandardMaterial._EmissiveTextureEnabled = value;
  43122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43123. },
  43124. enumerable: true,
  43125. configurable: true
  43126. });
  43127. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43128. get: function () {
  43129. return StandardMaterial._SpecularTextureEnabled;
  43130. },
  43131. set: function (value) {
  43132. if (StandardMaterial._SpecularTextureEnabled === value) {
  43133. return;
  43134. }
  43135. StandardMaterial._SpecularTextureEnabled = value;
  43136. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43137. },
  43138. enumerable: true,
  43139. configurable: true
  43140. });
  43141. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43142. get: function () {
  43143. return StandardMaterial._BumpTextureEnabled;
  43144. },
  43145. set: function (value) {
  43146. if (StandardMaterial._BumpTextureEnabled === value) {
  43147. return;
  43148. }
  43149. StandardMaterial._BumpTextureEnabled = value;
  43150. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43151. },
  43152. enumerable: true,
  43153. configurable: true
  43154. });
  43155. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43156. get: function () {
  43157. return StandardMaterial._LightmapTextureEnabled;
  43158. },
  43159. set: function (value) {
  43160. if (StandardMaterial._LightmapTextureEnabled === value) {
  43161. return;
  43162. }
  43163. StandardMaterial._LightmapTextureEnabled = value;
  43164. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43165. },
  43166. enumerable: true,
  43167. configurable: true
  43168. });
  43169. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43170. get: function () {
  43171. return StandardMaterial._RefractionTextureEnabled;
  43172. },
  43173. set: function (value) {
  43174. if (StandardMaterial._RefractionTextureEnabled === value) {
  43175. return;
  43176. }
  43177. StandardMaterial._RefractionTextureEnabled = value;
  43178. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43179. },
  43180. enumerable: true,
  43181. configurable: true
  43182. });
  43183. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43184. get: function () {
  43185. return StandardMaterial._ColorGradingTextureEnabled;
  43186. },
  43187. set: function (value) {
  43188. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43189. return;
  43190. }
  43191. StandardMaterial._ColorGradingTextureEnabled = value;
  43192. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43193. },
  43194. enumerable: true,
  43195. configurable: true
  43196. });
  43197. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43198. get: function () {
  43199. return StandardMaterial._FresnelEnabled;
  43200. },
  43201. set: function (value) {
  43202. if (StandardMaterial._FresnelEnabled === value) {
  43203. return;
  43204. }
  43205. StandardMaterial._FresnelEnabled = value;
  43206. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43207. },
  43208. enumerable: true,
  43209. configurable: true
  43210. });
  43211. // Flags used to enable or disable a type of texture for all Standard Materials
  43212. StandardMaterial._DiffuseTextureEnabled = true;
  43213. StandardMaterial._AmbientTextureEnabled = true;
  43214. StandardMaterial._OpacityTextureEnabled = true;
  43215. StandardMaterial._ReflectionTextureEnabled = true;
  43216. StandardMaterial._EmissiveTextureEnabled = true;
  43217. StandardMaterial._SpecularTextureEnabled = true;
  43218. StandardMaterial._BumpTextureEnabled = true;
  43219. StandardMaterial._LightmapTextureEnabled = true;
  43220. StandardMaterial._RefractionTextureEnabled = true;
  43221. StandardMaterial._ColorGradingTextureEnabled = true;
  43222. StandardMaterial._FresnelEnabled = true;
  43223. __decorate([
  43224. BABYLON.serializeAsTexture("diffuseTexture")
  43225. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43226. __decorate([
  43227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43228. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43229. __decorate([
  43230. BABYLON.serializeAsTexture("ambientTexture")
  43231. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43232. __decorate([
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43234. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43235. __decorate([
  43236. BABYLON.serializeAsTexture("opacityTexture")
  43237. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43238. __decorate([
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43240. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43241. __decorate([
  43242. BABYLON.serializeAsTexture("reflectionTexture")
  43243. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43244. __decorate([
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43246. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43247. __decorate([
  43248. BABYLON.serializeAsTexture("emissiveTexture")
  43249. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43250. __decorate([
  43251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43252. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43253. __decorate([
  43254. BABYLON.serializeAsTexture("specularTexture")
  43255. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43256. __decorate([
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43258. ], StandardMaterial.prototype, "specularTexture", void 0);
  43259. __decorate([
  43260. BABYLON.serializeAsTexture("bumpTexture")
  43261. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43262. __decorate([
  43263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43264. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43265. __decorate([
  43266. BABYLON.serializeAsTexture("lightmapTexture")
  43267. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43268. __decorate([
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43271. __decorate([
  43272. BABYLON.serializeAsTexture("refractionTexture")
  43273. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43274. __decorate([
  43275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43276. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43277. __decorate([
  43278. BABYLON.serializeAsColor3("ambient")
  43279. ], StandardMaterial.prototype, "ambientColor", void 0);
  43280. __decorate([
  43281. BABYLON.serializeAsColor3("diffuse")
  43282. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43283. __decorate([
  43284. BABYLON.serializeAsColor3("specular")
  43285. ], StandardMaterial.prototype, "specularColor", void 0);
  43286. __decorate([
  43287. BABYLON.serializeAsColor3("emissive")
  43288. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43289. __decorate([
  43290. BABYLON.serialize()
  43291. ], StandardMaterial.prototype, "specularPower", void 0);
  43292. __decorate([
  43293. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43294. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43295. __decorate([
  43296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43297. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43298. __decorate([
  43299. BABYLON.serialize("useEmissiveAsIllumination")
  43300. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43301. __decorate([
  43302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43303. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43304. __decorate([
  43305. BABYLON.serialize("linkEmissiveWithDiffuse")
  43306. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43307. __decorate([
  43308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43309. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43310. __decorate([
  43311. BABYLON.serialize("useSpecularOverAlpha")
  43312. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43313. __decorate([
  43314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43315. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43316. __decorate([
  43317. BABYLON.serialize("useReflectionOverAlpha")
  43318. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43319. __decorate([
  43320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43321. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43322. __decorate([
  43323. BABYLON.serialize("disableLighting")
  43324. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43325. __decorate([
  43326. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43327. ], StandardMaterial.prototype, "disableLighting", void 0);
  43328. __decorate([
  43329. BABYLON.serialize("useObjectSpaceNormalMap")
  43330. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43331. __decorate([
  43332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43333. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43334. __decorate([
  43335. BABYLON.serialize("useParallax")
  43336. ], StandardMaterial.prototype, "_useParallax", void 0);
  43337. __decorate([
  43338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43339. ], StandardMaterial.prototype, "useParallax", void 0);
  43340. __decorate([
  43341. BABYLON.serialize("useParallaxOcclusion")
  43342. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43343. __decorate([
  43344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43345. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43346. __decorate([
  43347. BABYLON.serialize()
  43348. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43349. __decorate([
  43350. BABYLON.serialize("roughness")
  43351. ], StandardMaterial.prototype, "_roughness", void 0);
  43352. __decorate([
  43353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43354. ], StandardMaterial.prototype, "roughness", void 0);
  43355. __decorate([
  43356. BABYLON.serialize()
  43357. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43358. __decorate([
  43359. BABYLON.serialize()
  43360. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43361. __decorate([
  43362. BABYLON.serialize()
  43363. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43364. __decorate([
  43365. BABYLON.serialize("useLightmapAsShadowmap")
  43366. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43367. __decorate([
  43368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43369. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43370. __decorate([
  43371. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43372. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43373. __decorate([
  43374. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43375. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43376. __decorate([
  43377. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43378. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43379. __decorate([
  43380. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43381. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43382. __decorate([
  43383. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43384. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43385. __decorate([
  43386. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43387. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43388. __decorate([
  43389. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43390. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43391. __decorate([
  43392. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43393. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43394. __decorate([
  43395. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43396. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43397. __decorate([
  43398. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43399. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43400. __decorate([
  43401. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43402. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43403. __decorate([
  43404. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43405. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43406. __decorate([
  43407. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43408. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43409. __decorate([
  43410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43411. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43412. __decorate([
  43413. BABYLON.serialize("maxSimultaneousLights")
  43414. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43415. __decorate([
  43416. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43417. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43418. __decorate([
  43419. BABYLON.serialize("invertNormalMapX")
  43420. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43421. __decorate([
  43422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43423. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43424. __decorate([
  43425. BABYLON.serialize("invertNormalMapY")
  43426. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43427. __decorate([
  43428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43429. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43430. __decorate([
  43431. BABYLON.serialize("twoSidedLighting")
  43432. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43433. __decorate([
  43434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43435. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43436. __decorate([
  43437. BABYLON.serialize()
  43438. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43439. return StandardMaterial;
  43440. }(BABYLON.PushMaterial));
  43441. BABYLON.StandardMaterial = StandardMaterial;
  43442. })(BABYLON || (BABYLON = {}));
  43443. //# sourceMappingURL=babylon.standardMaterial.js.map
  43444. var BABYLON;
  43445. (function (BABYLON) {
  43446. /**
  43447. * Manages the defines for the PBR Material.
  43448. * @hiddenChildren
  43449. */
  43450. var PBRMaterialDefines = /** @class */ (function (_super) {
  43451. __extends(PBRMaterialDefines, _super);
  43452. /**
  43453. * Initializes the PBR Material defines.
  43454. */
  43455. function PBRMaterialDefines() {
  43456. var _this = _super.call(this) || this;
  43457. _this.PBR = true;
  43458. _this.MAINUV1 = false;
  43459. _this.MAINUV2 = false;
  43460. _this.UV1 = false;
  43461. _this.UV2 = false;
  43462. _this.ALBEDO = false;
  43463. _this.ALBEDODIRECTUV = 0;
  43464. _this.VERTEXCOLOR = false;
  43465. _this.AMBIENT = false;
  43466. _this.AMBIENTDIRECTUV = 0;
  43467. _this.AMBIENTINGRAYSCALE = false;
  43468. _this.OPACITY = false;
  43469. _this.VERTEXALPHA = false;
  43470. _this.OPACITYDIRECTUV = 0;
  43471. _this.OPACITYRGB = false;
  43472. _this.ALPHATEST = false;
  43473. _this.DEPTHPREPASS = false;
  43474. _this.ALPHABLEND = false;
  43475. _this.ALPHAFROMALBEDO = false;
  43476. _this.ALPHATESTVALUE = "0.5";
  43477. _this.SPECULAROVERALPHA = false;
  43478. _this.RADIANCEOVERALPHA = false;
  43479. _this.ALPHAFRESNEL = false;
  43480. _this.LINEARALPHAFRESNEL = false;
  43481. _this.PREMULTIPLYALPHA = false;
  43482. _this.EMISSIVE = false;
  43483. _this.EMISSIVEDIRECTUV = 0;
  43484. _this.REFLECTIVITY = false;
  43485. _this.REFLECTIVITYDIRECTUV = 0;
  43486. _this.SPECULARTERM = false;
  43487. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43488. _this.MICROSURFACEAUTOMATIC = false;
  43489. _this.LODBASEDMICROSFURACE = false;
  43490. _this.MICROSURFACEMAP = false;
  43491. _this.MICROSURFACEMAPDIRECTUV = 0;
  43492. _this.METALLICWORKFLOW = false;
  43493. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43494. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43495. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43496. _this.AOSTOREINMETALMAPRED = false;
  43497. _this.ENVIRONMENTBRDF = false;
  43498. _this.NORMAL = false;
  43499. _this.TANGENT = false;
  43500. _this.BUMP = false;
  43501. _this.BUMPDIRECTUV = 0;
  43502. _this.OBJECTSPACE_NORMALMAP = false;
  43503. _this.PARALLAX = false;
  43504. _this.PARALLAXOCCLUSION = false;
  43505. _this.NORMALXYSCALE = true;
  43506. _this.LIGHTMAP = false;
  43507. _this.LIGHTMAPDIRECTUV = 0;
  43508. _this.USELIGHTMAPASSHADOWMAP = false;
  43509. _this.GAMMALIGHTMAP = false;
  43510. _this.REFLECTION = false;
  43511. _this.REFLECTIONMAP_3D = false;
  43512. _this.REFLECTIONMAP_SPHERICAL = false;
  43513. _this.REFLECTIONMAP_PLANAR = false;
  43514. _this.REFLECTIONMAP_CUBIC = false;
  43515. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43516. _this.REFLECTIONMAP_PROJECTION = false;
  43517. _this.REFLECTIONMAP_SKYBOX = false;
  43518. _this.REFLECTIONMAP_EXPLICIT = false;
  43519. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43520. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43521. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43522. _this.INVERTCUBICMAP = false;
  43523. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43524. _this.USESPHERICALINVERTEX = false;
  43525. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43526. _this.LODINREFLECTIONALPHA = false;
  43527. _this.GAMMAREFLECTION = false;
  43528. _this.RGBDREFLECTION = false;
  43529. _this.RADIANCEOCCLUSION = false;
  43530. _this.HORIZONOCCLUSION = false;
  43531. _this.REFRACTION = false;
  43532. _this.REFRACTIONMAP_3D = false;
  43533. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43534. _this.LODINREFRACTIONALPHA = false;
  43535. _this.GAMMAREFRACTION = false;
  43536. _this.RGBDREFRACTION = false;
  43537. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43538. _this.INSTANCES = false;
  43539. _this.NUM_BONE_INFLUENCERS = 0;
  43540. _this.BonesPerMesh = 0;
  43541. _this.NONUNIFORMSCALING = false;
  43542. _this.MORPHTARGETS = false;
  43543. _this.MORPHTARGETS_NORMAL = false;
  43544. _this.MORPHTARGETS_TANGENT = false;
  43545. _this.NUM_MORPH_INFLUENCERS = 0;
  43546. _this.IMAGEPROCESSING = false;
  43547. _this.VIGNETTE = false;
  43548. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43549. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43550. _this.TONEMAPPING = false;
  43551. _this.CONTRAST = false;
  43552. _this.COLORCURVES = false;
  43553. _this.COLORGRADING = false;
  43554. _this.COLORGRADING3D = false;
  43555. _this.SAMPLER3DGREENDEPTH = false;
  43556. _this.SAMPLER3DBGRMAP = false;
  43557. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43558. _this.EXPOSURE = false;
  43559. _this.USEPHYSICALLIGHTFALLOFF = false;
  43560. _this.TWOSIDEDLIGHTING = false;
  43561. _this.SHADOWFLOAT = false;
  43562. _this.CLIPPLANE = false;
  43563. _this.POINTSIZE = false;
  43564. _this.FOG = false;
  43565. _this.LOGARITHMICDEPTH = false;
  43566. _this.FORCENORMALFORWARD = false;
  43567. _this.SPECULARAA = false;
  43568. _this.UNLIT = false;
  43569. _this.rebuild();
  43570. return _this;
  43571. }
  43572. /**
  43573. * Resets the PBR Material defines.
  43574. */
  43575. PBRMaterialDefines.prototype.reset = function () {
  43576. _super.prototype.reset.call(this);
  43577. this.ALPHATESTVALUE = "0.5";
  43578. this.PBR = true;
  43579. };
  43580. return PBRMaterialDefines;
  43581. }(BABYLON.MaterialDefines));
  43582. /**
  43583. * The Physically based material base class of BJS.
  43584. *
  43585. * This offers the main features of a standard PBR material.
  43586. * For more information, please refer to the documentation :
  43587. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43588. */
  43589. var PBRBaseMaterial = /** @class */ (function (_super) {
  43590. __extends(PBRBaseMaterial, _super);
  43591. /**
  43592. * Instantiates a new PBRMaterial instance.
  43593. *
  43594. * @param name The material name
  43595. * @param scene The scene the material will be use in.
  43596. */
  43597. function PBRBaseMaterial(name, scene) {
  43598. var _this = _super.call(this, name, scene) || this;
  43599. /**
  43600. * Intensity of the direct lights e.g. the four lights available in your scene.
  43601. * This impacts both the direct diffuse and specular highlights.
  43602. */
  43603. _this._directIntensity = 1.0;
  43604. /**
  43605. * Intensity of the emissive part of the material.
  43606. * This helps controlling the emissive effect without modifying the emissive color.
  43607. */
  43608. _this._emissiveIntensity = 1.0;
  43609. /**
  43610. * Intensity of the environment e.g. how much the environment will light the object
  43611. * either through harmonics for rough material or through the refelction for shiny ones.
  43612. */
  43613. _this._environmentIntensity = 1.0;
  43614. /**
  43615. * This is a special control allowing the reduction of the specular highlights coming from the
  43616. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43617. */
  43618. _this._specularIntensity = 1.0;
  43619. /**
  43620. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43621. */
  43622. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43623. /**
  43624. * Debug Control allowing disabling the bump map on this material.
  43625. */
  43626. _this._disableBumpMap = false;
  43627. /**
  43628. * AKA Occlusion Texture Intensity in other nomenclature.
  43629. */
  43630. _this._ambientTextureStrength = 1.0;
  43631. /**
  43632. * The color of a material in ambient lighting.
  43633. */
  43634. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43635. /**
  43636. * AKA Diffuse Color in other nomenclature.
  43637. */
  43638. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43639. /**
  43640. * AKA Specular Color in other nomenclature.
  43641. */
  43642. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43643. /**
  43644. * The color applied when light is reflected from a material.
  43645. */
  43646. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43647. /**
  43648. * The color applied when light is emitted from a material.
  43649. */
  43650. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43651. /**
  43652. * AKA Glossiness in other nomenclature.
  43653. */
  43654. _this._microSurface = 0.9;
  43655. /**
  43656. * source material index of refraction (IOR)' / 'destination material IOR.
  43657. */
  43658. _this._indexOfRefraction = 0.66;
  43659. /**
  43660. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43661. */
  43662. _this._invertRefractionY = false;
  43663. /**
  43664. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43665. * Materials half opaque for instance using refraction could benefit from this control.
  43666. */
  43667. _this._linkRefractionWithTransparency = false;
  43668. /**
  43669. * Specifies that the material will use the light map as a show map.
  43670. */
  43671. _this._useLightmapAsShadowmap = false;
  43672. /**
  43673. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43674. * makes the reflect vector face the model (under horizon).
  43675. */
  43676. _this._useHorizonOcclusion = true;
  43677. /**
  43678. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43679. * too much the area relying on ambient texture to define their ambient occlusion.
  43680. */
  43681. _this._useRadianceOcclusion = true;
  43682. /**
  43683. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43684. */
  43685. _this._useAlphaFromAlbedoTexture = false;
  43686. /**
  43687. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43688. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43689. */
  43690. _this._useSpecularOverAlpha = true;
  43691. /**
  43692. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43693. */
  43694. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43695. /**
  43696. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43697. */
  43698. _this._useRoughnessFromMetallicTextureAlpha = true;
  43699. /**
  43700. * Specifies if the metallic texture contains the roughness information in its green channel.
  43701. */
  43702. _this._useRoughnessFromMetallicTextureGreen = false;
  43703. /**
  43704. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43705. */
  43706. _this._useMetallnessFromMetallicTextureBlue = false;
  43707. /**
  43708. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43709. */
  43710. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43711. /**
  43712. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43713. */
  43714. _this._useAmbientInGrayScale = false;
  43715. /**
  43716. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43717. * The material will try to infer what glossiness each pixel should be.
  43718. */
  43719. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43720. /**
  43721. * BJS is using an harcoded light falloff based on a manually sets up range.
  43722. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43723. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43724. */
  43725. _this._usePhysicalLightFalloff = true;
  43726. /**
  43727. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43728. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43729. */
  43730. _this._useRadianceOverAlpha = true;
  43731. /**
  43732. * Allows using an object space normal map (instead of tangent space).
  43733. */
  43734. _this._useObjectSpaceNormalMap = false;
  43735. /**
  43736. * Allows using the bump map in parallax mode.
  43737. */
  43738. _this._useParallax = false;
  43739. /**
  43740. * Allows using the bump map in parallax occlusion mode.
  43741. */
  43742. _this._useParallaxOcclusion = false;
  43743. /**
  43744. * Controls the scale bias of the parallax mode.
  43745. */
  43746. _this._parallaxScaleBias = 0.05;
  43747. /**
  43748. * If sets to true, disables all the lights affecting the material.
  43749. */
  43750. _this._disableLighting = false;
  43751. /**
  43752. * Number of Simultaneous lights allowed on the material.
  43753. */
  43754. _this._maxSimultaneousLights = 4;
  43755. /**
  43756. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43757. */
  43758. _this._invertNormalMapX = false;
  43759. /**
  43760. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43761. */
  43762. _this._invertNormalMapY = false;
  43763. /**
  43764. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43765. */
  43766. _this._twoSidedLighting = false;
  43767. /**
  43768. * Defines the alpha limits in alpha test mode.
  43769. */
  43770. _this._alphaCutOff = 0.4;
  43771. /**
  43772. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43773. */
  43774. _this._forceAlphaTest = false;
  43775. /**
  43776. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43777. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43778. */
  43779. _this._useAlphaFresnel = false;
  43780. /**
  43781. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43782. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43783. */
  43784. _this._useLinearAlphaFresnel = false;
  43785. /**
  43786. * The transparency mode of the material.
  43787. */
  43788. _this._transparencyMode = null;
  43789. /**
  43790. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43791. * from cos thetav and roughness:
  43792. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43793. */
  43794. _this._environmentBRDFTexture = null;
  43795. /**
  43796. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43797. */
  43798. _this._forceIrradianceInFragment = false;
  43799. /**
  43800. * Force normal to face away from face.
  43801. */
  43802. _this._forceNormalForward = false;
  43803. /**
  43804. * Enables specular anti aliasing in the PBR shader.
  43805. * It will both interacts on the Geometry for analytical and IBL lighting.
  43806. * It also prefilter the roughness map based on the bump values.
  43807. */
  43808. _this._enableSpecularAntiAliasing = false;
  43809. /**
  43810. * Stores the available render targets.
  43811. */
  43812. _this._renderTargets = new BABYLON.SmartArray(16);
  43813. /**
  43814. * Sets the global ambient color for the material used in lighting calculations.
  43815. */
  43816. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43817. /**
  43818. * If set to true, no lighting calculations will be applied.
  43819. */
  43820. _this._unlit = false;
  43821. // Setup the default processing configuration to the scene.
  43822. _this._attachImageProcessingConfiguration(null);
  43823. _this.getRenderTargetTextures = function () {
  43824. _this._renderTargets.reset();
  43825. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43826. _this._renderTargets.push(_this._reflectionTexture);
  43827. }
  43828. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43829. _this._renderTargets.push(_this._refractionTexture);
  43830. }
  43831. return _this._renderTargets;
  43832. };
  43833. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43834. return _this;
  43835. }
  43836. /**
  43837. * Attaches a new image processing configuration to the PBR Material.
  43838. * @param configuration
  43839. */
  43840. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43841. var _this = this;
  43842. if (configuration === this._imageProcessingConfiguration) {
  43843. return;
  43844. }
  43845. // Detaches observer.
  43846. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43847. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43848. }
  43849. // Pick the scene configuration if needed.
  43850. if (!configuration) {
  43851. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43852. }
  43853. else {
  43854. this._imageProcessingConfiguration = configuration;
  43855. }
  43856. // Attaches observer.
  43857. if (this._imageProcessingConfiguration) {
  43858. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43859. _this._markAllSubMeshesAsImageProcessingDirty();
  43860. });
  43861. }
  43862. };
  43863. /**
  43864. * Gets the name of the material class.
  43865. */
  43866. PBRBaseMaterial.prototype.getClassName = function () {
  43867. return "PBRBaseMaterial";
  43868. };
  43869. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43870. /**
  43871. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43872. */
  43873. get: function () {
  43874. return this._useLogarithmicDepth;
  43875. },
  43876. /**
  43877. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43878. */
  43879. set: function (value) {
  43880. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43881. },
  43882. enumerable: true,
  43883. configurable: true
  43884. });
  43885. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43886. /**
  43887. * Gets the current transparency mode.
  43888. */
  43889. get: function () {
  43890. return this._transparencyMode;
  43891. },
  43892. /**
  43893. * Sets the transparency mode of the material.
  43894. *
  43895. * | Value | Type | Description |
  43896. * | ----- | ----------------------------------- | ----------- |
  43897. * | 0 | OPAQUE | |
  43898. * | 1 | ALPHATEST | |
  43899. * | 2 | ALPHABLEND | |
  43900. * | 3 | ALPHATESTANDBLEND | |
  43901. *
  43902. */
  43903. set: function (value) {
  43904. if (this._transparencyMode === value) {
  43905. return;
  43906. }
  43907. this._transparencyMode = value;
  43908. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43909. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43910. },
  43911. enumerable: true,
  43912. configurable: true
  43913. });
  43914. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43915. /**
  43916. * Returns true if alpha blending should be disabled.
  43917. */
  43918. get: function () {
  43919. return (this._linkRefractionWithTransparency ||
  43920. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43921. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43922. },
  43923. enumerable: true,
  43924. configurable: true
  43925. });
  43926. /**
  43927. * Specifies whether or not this material should be rendered in alpha blend mode.
  43928. */
  43929. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43930. if (this._disableAlphaBlending) {
  43931. return false;
  43932. }
  43933. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43934. };
  43935. /**
  43936. * Specifies if the mesh will require alpha blending.
  43937. * @param mesh - BJS mesh.
  43938. */
  43939. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43940. if (this._disableAlphaBlending) {
  43941. return false;
  43942. }
  43943. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43944. };
  43945. /**
  43946. * Specifies whether or not this material should be rendered in alpha test mode.
  43947. */
  43948. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43949. if (this._forceAlphaTest) {
  43950. return true;
  43951. }
  43952. if (this._linkRefractionWithTransparency) {
  43953. return false;
  43954. }
  43955. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43956. };
  43957. /**
  43958. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43959. */
  43960. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43961. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43962. };
  43963. /**
  43964. * Gets the texture used for the alpha test.
  43965. */
  43966. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43967. return this._albedoTexture;
  43968. };
  43969. /**
  43970. * Specifies that the submesh is ready to be used.
  43971. * @param mesh - BJS mesh.
  43972. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43973. * @param useInstances - Specifies that instances should be used.
  43974. * @returns - boolean indicating that the submesh is ready or not.
  43975. */
  43976. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43977. if (subMesh.effect && this.isFrozen) {
  43978. if (this._wasPreviouslyReady) {
  43979. return true;
  43980. }
  43981. }
  43982. if (!subMesh._materialDefines) {
  43983. subMesh._materialDefines = new PBRMaterialDefines();
  43984. }
  43985. var defines = subMesh._materialDefines;
  43986. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43987. if (defines._renderId === this.getScene().getRenderId()) {
  43988. return true;
  43989. }
  43990. }
  43991. var scene = this.getScene();
  43992. var engine = scene.getEngine();
  43993. if (defines._areTexturesDirty) {
  43994. if (scene.texturesEnabled) {
  43995. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43996. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43997. return false;
  43998. }
  43999. }
  44000. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44001. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44002. return false;
  44003. }
  44004. }
  44005. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44006. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44007. return false;
  44008. }
  44009. }
  44010. var reflectionTexture = this._getReflectionTexture();
  44011. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44012. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44013. return false;
  44014. }
  44015. }
  44016. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44017. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44018. return false;
  44019. }
  44020. }
  44021. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44022. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44023. return false;
  44024. }
  44025. }
  44026. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44027. if (this._metallicTexture) {
  44028. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44029. return false;
  44030. }
  44031. }
  44032. else if (this._reflectivityTexture) {
  44033. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44034. return false;
  44035. }
  44036. }
  44037. if (this._microSurfaceTexture) {
  44038. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44039. return false;
  44040. }
  44041. }
  44042. }
  44043. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44044. // Bump texture cannot be not blocking.
  44045. if (!this._bumpTexture.isReady()) {
  44046. return false;
  44047. }
  44048. }
  44049. var refractionTexture = this._getRefractionTexture();
  44050. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44051. if (!refractionTexture.isReadyOrNotBlocking()) {
  44052. return false;
  44053. }
  44054. }
  44055. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44056. // This is blocking.
  44057. if (!this._environmentBRDFTexture.isReady()) {
  44058. return false;
  44059. }
  44060. }
  44061. }
  44062. }
  44063. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44064. if (!this._imageProcessingConfiguration.isReady()) {
  44065. return false;
  44066. }
  44067. }
  44068. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44069. mesh.createNormals(true);
  44070. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44071. }
  44072. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44073. if (effect) {
  44074. scene.resetCachedMaterial();
  44075. subMesh.setEffect(effect, defines);
  44076. this.buildUniformLayout();
  44077. }
  44078. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44079. return false;
  44080. }
  44081. defines._renderId = scene.getRenderId();
  44082. this._wasPreviouslyReady = true;
  44083. return true;
  44084. };
  44085. /**
  44086. * Specifies if the material uses metallic roughness workflow.
  44087. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44088. */
  44089. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44090. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44091. return true;
  44092. }
  44093. return false;
  44094. };
  44095. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44096. if (onCompiled === void 0) { onCompiled = null; }
  44097. if (onError === void 0) { onError = null; }
  44098. if (useInstances === void 0) { useInstances = null; }
  44099. if (useClipPlane === void 0) { useClipPlane = null; }
  44100. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44101. if (!defines.isDirty) {
  44102. return null;
  44103. }
  44104. defines.markAsProcessed();
  44105. var scene = this.getScene();
  44106. var engine = scene.getEngine();
  44107. // Fallbacks
  44108. var fallbacks = new BABYLON.EffectFallbacks();
  44109. var fallbackRank = 0;
  44110. if (defines.USESPHERICALINVERTEX) {
  44111. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44112. }
  44113. if (defines.FOG) {
  44114. fallbacks.addFallback(fallbackRank, "FOG");
  44115. }
  44116. if (defines.SPECULARAA) {
  44117. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44118. }
  44119. if (defines.POINTSIZE) {
  44120. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44121. }
  44122. if (defines.LOGARITHMICDEPTH) {
  44123. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44124. }
  44125. if (defines.PARALLAX) {
  44126. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44127. }
  44128. if (defines.PARALLAXOCCLUSION) {
  44129. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44130. }
  44131. if (defines.ENVIRONMENTBRDF) {
  44132. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44133. }
  44134. if (defines.TANGENT) {
  44135. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44136. }
  44137. if (defines.BUMP) {
  44138. fallbacks.addFallback(fallbackRank++, "BUMP");
  44139. }
  44140. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44141. if (defines.SPECULARTERM) {
  44142. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44143. }
  44144. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44145. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44146. }
  44147. if (defines.LIGHTMAP) {
  44148. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44149. }
  44150. if (defines.NORMAL) {
  44151. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44152. }
  44153. if (defines.AMBIENT) {
  44154. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44155. }
  44156. if (defines.EMISSIVE) {
  44157. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44158. }
  44159. if (defines.VERTEXCOLOR) {
  44160. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44161. }
  44162. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44163. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44164. }
  44165. if (defines.MORPHTARGETS) {
  44166. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44167. }
  44168. //Attributes
  44169. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44170. if (defines.NORMAL) {
  44171. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44172. }
  44173. if (defines.TANGENT) {
  44174. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44175. }
  44176. if (defines.UV1) {
  44177. attribs.push(BABYLON.VertexBuffer.UVKind);
  44178. }
  44179. if (defines.UV2) {
  44180. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44181. }
  44182. if (defines.VERTEXCOLOR) {
  44183. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44184. }
  44185. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44186. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44187. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44188. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44189. "vFogInfos", "vFogColor", "pointSize",
  44190. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44191. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44192. "mBones",
  44193. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44194. "vLightingIntensity",
  44195. "logarithmicDepthConstant",
  44196. "vSphericalX", "vSphericalY", "vSphericalZ",
  44197. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44198. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44199. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44200. "vTangentSpaceParams"
  44201. ];
  44202. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44203. "bumpSampler", "lightmapSampler", "opacitySampler",
  44204. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44205. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44206. "microSurfaceSampler", "environmentBrdfSampler"];
  44207. var uniformBuffers = ["Material", "Scene"];
  44208. if (BABYLON.ImageProcessingConfiguration) {
  44209. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44210. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44211. }
  44212. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44213. uniformsNames: uniforms,
  44214. uniformBuffersNames: uniformBuffers,
  44215. samplers: samplers,
  44216. defines: defines,
  44217. maxSimultaneousLights: this._maxSimultaneousLights
  44218. });
  44219. var join = defines.toString();
  44220. return engine.createEffect("pbr", {
  44221. attributes: attribs,
  44222. uniformsNames: uniforms,
  44223. uniformBuffersNames: uniformBuffers,
  44224. samplers: samplers,
  44225. defines: join,
  44226. fallbacks: fallbacks,
  44227. onCompiled: onCompiled,
  44228. onError: onError,
  44229. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44230. }, engine);
  44231. };
  44232. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44233. if (useInstances === void 0) { useInstances = null; }
  44234. if (useClipPlane === void 0) { useClipPlane = null; }
  44235. var scene = this.getScene();
  44236. var engine = scene.getEngine();
  44237. // Lights
  44238. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44239. defines._needNormals = true;
  44240. // Textures
  44241. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44242. if (defines._areTexturesDirty) {
  44243. defines._needUVs = false;
  44244. if (scene.texturesEnabled) {
  44245. if (scene.getEngine().getCaps().textureLOD) {
  44246. defines.LODBASEDMICROSFURACE = true;
  44247. }
  44248. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44250. }
  44251. else {
  44252. defines.ALBEDO = false;
  44253. }
  44254. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44256. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44257. }
  44258. else {
  44259. defines.AMBIENT = false;
  44260. }
  44261. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44263. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44264. }
  44265. else {
  44266. defines.OPACITY = false;
  44267. }
  44268. var reflectionTexture = this._getReflectionTexture();
  44269. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44270. defines.REFLECTION = true;
  44271. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44272. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44273. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44274. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44275. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44276. defines.INVERTCUBICMAP = true;
  44277. }
  44278. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44279. switch (reflectionTexture.coordinatesMode) {
  44280. case BABYLON.Texture.EXPLICIT_MODE:
  44281. defines.REFLECTIONMAP_EXPLICIT = true;
  44282. break;
  44283. case BABYLON.Texture.PLANAR_MODE:
  44284. defines.REFLECTIONMAP_PLANAR = true;
  44285. break;
  44286. case BABYLON.Texture.PROJECTION_MODE:
  44287. defines.REFLECTIONMAP_PROJECTION = true;
  44288. break;
  44289. case BABYLON.Texture.SKYBOX_MODE:
  44290. defines.REFLECTIONMAP_SKYBOX = true;
  44291. break;
  44292. case BABYLON.Texture.SPHERICAL_MODE:
  44293. defines.REFLECTIONMAP_SPHERICAL = true;
  44294. break;
  44295. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44296. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44297. break;
  44298. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44299. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44300. break;
  44301. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44302. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44303. break;
  44304. case BABYLON.Texture.CUBIC_MODE:
  44305. case BABYLON.Texture.INVCUBIC_MODE:
  44306. default:
  44307. defines.REFLECTIONMAP_CUBIC = true;
  44308. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44309. break;
  44310. }
  44311. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44312. if (reflectionTexture.sphericalPolynomial) {
  44313. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44314. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44315. defines.USESPHERICALINVERTEX = false;
  44316. }
  44317. else {
  44318. defines.USESPHERICALINVERTEX = true;
  44319. }
  44320. }
  44321. }
  44322. }
  44323. else {
  44324. defines.REFLECTION = false;
  44325. defines.REFLECTIONMAP_3D = false;
  44326. defines.REFLECTIONMAP_SPHERICAL = false;
  44327. defines.REFLECTIONMAP_PLANAR = false;
  44328. defines.REFLECTIONMAP_CUBIC = false;
  44329. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44330. defines.REFLECTIONMAP_PROJECTION = false;
  44331. defines.REFLECTIONMAP_SKYBOX = false;
  44332. defines.REFLECTIONMAP_EXPLICIT = false;
  44333. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44334. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44335. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44336. defines.INVERTCUBICMAP = false;
  44337. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44338. defines.USESPHERICALINVERTEX = false;
  44339. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44340. defines.LODINREFLECTIONALPHA = false;
  44341. defines.GAMMAREFLECTION = false;
  44342. defines.RGBDREFLECTION = false;
  44343. }
  44344. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44345. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44346. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44347. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44348. }
  44349. else {
  44350. defines.LIGHTMAP = false;
  44351. }
  44352. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44353. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44354. }
  44355. else {
  44356. defines.EMISSIVE = false;
  44357. }
  44358. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44359. if (this._metallicTexture) {
  44360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44361. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44362. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44363. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44364. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44365. }
  44366. else if (this._reflectivityTexture) {
  44367. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44368. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44369. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44370. }
  44371. else {
  44372. defines.REFLECTIVITY = false;
  44373. }
  44374. if (this._microSurfaceTexture) {
  44375. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44376. }
  44377. else {
  44378. defines.MICROSURFACEMAP = false;
  44379. }
  44380. }
  44381. else {
  44382. defines.REFLECTIVITY = false;
  44383. defines.MICROSURFACEMAP = false;
  44384. }
  44385. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44386. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44387. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44388. defines.PARALLAX = true;
  44389. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44390. }
  44391. else {
  44392. defines.PARALLAX = false;
  44393. }
  44394. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44395. }
  44396. else {
  44397. defines.BUMP = false;
  44398. }
  44399. var refractionTexture = this._getRefractionTexture();
  44400. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44401. defines.REFRACTION = true;
  44402. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44403. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44404. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44405. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44406. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44407. if (this._linkRefractionWithTransparency) {
  44408. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44409. }
  44410. }
  44411. else {
  44412. defines.REFRACTION = false;
  44413. }
  44414. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44415. defines.ENVIRONMENTBRDF = true;
  44416. }
  44417. else {
  44418. defines.ENVIRONMENTBRDF = false;
  44419. }
  44420. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44421. defines.ALPHAFROMALBEDO = true;
  44422. }
  44423. else {
  44424. defines.ALPHAFROMALBEDO = false;
  44425. }
  44426. }
  44427. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44428. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44429. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44430. if (!this.backFaceCulling && this._twoSidedLighting) {
  44431. defines.TWOSIDEDLIGHTING = true;
  44432. }
  44433. else {
  44434. defines.TWOSIDEDLIGHTING = false;
  44435. }
  44436. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44437. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44438. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44439. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44440. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44441. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44442. }
  44443. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44444. this._imageProcessingConfiguration.prepareDefines(defines);
  44445. }
  44446. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44447. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44448. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44449. // Misc.
  44450. if (defines._areMiscDirty) {
  44451. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44452. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44453. }
  44454. // Values that need to be evaluated on every frame
  44455. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44456. // Attribs
  44457. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44458. };
  44459. /**
  44460. * Force shader compilation
  44461. */
  44462. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44463. var _this = this;
  44464. var localOptions = __assign({ clipPlane: false }, options);
  44465. var defines = new PBRMaterialDefines();
  44466. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44467. if (effect.isReady()) {
  44468. if (onCompiled) {
  44469. onCompiled(this);
  44470. }
  44471. }
  44472. else {
  44473. effect.onCompileObservable.add(function () {
  44474. if (onCompiled) {
  44475. onCompiled(_this);
  44476. }
  44477. });
  44478. }
  44479. };
  44480. /**
  44481. * Initializes the uniform buffer layout for the shader.
  44482. */
  44483. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44484. // Order is important !
  44485. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44486. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44487. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44488. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44489. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44490. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44491. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44492. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44493. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44494. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44495. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44496. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44497. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44498. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44499. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44500. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44501. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44502. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44503. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44504. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44505. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44506. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44507. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44508. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44509. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44510. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44511. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44512. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44513. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44514. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44515. this._uniformBuffer.addUniform("pointSize", 1);
  44516. this._uniformBuffer.create();
  44517. };
  44518. /**
  44519. * Unbinds the textures.
  44520. */
  44521. PBRBaseMaterial.prototype.unbind = function () {
  44522. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44523. this._uniformBuffer.setTexture("reflectionSampler", null);
  44524. }
  44525. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44526. this._uniformBuffer.setTexture("refractionSampler", null);
  44527. }
  44528. _super.prototype.unbind.call(this);
  44529. };
  44530. /**
  44531. * Binds the submesh data.
  44532. * @param world - The world matrix.
  44533. * @param mesh - The BJS mesh.
  44534. * @param subMesh - A submesh of the BJS mesh.
  44535. */
  44536. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44537. var scene = this.getScene();
  44538. var defines = subMesh._materialDefines;
  44539. if (!defines) {
  44540. return;
  44541. }
  44542. var effect = subMesh.effect;
  44543. if (!effect) {
  44544. return;
  44545. }
  44546. this._activeEffect = effect;
  44547. // Matrices
  44548. this.bindOnlyWorldMatrix(world);
  44549. // Normal Matrix
  44550. if (defines.OBJECTSPACE_NORMALMAP) {
  44551. world.toNormalMatrix(this._normalMatrix);
  44552. this.bindOnlyNormalMatrix(this._normalMatrix);
  44553. }
  44554. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44555. // Bones
  44556. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44557. var reflectionTexture = null;
  44558. if (mustRebind) {
  44559. this._uniformBuffer.bindToEffect(effect, "Material");
  44560. this.bindViewProjection(effect);
  44561. reflectionTexture = this._getReflectionTexture();
  44562. var refractionTexture = this._getRefractionTexture();
  44563. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44564. // Texture uniforms
  44565. if (scene.texturesEnabled) {
  44566. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44567. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44568. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44569. }
  44570. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44571. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44572. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44573. }
  44574. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44575. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44576. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44577. }
  44578. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44579. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44580. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44581. if (reflectionTexture.boundingBoxSize) {
  44582. var cubeTexture = reflectionTexture;
  44583. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44584. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44585. }
  44586. var polynomials = reflectionTexture.sphericalPolynomial;
  44587. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44588. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44589. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44590. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44591. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44592. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44593. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44594. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44595. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44596. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44597. }
  44598. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44599. }
  44600. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44601. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44602. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44603. }
  44604. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44605. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44606. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44607. }
  44608. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44609. if (this._metallicTexture) {
  44610. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44611. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44612. }
  44613. else if (this._reflectivityTexture) {
  44614. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44615. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44616. }
  44617. if (this._microSurfaceTexture) {
  44618. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44619. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44620. }
  44621. }
  44622. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44623. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44624. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44625. if (scene._mirroredCameraPosition) {
  44626. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44627. }
  44628. else {
  44629. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44630. }
  44631. }
  44632. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44633. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44634. var depth = 1.0;
  44635. if (!refractionTexture.isCube) {
  44636. if (refractionTexture.depth) {
  44637. depth = refractionTexture.depth;
  44638. }
  44639. }
  44640. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44641. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44642. }
  44643. }
  44644. // Point size
  44645. if (this.pointsCloud) {
  44646. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44647. }
  44648. // Colors
  44649. if (defines.METALLICWORKFLOW) {
  44650. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44651. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44652. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44653. }
  44654. else {
  44655. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44656. }
  44657. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44658. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44659. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44660. // Misc
  44661. this._lightingInfos.x = this._directIntensity;
  44662. this._lightingInfos.y = this._emissiveIntensity;
  44663. this._lightingInfos.z = this._environmentIntensity;
  44664. this._lightingInfos.w = this._specularIntensity;
  44665. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44666. }
  44667. // Textures
  44668. if (scene.texturesEnabled) {
  44669. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44670. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44671. }
  44672. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44673. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44674. }
  44675. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44676. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44677. }
  44678. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44679. if (defines.LODBASEDMICROSFURACE) {
  44680. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44681. }
  44682. else {
  44683. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44684. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44685. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44686. }
  44687. }
  44688. if (defines.ENVIRONMENTBRDF) {
  44689. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44690. }
  44691. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44692. if (defines.LODBASEDMICROSFURACE) {
  44693. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44694. }
  44695. else {
  44696. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44697. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44698. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44699. }
  44700. }
  44701. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44702. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44703. }
  44704. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44705. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44706. }
  44707. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44708. if (this._metallicTexture) {
  44709. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44710. }
  44711. else if (this._reflectivityTexture) {
  44712. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44713. }
  44714. if (this._microSurfaceTexture) {
  44715. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44716. }
  44717. }
  44718. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44719. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44720. }
  44721. }
  44722. // Clip plane
  44723. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44724. // Colors
  44725. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44726. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44727. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44728. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44729. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44730. }
  44731. if (mustRebind || !this.isFrozen) {
  44732. // Lights
  44733. if (scene.lightsEnabled && !this._disableLighting) {
  44734. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44735. }
  44736. // View
  44737. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44738. this.bindView(effect);
  44739. }
  44740. // Fog
  44741. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44742. // Morph targets
  44743. if (defines.NUM_MORPH_INFLUENCERS) {
  44744. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44745. }
  44746. // image processing
  44747. this._imageProcessingConfiguration.bind(this._activeEffect);
  44748. // Log. depth
  44749. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44750. }
  44751. this._uniformBuffer.update();
  44752. this._afterBind(mesh, this._activeEffect);
  44753. };
  44754. /**
  44755. * Returns the animatable textures.
  44756. * @returns - Array of animatable textures.
  44757. */
  44758. PBRBaseMaterial.prototype.getAnimatables = function () {
  44759. var results = [];
  44760. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44761. results.push(this._albedoTexture);
  44762. }
  44763. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44764. results.push(this._ambientTexture);
  44765. }
  44766. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44767. results.push(this._opacityTexture);
  44768. }
  44769. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44770. results.push(this._reflectionTexture);
  44771. }
  44772. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44773. results.push(this._emissiveTexture);
  44774. }
  44775. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44776. results.push(this._metallicTexture);
  44777. }
  44778. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44779. results.push(this._reflectivityTexture);
  44780. }
  44781. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44782. results.push(this._bumpTexture);
  44783. }
  44784. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44785. results.push(this._lightmapTexture);
  44786. }
  44787. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44788. results.push(this._refractionTexture);
  44789. }
  44790. return results;
  44791. };
  44792. /**
  44793. * Returns the texture used for reflections.
  44794. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44795. */
  44796. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44797. if (this._reflectionTexture) {
  44798. return this._reflectionTexture;
  44799. }
  44800. return this.getScene().environmentTexture;
  44801. };
  44802. /**
  44803. * Returns the texture used for refraction or null if none is used.
  44804. * @returns - Refection texture if present. If no refraction texture and refraction
  44805. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44806. */
  44807. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44808. if (this._refractionTexture) {
  44809. return this._refractionTexture;
  44810. }
  44811. if (this._linkRefractionWithTransparency) {
  44812. return this.getScene().environmentTexture;
  44813. }
  44814. return null;
  44815. };
  44816. /**
  44817. * Disposes the resources of the material.
  44818. * @param forceDisposeEffect - Forces the disposal of effects.
  44819. * @param forceDisposeTextures - Forces the disposal of all textures.
  44820. */
  44821. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44822. if (forceDisposeTextures) {
  44823. if (this._albedoTexture) {
  44824. this._albedoTexture.dispose();
  44825. }
  44826. if (this._ambientTexture) {
  44827. this._ambientTexture.dispose();
  44828. }
  44829. if (this._opacityTexture) {
  44830. this._opacityTexture.dispose();
  44831. }
  44832. if (this._reflectionTexture) {
  44833. this._reflectionTexture.dispose();
  44834. }
  44835. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44836. this._environmentBRDFTexture.dispose();
  44837. }
  44838. if (this._emissiveTexture) {
  44839. this._emissiveTexture.dispose();
  44840. }
  44841. if (this._metallicTexture) {
  44842. this._metallicTexture.dispose();
  44843. }
  44844. if (this._reflectivityTexture) {
  44845. this._reflectivityTexture.dispose();
  44846. }
  44847. if (this._bumpTexture) {
  44848. this._bumpTexture.dispose();
  44849. }
  44850. if (this._lightmapTexture) {
  44851. this._lightmapTexture.dispose();
  44852. }
  44853. if (this._refractionTexture) {
  44854. this._refractionTexture.dispose();
  44855. }
  44856. }
  44857. this._renderTargets.dispose();
  44858. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44859. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44860. }
  44861. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44862. };
  44863. /**
  44864. * Stores the reflectivity values based on metallic roughness workflow.
  44865. */
  44866. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44867. __decorate([
  44868. BABYLON.serializeAsImageProcessingConfiguration()
  44869. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44870. __decorate([
  44871. BABYLON.serialize()
  44872. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44873. __decorate([
  44874. BABYLON.serialize()
  44875. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44876. return PBRBaseMaterial;
  44877. }(BABYLON.PushMaterial));
  44878. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44879. })(BABYLON || (BABYLON = {}));
  44880. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44881. var BABYLON;
  44882. (function (BABYLON) {
  44883. /**
  44884. * The Physically based simple base material of BJS.
  44885. *
  44886. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44887. * It is used as the base class for both the specGloss and metalRough conventions.
  44888. */
  44889. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44890. __extends(PBRBaseSimpleMaterial, _super);
  44891. /**
  44892. * Instantiates a new PBRMaterial instance.
  44893. *
  44894. * @param name The material name
  44895. * @param scene The scene the material will be use in.
  44896. */
  44897. function PBRBaseSimpleMaterial(name, scene) {
  44898. var _this = _super.call(this, name, scene) || this;
  44899. /**
  44900. * Number of Simultaneous lights allowed on the material.
  44901. */
  44902. _this.maxSimultaneousLights = 4;
  44903. /**
  44904. * If sets to true, disables all the lights affecting the material.
  44905. */
  44906. _this.disableLighting = false;
  44907. /**
  44908. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44909. */
  44910. _this.invertNormalMapX = false;
  44911. /**
  44912. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44913. */
  44914. _this.invertNormalMapY = false;
  44915. /**
  44916. * Emissivie color used to self-illuminate the model.
  44917. */
  44918. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44919. /**
  44920. * Occlusion Channel Strenght.
  44921. */
  44922. _this.occlusionStrength = 1.0;
  44923. _this.useLightmapAsShadowmap = false;
  44924. _this._useAlphaFromAlbedoTexture = true;
  44925. _this._useAmbientInGrayScale = true;
  44926. return _this;
  44927. }
  44928. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44929. /**
  44930. * Gets the current double sided mode.
  44931. */
  44932. get: function () {
  44933. return this._twoSidedLighting;
  44934. },
  44935. /**
  44936. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44937. */
  44938. set: function (value) {
  44939. if (this._twoSidedLighting === value) {
  44940. return;
  44941. }
  44942. this._twoSidedLighting = value;
  44943. this.backFaceCulling = !value;
  44944. this._markAllSubMeshesAsTexturesDirty();
  44945. },
  44946. enumerable: true,
  44947. configurable: true
  44948. });
  44949. /**
  44950. * Return the active textures of the material.
  44951. */
  44952. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44953. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44954. if (this.environmentTexture) {
  44955. activeTextures.push(this.environmentTexture);
  44956. }
  44957. if (this.normalTexture) {
  44958. activeTextures.push(this.normalTexture);
  44959. }
  44960. if (this.emissiveTexture) {
  44961. activeTextures.push(this.emissiveTexture);
  44962. }
  44963. if (this.occlusionTexture) {
  44964. activeTextures.push(this.occlusionTexture);
  44965. }
  44966. if (this.lightmapTexture) {
  44967. activeTextures.push(this.lightmapTexture);
  44968. }
  44969. return activeTextures;
  44970. };
  44971. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44972. if (_super.prototype.hasTexture.call(this, texture)) {
  44973. return true;
  44974. }
  44975. if (this.lightmapTexture === texture) {
  44976. return true;
  44977. }
  44978. return false;
  44979. };
  44980. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44981. return "PBRBaseSimpleMaterial";
  44982. };
  44983. __decorate([
  44984. BABYLON.serialize(),
  44985. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44986. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44987. __decorate([
  44988. BABYLON.serialize(),
  44989. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44990. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44991. __decorate([
  44992. BABYLON.serializeAsTexture(),
  44993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44994. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44995. __decorate([
  44996. BABYLON.serialize(),
  44997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44998. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44999. __decorate([
  45000. BABYLON.serialize(),
  45001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45002. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45003. __decorate([
  45004. BABYLON.serializeAsTexture(),
  45005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45006. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45007. __decorate([
  45008. BABYLON.serializeAsColor3("emissive"),
  45009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45010. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45011. __decorate([
  45012. BABYLON.serializeAsTexture(),
  45013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45014. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45015. __decorate([
  45016. BABYLON.serialize(),
  45017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45018. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45019. __decorate([
  45020. BABYLON.serializeAsTexture(),
  45021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45022. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45023. __decorate([
  45024. BABYLON.serialize(),
  45025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45026. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45027. __decorate([
  45028. BABYLON.serialize()
  45029. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45030. __decorate([
  45031. BABYLON.serializeAsTexture(),
  45032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45033. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45034. __decorate([
  45035. BABYLON.serialize(),
  45036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45037. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45038. return PBRBaseSimpleMaterial;
  45039. }(BABYLON.PBRBaseMaterial));
  45040. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45041. })(BABYLON || (BABYLON = {}));
  45042. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45043. var BABYLON;
  45044. (function (BABYLON) {
  45045. /**
  45046. * The Physically based material of BJS.
  45047. *
  45048. * This offers the main features of a standard PBR material.
  45049. * For more information, please refer to the documentation :
  45050. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45051. */
  45052. var PBRMaterial = /** @class */ (function (_super) {
  45053. __extends(PBRMaterial, _super);
  45054. /**
  45055. * Instantiates a new PBRMaterial instance.
  45056. *
  45057. * @param name The material name
  45058. * @param scene The scene the material will be use in.
  45059. */
  45060. function PBRMaterial(name, scene) {
  45061. var _this = _super.call(this, name, scene) || this;
  45062. /**
  45063. * Intensity of the direct lights e.g. the four lights available in your scene.
  45064. * This impacts both the direct diffuse and specular highlights.
  45065. */
  45066. _this.directIntensity = 1.0;
  45067. /**
  45068. * Intensity of the emissive part of the material.
  45069. * This helps controlling the emissive effect without modifying the emissive color.
  45070. */
  45071. _this.emissiveIntensity = 1.0;
  45072. /**
  45073. * Intensity of the environment e.g. how much the environment will light the object
  45074. * either through harmonics for rough material or through the refelction for shiny ones.
  45075. */
  45076. _this.environmentIntensity = 1.0;
  45077. /**
  45078. * This is a special control allowing the reduction of the specular highlights coming from the
  45079. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45080. */
  45081. _this.specularIntensity = 1.0;
  45082. /**
  45083. * Debug Control allowing disabling the bump map on this material.
  45084. */
  45085. _this.disableBumpMap = false;
  45086. /**
  45087. * AKA Occlusion Texture Intensity in other nomenclature.
  45088. */
  45089. _this.ambientTextureStrength = 1.0;
  45090. /**
  45091. * The color of a material in ambient lighting.
  45092. */
  45093. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45094. /**
  45095. * AKA Diffuse Color in other nomenclature.
  45096. */
  45097. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45098. /**
  45099. * AKA Specular Color in other nomenclature.
  45100. */
  45101. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45102. /**
  45103. * The color reflected from the material.
  45104. */
  45105. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45106. /**
  45107. * The color emitted from the material.
  45108. */
  45109. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45110. /**
  45111. * AKA Glossiness in other nomenclature.
  45112. */
  45113. _this.microSurface = 1.0;
  45114. /**
  45115. * source material index of refraction (IOR)' / 'destination material IOR.
  45116. */
  45117. _this.indexOfRefraction = 0.66;
  45118. /**
  45119. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45120. */
  45121. _this.invertRefractionY = false;
  45122. /**
  45123. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45124. * Materials half opaque for instance using refraction could benefit from this control.
  45125. */
  45126. _this.linkRefractionWithTransparency = false;
  45127. _this.useLightmapAsShadowmap = false;
  45128. /**
  45129. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45130. */
  45131. _this.useAlphaFromAlbedoTexture = false;
  45132. /**
  45133. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45134. */
  45135. _this.forceAlphaTest = false;
  45136. /**
  45137. * Defines the alpha limits in alpha test mode.
  45138. */
  45139. _this.alphaCutOff = 0.4;
  45140. /**
  45141. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45142. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45143. */
  45144. _this.useSpecularOverAlpha = true;
  45145. /**
  45146. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45147. */
  45148. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45149. /**
  45150. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45151. */
  45152. _this.useRoughnessFromMetallicTextureAlpha = true;
  45153. /**
  45154. * Specifies if the metallic texture contains the roughness information in its green channel.
  45155. */
  45156. _this.useRoughnessFromMetallicTextureGreen = false;
  45157. /**
  45158. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45159. */
  45160. _this.useMetallnessFromMetallicTextureBlue = false;
  45161. /**
  45162. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45163. */
  45164. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45165. /**
  45166. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45167. */
  45168. _this.useAmbientInGrayScale = false;
  45169. /**
  45170. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45171. * The material will try to infer what glossiness each pixel should be.
  45172. */
  45173. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45174. /**
  45175. * BJS is using an harcoded light falloff based on a manually sets up range.
  45176. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45177. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45178. */
  45179. _this.usePhysicalLightFalloff = true;
  45180. /**
  45181. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45182. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45183. */
  45184. _this.useRadianceOverAlpha = true;
  45185. /**
  45186. * Allows using an object space normal map (instead of tangent space).
  45187. */
  45188. _this.useObjectSpaceNormalMap = false;
  45189. /**
  45190. * Allows using the bump map in parallax mode.
  45191. */
  45192. _this.useParallax = false;
  45193. /**
  45194. * Allows using the bump map in parallax occlusion mode.
  45195. */
  45196. _this.useParallaxOcclusion = false;
  45197. /**
  45198. * Controls the scale bias of the parallax mode.
  45199. */
  45200. _this.parallaxScaleBias = 0.05;
  45201. /**
  45202. * If sets to true, disables all the lights affecting the material.
  45203. */
  45204. _this.disableLighting = false;
  45205. /**
  45206. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45207. */
  45208. _this.forceIrradianceInFragment = false;
  45209. /**
  45210. * Number of Simultaneous lights allowed on the material.
  45211. */
  45212. _this.maxSimultaneousLights = 4;
  45213. /**
  45214. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45215. */
  45216. _this.invertNormalMapX = false;
  45217. /**
  45218. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45219. */
  45220. _this.invertNormalMapY = false;
  45221. /**
  45222. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45223. */
  45224. _this.twoSidedLighting = false;
  45225. /**
  45226. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45227. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45228. */
  45229. _this.useAlphaFresnel = false;
  45230. /**
  45231. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45232. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45233. */
  45234. _this.useLinearAlphaFresnel = false;
  45235. /**
  45236. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45237. * And/Or occlude the blended part.
  45238. */
  45239. _this.environmentBRDFTexture = null;
  45240. /**
  45241. * Force normal to face away from face.
  45242. */
  45243. _this.forceNormalForward = false;
  45244. /**
  45245. * Enables specular anti aliasing in the PBR shader.
  45246. * It will both interacts on the Geometry for analytical and IBL lighting.
  45247. * It also prefilter the roughness map based on the bump values.
  45248. */
  45249. _this.enableSpecularAntiAliasing = false;
  45250. /**
  45251. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45252. * makes the reflect vector face the model (under horizon).
  45253. */
  45254. _this.useHorizonOcclusion = true;
  45255. /**
  45256. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45257. * too much the area relying on ambient texture to define their ambient occlusion.
  45258. */
  45259. _this.useRadianceOcclusion = true;
  45260. /**
  45261. * If set to true, no lighting calculations will be applied.
  45262. */
  45263. _this.unlit = false;
  45264. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45265. return _this;
  45266. }
  45267. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45268. /**
  45269. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45270. */
  45271. get: function () {
  45272. return this._PBRMATERIAL_OPAQUE;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45278. /**
  45279. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45280. */
  45281. get: function () {
  45282. return this._PBRMATERIAL_ALPHATEST;
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45288. /**
  45289. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45290. */
  45291. get: function () {
  45292. return this._PBRMATERIAL_ALPHABLEND;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45298. /**
  45299. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45300. * They are also discarded below the alpha cutoff threshold to improve performances.
  45301. */
  45302. get: function () {
  45303. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45304. },
  45305. enumerable: true,
  45306. configurable: true
  45307. });
  45308. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45309. /**
  45310. * Gets the image processing configuration used either in this material.
  45311. */
  45312. get: function () {
  45313. return this._imageProcessingConfiguration;
  45314. },
  45315. /**
  45316. * Sets the Default image processing configuration used either in the this material.
  45317. *
  45318. * If sets to null, the scene one is in use.
  45319. */
  45320. set: function (value) {
  45321. this._attachImageProcessingConfiguration(value);
  45322. // Ensure the effect will be rebuilt.
  45323. this._markAllSubMeshesAsTexturesDirty();
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45329. /**
  45330. * Gets wether the color curves effect is enabled.
  45331. */
  45332. get: function () {
  45333. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45334. },
  45335. /**
  45336. * Sets wether the color curves effect is enabled.
  45337. */
  45338. set: function (value) {
  45339. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45340. },
  45341. enumerable: true,
  45342. configurable: true
  45343. });
  45344. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45345. /**
  45346. * Gets wether the color grading effect is enabled.
  45347. */
  45348. get: function () {
  45349. return this.imageProcessingConfiguration.colorGradingEnabled;
  45350. },
  45351. /**
  45352. * Gets wether the color grading effect is enabled.
  45353. */
  45354. set: function (value) {
  45355. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45356. },
  45357. enumerable: true,
  45358. configurable: true
  45359. });
  45360. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45361. /**
  45362. * Gets wether tonemapping is enabled or not.
  45363. */
  45364. get: function () {
  45365. return this._imageProcessingConfiguration.toneMappingEnabled;
  45366. },
  45367. /**
  45368. * Sets wether tonemapping is enabled or not
  45369. */
  45370. set: function (value) {
  45371. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45372. },
  45373. enumerable: true,
  45374. configurable: true
  45375. });
  45376. ;
  45377. ;
  45378. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45379. /**
  45380. * The camera exposure used on this material.
  45381. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45382. * This corresponds to a photographic exposure.
  45383. */
  45384. get: function () {
  45385. return this._imageProcessingConfiguration.exposure;
  45386. },
  45387. /**
  45388. * The camera exposure used on this material.
  45389. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45390. * This corresponds to a photographic exposure.
  45391. */
  45392. set: function (value) {
  45393. this._imageProcessingConfiguration.exposure = value;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. ;
  45399. ;
  45400. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45401. /**
  45402. * Gets The camera contrast used on this material.
  45403. */
  45404. get: function () {
  45405. return this._imageProcessingConfiguration.contrast;
  45406. },
  45407. /**
  45408. * Sets The camera contrast used on this material.
  45409. */
  45410. set: function (value) {
  45411. this._imageProcessingConfiguration.contrast = value;
  45412. },
  45413. enumerable: true,
  45414. configurable: true
  45415. });
  45416. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45417. /**
  45418. * Gets the Color Grading 2D Lookup Texture.
  45419. */
  45420. get: function () {
  45421. return this._imageProcessingConfiguration.colorGradingTexture;
  45422. },
  45423. /**
  45424. * Sets the Color Grading 2D Lookup Texture.
  45425. */
  45426. set: function (value) {
  45427. this._imageProcessingConfiguration.colorGradingTexture = value;
  45428. },
  45429. enumerable: true,
  45430. configurable: true
  45431. });
  45432. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45433. /**
  45434. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45435. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45436. * 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;
  45437. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45438. */
  45439. get: function () {
  45440. return this._imageProcessingConfiguration.colorCurves;
  45441. },
  45442. /**
  45443. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45444. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45445. * 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;
  45446. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45447. */
  45448. set: function (value) {
  45449. this._imageProcessingConfiguration.colorCurves = value;
  45450. },
  45451. enumerable: true,
  45452. configurable: true
  45453. });
  45454. /**
  45455. * Returns the name of this material class.
  45456. */
  45457. PBRMaterial.prototype.getClassName = function () {
  45458. return "PBRMaterial";
  45459. };
  45460. /**
  45461. * Returns an array of the actively used textures.
  45462. * @returns - Array of BaseTextures
  45463. */
  45464. PBRMaterial.prototype.getActiveTextures = function () {
  45465. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45466. if (this._albedoTexture) {
  45467. activeTextures.push(this._albedoTexture);
  45468. }
  45469. if (this._ambientTexture) {
  45470. activeTextures.push(this._ambientTexture);
  45471. }
  45472. if (this._opacityTexture) {
  45473. activeTextures.push(this._opacityTexture);
  45474. }
  45475. if (this._reflectionTexture) {
  45476. activeTextures.push(this._reflectionTexture);
  45477. }
  45478. if (this._emissiveTexture) {
  45479. activeTextures.push(this._emissiveTexture);
  45480. }
  45481. if (this._reflectivityTexture) {
  45482. activeTextures.push(this._reflectivityTexture);
  45483. }
  45484. if (this._metallicTexture) {
  45485. activeTextures.push(this._metallicTexture);
  45486. }
  45487. if (this._microSurfaceTexture) {
  45488. activeTextures.push(this._microSurfaceTexture);
  45489. }
  45490. if (this._bumpTexture) {
  45491. activeTextures.push(this._bumpTexture);
  45492. }
  45493. if (this._lightmapTexture) {
  45494. activeTextures.push(this._lightmapTexture);
  45495. }
  45496. if (this._refractionTexture) {
  45497. activeTextures.push(this._refractionTexture);
  45498. }
  45499. return activeTextures;
  45500. };
  45501. /**
  45502. * Checks to see if a texture is used in the material.
  45503. * @param texture - Base texture to use.
  45504. * @returns - Boolean specifying if a texture is used in the material.
  45505. */
  45506. PBRMaterial.prototype.hasTexture = function (texture) {
  45507. if (_super.prototype.hasTexture.call(this, texture)) {
  45508. return true;
  45509. }
  45510. if (this._albedoTexture === texture) {
  45511. return true;
  45512. }
  45513. if (this._ambientTexture === texture) {
  45514. return true;
  45515. }
  45516. if (this._opacityTexture === texture) {
  45517. return true;
  45518. }
  45519. if (this._reflectionTexture === texture) {
  45520. return true;
  45521. }
  45522. if (this._reflectivityTexture === texture) {
  45523. return true;
  45524. }
  45525. if (this._metallicTexture === texture) {
  45526. return true;
  45527. }
  45528. if (this._microSurfaceTexture === texture) {
  45529. return true;
  45530. }
  45531. if (this._bumpTexture === texture) {
  45532. return true;
  45533. }
  45534. if (this._lightmapTexture === texture) {
  45535. return true;
  45536. }
  45537. if (this._refractionTexture === texture) {
  45538. return true;
  45539. }
  45540. return false;
  45541. };
  45542. /**
  45543. * Makes a duplicate of the current material.
  45544. * @param name - name to use for the new material.
  45545. */
  45546. PBRMaterial.prototype.clone = function (name) {
  45547. var _this = this;
  45548. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45549. clone.id = name;
  45550. clone.name = name;
  45551. return clone;
  45552. };
  45553. /**
  45554. * Serializes this PBR Material.
  45555. * @returns - An object with the serialized material.
  45556. */
  45557. PBRMaterial.prototype.serialize = function () {
  45558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45559. serializationObject.customType = "BABYLON.PBRMaterial";
  45560. return serializationObject;
  45561. };
  45562. // Statics
  45563. /**
  45564. * Parses a PBR Material from a serialized object.
  45565. * @param source - Serialized object.
  45566. * @param scene - BJS scene instance.
  45567. * @param rootUrl - url for the scene object
  45568. * @returns - PBRMaterial
  45569. */
  45570. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45571. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45572. };
  45573. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45574. /**
  45575. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45576. */
  45577. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45578. /**
  45579. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45580. */
  45581. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45582. /**
  45583. * 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.
  45584. * They are also discarded below the alpha cutoff threshold to improve performances.
  45585. */
  45586. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "directIntensity", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsTexture(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45611. __decorate([
  45612. BABYLON.serializeAsTexture(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45619. __decorate([
  45620. BABYLON.serializeAsTexture(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45622. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45623. __decorate([
  45624. BABYLON.serializeAsTexture(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45627. __decorate([
  45628. BABYLON.serializeAsTexture(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45631. __decorate([
  45632. BABYLON.serializeAsTexture(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45635. __decorate([
  45636. BABYLON.serializeAsTexture(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "metallic", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "roughness", void 0);
  45647. __decorate([
  45648. BABYLON.serializeAsTexture(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45651. __decorate([
  45652. BABYLON.serializeAsTexture(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45655. __decorate([
  45656. BABYLON.serializeAsTexture(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45658. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45659. __decorate([
  45660. BABYLON.serializeAsTexture(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45663. __decorate([
  45664. BABYLON.serializeAsColor3("ambient"),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "ambientColor", void 0);
  45667. __decorate([
  45668. BABYLON.serializeAsColor3("albedo"),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "albedoColor", void 0);
  45671. __decorate([
  45672. BABYLON.serializeAsColor3("reflectivity"),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45675. __decorate([
  45676. BABYLON.serializeAsColor3("reflection"),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45679. __decorate([
  45680. BABYLON.serializeAsColor3("emissive"),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMaterial.prototype, "microSurface", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45690. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45698. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45706. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45707. __decorate([
  45708. BABYLON.serialize(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45710. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45714. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45718. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45722. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45723. __decorate([
  45724. BABYLON.serialize(),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45726. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45730. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45731. __decorate([
  45732. BABYLON.serialize(),
  45733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45734. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45735. __decorate([
  45736. BABYLON.serialize(),
  45737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45738. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45739. __decorate([
  45740. BABYLON.serialize(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45742. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45743. __decorate([
  45744. BABYLON.serialize(),
  45745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45746. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45747. __decorate([
  45748. BABYLON.serialize(),
  45749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45750. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45751. __decorate([
  45752. BABYLON.serialize(),
  45753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45754. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45755. __decorate([
  45756. BABYLON.serialize(),
  45757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45758. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45759. __decorate([
  45760. BABYLON.serialize(),
  45761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45762. ], PBRMaterial.prototype, "useParallax", void 0);
  45763. __decorate([
  45764. BABYLON.serialize(),
  45765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45766. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45767. __decorate([
  45768. BABYLON.serialize(),
  45769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45770. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45771. __decorate([
  45772. BABYLON.serialize(),
  45773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45774. ], PBRMaterial.prototype, "disableLighting", void 0);
  45775. __decorate([
  45776. BABYLON.serialize(),
  45777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45778. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45779. __decorate([
  45780. BABYLON.serialize(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45782. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45783. __decorate([
  45784. BABYLON.serialize(),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45787. __decorate([
  45788. BABYLON.serialize(),
  45789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45790. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45791. __decorate([
  45792. BABYLON.serialize(),
  45793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45794. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45795. __decorate([
  45796. BABYLON.serialize(),
  45797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45798. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45799. __decorate([
  45800. BABYLON.serialize(),
  45801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45802. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45803. __decorate([
  45804. BABYLON.serializeAsTexture(),
  45805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45806. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45807. __decorate([
  45808. BABYLON.serialize(),
  45809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45810. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45811. __decorate([
  45812. BABYLON.serialize(),
  45813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45814. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45815. __decorate([
  45816. BABYLON.serialize(),
  45817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45818. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45819. __decorate([
  45820. BABYLON.serialize(),
  45821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45822. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45823. __decorate([
  45824. BABYLON.serialize(),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45826. ], PBRMaterial.prototype, "unlit", void 0);
  45827. return PBRMaterial;
  45828. }(BABYLON.PBRBaseMaterial));
  45829. BABYLON.PBRMaterial = PBRMaterial;
  45830. })(BABYLON || (BABYLON = {}));
  45831. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45832. var BABYLON;
  45833. (function (BABYLON) {
  45834. /**
  45835. * The PBR material of BJS following the metal roughness convention.
  45836. *
  45837. * This fits to the PBR convention in the GLTF definition:
  45838. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45839. */
  45840. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45841. __extends(PBRMetallicRoughnessMaterial, _super);
  45842. /**
  45843. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45844. *
  45845. * @param name The material name
  45846. * @param scene The scene the material will be use in.
  45847. */
  45848. function PBRMetallicRoughnessMaterial(name, scene) {
  45849. var _this = _super.call(this, name, scene) || this;
  45850. _this._useRoughnessFromMetallicTextureAlpha = false;
  45851. _this._useRoughnessFromMetallicTextureGreen = true;
  45852. _this._useMetallnessFromMetallicTextureBlue = true;
  45853. _this.metallic = 1.0;
  45854. _this.roughness = 1.0;
  45855. return _this;
  45856. }
  45857. /**
  45858. * Return the currrent class name of the material.
  45859. */
  45860. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45861. return "PBRMetallicRoughnessMaterial";
  45862. };
  45863. /**
  45864. * Return the active textures of the material.
  45865. */
  45866. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45867. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45868. if (this.baseTexture) {
  45869. activeTextures.push(this.baseTexture);
  45870. }
  45871. if (this.metallicRoughnessTexture) {
  45872. activeTextures.push(this.metallicRoughnessTexture);
  45873. }
  45874. return activeTextures;
  45875. };
  45876. /**
  45877. * Checks to see if a texture is used in the material.
  45878. * @param texture - Base texture to use.
  45879. * @returns - Boolean specifying if a texture is used in the material.
  45880. */
  45881. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45882. if (_super.prototype.hasTexture.call(this, texture)) {
  45883. return true;
  45884. }
  45885. if (this.baseTexture === texture) {
  45886. return true;
  45887. }
  45888. if (this.metallicRoughnessTexture === texture) {
  45889. return true;
  45890. }
  45891. return false;
  45892. };
  45893. /**
  45894. * Makes a duplicate of the current material.
  45895. * @param name - name to use for the new material.
  45896. */
  45897. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45898. var _this = this;
  45899. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45900. clone.id = name;
  45901. clone.name = name;
  45902. return clone;
  45903. };
  45904. /**
  45905. * Serialize the material to a parsable JSON object.
  45906. */
  45907. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45908. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45909. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45910. return serializationObject;
  45911. };
  45912. /**
  45913. * Parses a JSON object correponding to the serialize function.
  45914. */
  45915. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45916. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45917. };
  45918. __decorate([
  45919. BABYLON.serializeAsColor3(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45921. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsTexture(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45925. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45930. __decorate([
  45931. BABYLON.serialize(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45933. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45934. __decorate([
  45935. BABYLON.serializeAsTexture(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45937. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45938. return PBRMetallicRoughnessMaterial;
  45939. }(BABYLON.PBRBaseSimpleMaterial));
  45940. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45941. })(BABYLON || (BABYLON = {}));
  45942. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45943. var BABYLON;
  45944. (function (BABYLON) {
  45945. /**
  45946. * The PBR material of BJS following the specular glossiness convention.
  45947. *
  45948. * This fits to the PBR convention in the GLTF definition:
  45949. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45950. */
  45951. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45952. __extends(PBRSpecularGlossinessMaterial, _super);
  45953. /**
  45954. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45955. *
  45956. * @param name The material name
  45957. * @param scene The scene the material will be use in.
  45958. */
  45959. function PBRSpecularGlossinessMaterial(name, scene) {
  45960. var _this = _super.call(this, name, scene) || this;
  45961. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45962. return _this;
  45963. }
  45964. /**
  45965. * Return the currrent class name of the material.
  45966. */
  45967. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45968. return "PBRSpecularGlossinessMaterial";
  45969. };
  45970. /**
  45971. * Return the active textures of the material.
  45972. */
  45973. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45975. if (this.diffuseTexture) {
  45976. activeTextures.push(this.diffuseTexture);
  45977. }
  45978. if (this.specularGlossinessTexture) {
  45979. activeTextures.push(this.specularGlossinessTexture);
  45980. }
  45981. return activeTextures;
  45982. };
  45983. /**
  45984. * Checks to see if a texture is used in the material.
  45985. * @param texture - Base texture to use.
  45986. * @returns - Boolean specifying if a texture is used in the material.
  45987. */
  45988. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45989. if (_super.prototype.hasTexture.call(this, texture)) {
  45990. return true;
  45991. }
  45992. if (this.diffuseTexture === texture) {
  45993. return true;
  45994. }
  45995. if (this.specularGlossinessTexture === texture) {
  45996. return true;
  45997. }
  45998. return false;
  45999. };
  46000. /**
  46001. * Makes a duplicate of the current material.
  46002. * @param name - name to use for the new material.
  46003. */
  46004. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46005. var _this = this;
  46006. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46007. clone.id = name;
  46008. clone.name = name;
  46009. return clone;
  46010. };
  46011. /**
  46012. * Serialize the material to a parsable JSON object.
  46013. */
  46014. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46015. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46016. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46017. return serializationObject;
  46018. };
  46019. /**
  46020. * Parses a JSON object correponding to the serialize function.
  46021. */
  46022. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46023. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46024. };
  46025. __decorate([
  46026. BABYLON.serializeAsColor3("diffuse"),
  46027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46028. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46029. __decorate([
  46030. BABYLON.serializeAsTexture(),
  46031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46032. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46033. __decorate([
  46034. BABYLON.serializeAsColor3("specular"),
  46035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46036. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46037. __decorate([
  46038. BABYLON.serialize(),
  46039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46040. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46041. __decorate([
  46042. BABYLON.serializeAsTexture(),
  46043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46044. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46045. return PBRSpecularGlossinessMaterial;
  46046. }(BABYLON.PBRBaseSimpleMaterial));
  46047. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46048. })(BABYLON || (BABYLON = {}));
  46049. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46050. var BABYLON;
  46051. (function (BABYLON) {
  46052. BABYLON.CameraInputTypes = {};
  46053. var CameraInputsManager = /** @class */ (function () {
  46054. function CameraInputsManager(camera) {
  46055. this.attached = {};
  46056. this.camera = camera;
  46057. this.checkInputs = function () { };
  46058. }
  46059. /**
  46060. * Add an input method to a camera.
  46061. * builtin inputs example: camera.inputs.addGamepad();
  46062. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46063. * @param input camera input method
  46064. */
  46065. CameraInputsManager.prototype.add = function (input) {
  46066. var type = input.getSimpleName();
  46067. if (this.attached[type]) {
  46068. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46069. return;
  46070. }
  46071. this.attached[type] = input;
  46072. input.camera = this.camera;
  46073. //for checkInputs, we are dynamically creating a function
  46074. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46075. if (input.checkInputs) {
  46076. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46077. }
  46078. if (this.attachedElement) {
  46079. input.attachControl(this.attachedElement);
  46080. }
  46081. };
  46082. /**
  46083. * Remove a specific input method from a camera
  46084. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46085. * @param inputToRemove camera input method
  46086. */
  46087. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46088. for (var cam in this.attached) {
  46089. var input = this.attached[cam];
  46090. if (input === inputToRemove) {
  46091. input.detachControl(this.attachedElement);
  46092. input.camera = null;
  46093. delete this.attached[cam];
  46094. this.rebuildInputCheck();
  46095. }
  46096. }
  46097. };
  46098. CameraInputsManager.prototype.removeByType = function (inputType) {
  46099. for (var cam in this.attached) {
  46100. var input = this.attached[cam];
  46101. if (input.getClassName() === inputType) {
  46102. input.detachControl(this.attachedElement);
  46103. input.camera = null;
  46104. delete this.attached[cam];
  46105. this.rebuildInputCheck();
  46106. }
  46107. }
  46108. };
  46109. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46110. var current = this.checkInputs;
  46111. return function () {
  46112. current();
  46113. fn();
  46114. };
  46115. };
  46116. CameraInputsManager.prototype.attachInput = function (input) {
  46117. if (this.attachedElement) {
  46118. input.attachControl(this.attachedElement, this.noPreventDefault);
  46119. }
  46120. };
  46121. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46122. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46123. if (this.attachedElement) {
  46124. return;
  46125. }
  46126. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46127. this.attachedElement = element;
  46128. this.noPreventDefault = noPreventDefault;
  46129. for (var cam in this.attached) {
  46130. this.attached[cam].attachControl(element, noPreventDefault);
  46131. }
  46132. };
  46133. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46134. if (disconnect === void 0) { disconnect = false; }
  46135. if (this.attachedElement !== element) {
  46136. return;
  46137. }
  46138. for (var cam in this.attached) {
  46139. this.attached[cam].detachControl(element);
  46140. if (disconnect) {
  46141. this.attached[cam].camera = null;
  46142. }
  46143. }
  46144. this.attachedElement = null;
  46145. };
  46146. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46147. this.checkInputs = function () { };
  46148. for (var cam in this.attached) {
  46149. var input = this.attached[cam];
  46150. if (input.checkInputs) {
  46151. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46152. }
  46153. }
  46154. };
  46155. /**
  46156. * Remove all attached input methods from a camera
  46157. */
  46158. CameraInputsManager.prototype.clear = function () {
  46159. if (this.attachedElement) {
  46160. this.detachElement(this.attachedElement, true);
  46161. }
  46162. this.attached = {};
  46163. this.attachedElement = null;
  46164. this.checkInputs = function () { };
  46165. };
  46166. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46167. var inputs = {};
  46168. for (var cam in this.attached) {
  46169. var input = this.attached[cam];
  46170. var res = BABYLON.SerializationHelper.Serialize(input);
  46171. inputs[input.getClassName()] = res;
  46172. }
  46173. serializedCamera.inputsmgr = inputs;
  46174. };
  46175. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46176. var parsedInputs = parsedCamera.inputsmgr;
  46177. if (parsedInputs) {
  46178. this.clear();
  46179. for (var n in parsedInputs) {
  46180. var construct = BABYLON.CameraInputTypes[n];
  46181. if (construct) {
  46182. var parsedinput = parsedInputs[n];
  46183. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46184. this.add(input);
  46185. }
  46186. }
  46187. }
  46188. else {
  46189. //2016-03-08 this part is for managing backward compatibility
  46190. for (var n in this.attached) {
  46191. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46192. if (construct) {
  46193. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46194. this.remove(this.attached[n]);
  46195. this.add(input);
  46196. }
  46197. }
  46198. }
  46199. };
  46200. return CameraInputsManager;
  46201. }());
  46202. BABYLON.CameraInputsManager = CameraInputsManager;
  46203. })(BABYLON || (BABYLON = {}));
  46204. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46205. var BABYLON;
  46206. (function (BABYLON) {
  46207. var TargetCamera = /** @class */ (function (_super) {
  46208. __extends(TargetCamera, _super);
  46209. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46210. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46211. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46212. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46213. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46214. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46215. _this.speed = 2.0;
  46216. _this.noRotationConstraint = false;
  46217. _this.lockedTarget = null;
  46218. _this._currentTarget = BABYLON.Vector3.Zero();
  46219. _this._viewMatrix = BABYLON.Matrix.Zero();
  46220. _this._camMatrix = BABYLON.Matrix.Zero();
  46221. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46222. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46223. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46224. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46225. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46226. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46227. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46228. return _this;
  46229. }
  46230. TargetCamera.prototype.getFrontPosition = function (distance) {
  46231. this.getWorldMatrix();
  46232. var direction = this.getTarget().subtract(this.position);
  46233. direction.normalize();
  46234. direction.scaleInPlace(distance);
  46235. return this.globalPosition.add(direction);
  46236. };
  46237. TargetCamera.prototype._getLockedTargetPosition = function () {
  46238. if (!this.lockedTarget) {
  46239. return null;
  46240. }
  46241. if (this.lockedTarget.absolutePosition) {
  46242. this.lockedTarget.computeWorldMatrix();
  46243. }
  46244. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46245. };
  46246. TargetCamera.prototype.storeState = function () {
  46247. this._storedPosition = this.position.clone();
  46248. this._storedRotation = this.rotation.clone();
  46249. if (this.rotationQuaternion) {
  46250. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46251. }
  46252. return _super.prototype.storeState.call(this);
  46253. };
  46254. /**
  46255. * Restored camera state. You must call storeState() first
  46256. */
  46257. TargetCamera.prototype._restoreStateValues = function () {
  46258. if (!_super.prototype._restoreStateValues.call(this)) {
  46259. return false;
  46260. }
  46261. this.position = this._storedPosition.clone();
  46262. this.rotation = this._storedRotation.clone();
  46263. if (this.rotationQuaternion) {
  46264. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46265. }
  46266. this.cameraDirection.copyFromFloats(0, 0, 0);
  46267. this.cameraRotation.copyFromFloats(0, 0);
  46268. return true;
  46269. };
  46270. // Cache
  46271. TargetCamera.prototype._initCache = function () {
  46272. _super.prototype._initCache.call(this);
  46273. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46274. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46275. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46276. };
  46277. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46278. if (!ignoreParentClass) {
  46279. _super.prototype._updateCache.call(this);
  46280. }
  46281. var lockedTargetPosition = this._getLockedTargetPosition();
  46282. if (!lockedTargetPosition) {
  46283. this._cache.lockedTarget = null;
  46284. }
  46285. else {
  46286. if (!this._cache.lockedTarget) {
  46287. this._cache.lockedTarget = lockedTargetPosition.clone();
  46288. }
  46289. else {
  46290. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46291. }
  46292. }
  46293. this._cache.rotation.copyFrom(this.rotation);
  46294. if (this.rotationQuaternion)
  46295. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46296. };
  46297. // Synchronized
  46298. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46299. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46300. return false;
  46301. }
  46302. var lockedTargetPosition = this._getLockedTargetPosition();
  46303. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46304. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46305. };
  46306. // Methods
  46307. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46308. var engine = this.getEngine();
  46309. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46310. };
  46311. // Target
  46312. TargetCamera.prototype.setTarget = function (target) {
  46313. this.upVector.normalize();
  46314. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46315. this._camMatrix.invert();
  46316. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46317. var vDir = target.subtract(this.position);
  46318. if (vDir.x >= 0.0) {
  46319. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46320. }
  46321. else {
  46322. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46323. }
  46324. this.rotation.z = 0;
  46325. if (isNaN(this.rotation.x)) {
  46326. this.rotation.x = 0;
  46327. }
  46328. if (isNaN(this.rotation.y)) {
  46329. this.rotation.y = 0;
  46330. }
  46331. if (isNaN(this.rotation.z)) {
  46332. this.rotation.z = 0;
  46333. }
  46334. if (this.rotationQuaternion) {
  46335. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46336. }
  46337. };
  46338. /**
  46339. * Return the current target position of the camera. This value is expressed in local space.
  46340. */
  46341. TargetCamera.prototype.getTarget = function () {
  46342. return this._currentTarget;
  46343. };
  46344. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46345. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46346. };
  46347. TargetCamera.prototype._updatePosition = function () {
  46348. if (this.parent) {
  46349. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46350. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46351. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46352. return;
  46353. }
  46354. this.position.addInPlace(this.cameraDirection);
  46355. };
  46356. TargetCamera.prototype._checkInputs = function () {
  46357. var needToMove = this._decideIfNeedsToMove();
  46358. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46359. // Move
  46360. if (needToMove) {
  46361. this._updatePosition();
  46362. }
  46363. // Rotate
  46364. if (needToRotate) {
  46365. this.rotation.x += this.cameraRotation.x;
  46366. this.rotation.y += this.cameraRotation.y;
  46367. //rotate, if quaternion is set and rotation was used
  46368. if (this.rotationQuaternion) {
  46369. var len = this.rotation.lengthSquared();
  46370. if (len) {
  46371. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46372. }
  46373. }
  46374. if (!this.noRotationConstraint) {
  46375. var limit = (Math.PI / 2) * 0.95;
  46376. if (this.rotation.x > limit)
  46377. this.rotation.x = limit;
  46378. if (this.rotation.x < -limit)
  46379. this.rotation.x = -limit;
  46380. }
  46381. }
  46382. // Inertia
  46383. if (needToMove) {
  46384. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46385. this.cameraDirection.x = 0;
  46386. }
  46387. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46388. this.cameraDirection.y = 0;
  46389. }
  46390. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46391. this.cameraDirection.z = 0;
  46392. }
  46393. this.cameraDirection.scaleInPlace(this.inertia);
  46394. }
  46395. if (needToRotate) {
  46396. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46397. this.cameraRotation.x = 0;
  46398. }
  46399. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46400. this.cameraRotation.y = 0;
  46401. }
  46402. this.cameraRotation.scaleInPlace(this.inertia);
  46403. }
  46404. _super.prototype._checkInputs.call(this);
  46405. };
  46406. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46407. if (this.rotationQuaternion) {
  46408. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46409. }
  46410. else {
  46411. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46412. }
  46413. //update the up vector!
  46414. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46415. };
  46416. TargetCamera.prototype._getViewMatrix = function () {
  46417. if (this.lockedTarget) {
  46418. this.setTarget(this._getLockedTargetPosition());
  46419. }
  46420. // Compute
  46421. this._updateCameraRotationMatrix();
  46422. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46423. // Computing target and final matrix
  46424. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46425. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46426. return this._viewMatrix;
  46427. };
  46428. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46429. if (this.parent) {
  46430. var parentWorldMatrix = this.parent.getWorldMatrix();
  46431. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46432. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46433. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46434. this._markSyncedWithParent();
  46435. }
  46436. else {
  46437. this._globalPosition.copyFrom(this.position);
  46438. this._globalCurrentTarget.copyFrom(target);
  46439. this._globalCurrentUpVector.copyFrom(up);
  46440. }
  46441. if (this.getScene().useRightHandedSystem) {
  46442. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46443. }
  46444. else {
  46445. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46446. }
  46447. };
  46448. /**
  46449. * @override
  46450. * Override Camera.createRigCamera
  46451. */
  46452. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46453. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46454. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46455. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46456. if (!this.rotationQuaternion) {
  46457. this.rotationQuaternion = new BABYLON.Quaternion();
  46458. }
  46459. rigCamera._cameraRigParams = {};
  46460. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46461. }
  46462. return rigCamera;
  46463. }
  46464. return null;
  46465. };
  46466. /**
  46467. * @override
  46468. * Override Camera._updateRigCameras
  46469. */
  46470. TargetCamera.prototype._updateRigCameras = function () {
  46471. var camLeft = this._rigCameras[0];
  46472. var camRight = this._rigCameras[1];
  46473. switch (this.cameraRigMode) {
  46474. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46475. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46476. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46478. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46479. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46480. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46481. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46482. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46483. camLeft.setTarget(this.getTarget());
  46484. camRight.setTarget(this.getTarget());
  46485. break;
  46486. case BABYLON.Camera.RIG_MODE_VR:
  46487. if (camLeft.rotationQuaternion) {
  46488. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46489. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46490. }
  46491. else {
  46492. camLeft.rotation.copyFrom(this.rotation);
  46493. camRight.rotation.copyFrom(this.rotation);
  46494. }
  46495. camLeft.position.copyFrom(this.position);
  46496. camRight.position.copyFrom(this.position);
  46497. break;
  46498. }
  46499. _super.prototype._updateRigCameras.call(this);
  46500. };
  46501. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46502. if (!this._rigCamTransformMatrix) {
  46503. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46504. }
  46505. var target = this.getTarget();
  46506. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46507. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46508. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46509. };
  46510. TargetCamera.prototype.getClassName = function () {
  46511. return "TargetCamera";
  46512. };
  46513. __decorate([
  46514. BABYLON.serializeAsVector3()
  46515. ], TargetCamera.prototype, "rotation", void 0);
  46516. __decorate([
  46517. BABYLON.serialize()
  46518. ], TargetCamera.prototype, "speed", void 0);
  46519. __decorate([
  46520. BABYLON.serializeAsMeshReference("lockedTargetId")
  46521. ], TargetCamera.prototype, "lockedTarget", void 0);
  46522. return TargetCamera;
  46523. }(BABYLON.Camera));
  46524. BABYLON.TargetCamera = TargetCamera;
  46525. })(BABYLON || (BABYLON = {}));
  46526. //# sourceMappingURL=babylon.targetCamera.js.map
  46527. var BABYLON;
  46528. (function (BABYLON) {
  46529. var FreeCameraMouseInput = /** @class */ (function () {
  46530. function FreeCameraMouseInput(touchEnabled) {
  46531. if (touchEnabled === void 0) { touchEnabled = true; }
  46532. this.touchEnabled = touchEnabled;
  46533. this.buttons = [0, 1, 2];
  46534. this.angularSensibility = 2000.0;
  46535. this.previousPosition = null;
  46536. }
  46537. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46538. var _this = this;
  46539. var engine = this.camera.getEngine();
  46540. if (!this._pointerInput) {
  46541. this._pointerInput = function (p, s) {
  46542. var evt = p.event;
  46543. if (engine.isInVRExclusivePointerMode) {
  46544. return;
  46545. }
  46546. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46547. return;
  46548. }
  46549. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46550. return;
  46551. }
  46552. var srcElement = (evt.srcElement || evt.target);
  46553. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46554. try {
  46555. srcElement.setPointerCapture(evt.pointerId);
  46556. }
  46557. catch (e) {
  46558. //Nothing to do with the error. Execution will continue.
  46559. }
  46560. _this.previousPosition = {
  46561. x: evt.clientX,
  46562. y: evt.clientY
  46563. };
  46564. if (!noPreventDefault) {
  46565. evt.preventDefault();
  46566. element.focus();
  46567. }
  46568. }
  46569. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46570. try {
  46571. srcElement.releasePointerCapture(evt.pointerId);
  46572. }
  46573. catch (e) {
  46574. //Nothing to do with the error.
  46575. }
  46576. _this.previousPosition = null;
  46577. if (!noPreventDefault) {
  46578. evt.preventDefault();
  46579. }
  46580. }
  46581. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46582. if (!_this.previousPosition || engine.isPointerLock) {
  46583. return;
  46584. }
  46585. var offsetX = evt.clientX - _this.previousPosition.x;
  46586. if (_this.camera.getScene().useRightHandedSystem)
  46587. offsetX *= -1;
  46588. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46589. offsetX *= -1;
  46590. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46591. var offsetY = evt.clientY - _this.previousPosition.y;
  46592. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46593. _this.previousPosition = {
  46594. x: evt.clientX,
  46595. y: evt.clientY
  46596. };
  46597. if (!noPreventDefault) {
  46598. evt.preventDefault();
  46599. }
  46600. }
  46601. };
  46602. }
  46603. this._onMouseMove = function (evt) {
  46604. if (!engine.isPointerLock) {
  46605. return;
  46606. }
  46607. if (engine.isInVRExclusivePointerMode) {
  46608. return;
  46609. }
  46610. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46611. if (_this.camera.getScene().useRightHandedSystem)
  46612. offsetX *= -1;
  46613. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46614. offsetX *= -1;
  46615. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46616. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46617. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46618. _this.previousPosition = null;
  46619. if (!noPreventDefault) {
  46620. evt.preventDefault();
  46621. }
  46622. };
  46623. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46624. element.addEventListener("mousemove", this._onMouseMove, false);
  46625. };
  46626. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46627. if (this._observer && element) {
  46628. this.camera.getScene().onPointerObservable.remove(this._observer);
  46629. if (this._onMouseMove) {
  46630. element.removeEventListener("mousemove", this._onMouseMove);
  46631. }
  46632. this._observer = null;
  46633. this._onMouseMove = null;
  46634. this.previousPosition = null;
  46635. }
  46636. };
  46637. FreeCameraMouseInput.prototype.getClassName = function () {
  46638. return "FreeCameraMouseInput";
  46639. };
  46640. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46641. return "mouse";
  46642. };
  46643. __decorate([
  46644. BABYLON.serialize()
  46645. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46646. __decorate([
  46647. BABYLON.serialize()
  46648. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46649. return FreeCameraMouseInput;
  46650. }());
  46651. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46652. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46653. })(BABYLON || (BABYLON = {}));
  46654. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46655. var BABYLON;
  46656. (function (BABYLON) {
  46657. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46658. function FreeCameraKeyboardMoveInput() {
  46659. this._keys = new Array();
  46660. this.keysUp = [38];
  46661. this.keysDown = [40];
  46662. this.keysLeft = [37];
  46663. this.keysRight = [39];
  46664. }
  46665. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46666. var _this = this;
  46667. if (this._onCanvasBlurObserver) {
  46668. return;
  46669. }
  46670. this._scene = this.camera.getScene();
  46671. this._engine = this._scene.getEngine();
  46672. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46673. _this._keys = [];
  46674. });
  46675. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46676. var evt = info.event;
  46677. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46678. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46679. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46680. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46681. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46682. var index = _this._keys.indexOf(evt.keyCode);
  46683. if (index === -1) {
  46684. _this._keys.push(evt.keyCode);
  46685. }
  46686. if (!noPreventDefault) {
  46687. evt.preventDefault();
  46688. }
  46689. }
  46690. }
  46691. else {
  46692. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46693. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46694. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46695. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46696. var index = _this._keys.indexOf(evt.keyCode);
  46697. if (index >= 0) {
  46698. _this._keys.splice(index, 1);
  46699. }
  46700. if (!noPreventDefault) {
  46701. evt.preventDefault();
  46702. }
  46703. }
  46704. }
  46705. });
  46706. };
  46707. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46708. if (this._scene) {
  46709. if (this._onKeyboardObserver) {
  46710. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46711. }
  46712. if (this._onCanvasBlurObserver) {
  46713. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46714. }
  46715. this._onKeyboardObserver = null;
  46716. this._onCanvasBlurObserver = null;
  46717. }
  46718. this._keys = [];
  46719. };
  46720. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46721. if (this._onKeyboardObserver) {
  46722. var camera = this.camera;
  46723. // Keyboard
  46724. for (var index = 0; index < this._keys.length; index++) {
  46725. var keyCode = this._keys[index];
  46726. var speed = camera._computeLocalCameraSpeed();
  46727. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46728. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46729. }
  46730. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46731. camera._localDirection.copyFromFloats(0, 0, speed);
  46732. }
  46733. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46734. camera._localDirection.copyFromFloats(speed, 0, 0);
  46735. }
  46736. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46737. camera._localDirection.copyFromFloats(0, 0, -speed);
  46738. }
  46739. if (camera.getScene().useRightHandedSystem) {
  46740. camera._localDirection.z *= -1;
  46741. }
  46742. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46743. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46744. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46745. }
  46746. }
  46747. };
  46748. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46749. return "FreeCameraKeyboardMoveInput";
  46750. };
  46751. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46752. this._keys = [];
  46753. };
  46754. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46755. return "keyboard";
  46756. };
  46757. __decorate([
  46758. BABYLON.serialize()
  46759. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46760. __decorate([
  46761. BABYLON.serialize()
  46762. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46763. __decorate([
  46764. BABYLON.serialize()
  46765. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46769. return FreeCameraKeyboardMoveInput;
  46770. }());
  46771. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46772. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46773. })(BABYLON || (BABYLON = {}));
  46774. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46775. var BABYLON;
  46776. (function (BABYLON) {
  46777. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46778. __extends(FreeCameraInputsManager, _super);
  46779. function FreeCameraInputsManager(camera) {
  46780. return _super.call(this, camera) || this;
  46781. }
  46782. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46783. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46784. return this;
  46785. };
  46786. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46787. if (touchEnabled === void 0) { touchEnabled = true; }
  46788. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46789. return this;
  46790. };
  46791. FreeCameraInputsManager.prototype.addGamepad = function () {
  46792. this.add(new BABYLON.FreeCameraGamepadInput());
  46793. return this;
  46794. };
  46795. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46796. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46797. return this;
  46798. };
  46799. FreeCameraInputsManager.prototype.addTouch = function () {
  46800. this.add(new BABYLON.FreeCameraTouchInput());
  46801. return this;
  46802. };
  46803. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46804. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46805. return this;
  46806. };
  46807. return FreeCameraInputsManager;
  46808. }(BABYLON.CameraInputsManager));
  46809. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46810. })(BABYLON || (BABYLON = {}));
  46811. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46812. var BABYLON;
  46813. (function (BABYLON) {
  46814. var FreeCamera = /** @class */ (function (_super) {
  46815. __extends(FreeCamera, _super);
  46816. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46817. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46818. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46819. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46820. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46821. _this.checkCollisions = false;
  46822. _this.applyGravity = false;
  46823. _this._needMoveForGravity = false;
  46824. _this._oldPosition = BABYLON.Vector3.Zero();
  46825. _this._diffPosition = BABYLON.Vector3.Zero();
  46826. _this._newPosition = BABYLON.Vector3.Zero();
  46827. // Collisions
  46828. _this._collisionMask = -1;
  46829. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46830. if (collidedMesh === void 0) { collidedMesh = null; }
  46831. //TODO move this to the collision coordinator!
  46832. if (_this.getScene().workerCollisions)
  46833. newPosition.multiplyInPlace(_this._collider._radius);
  46834. var updatePosition = function (newPos) {
  46835. _this._newPosition.copyFrom(newPos);
  46836. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46837. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46838. _this.position.addInPlace(_this._diffPosition);
  46839. if (_this.onCollide && collidedMesh) {
  46840. _this.onCollide(collidedMesh);
  46841. }
  46842. }
  46843. };
  46844. updatePosition(newPosition);
  46845. };
  46846. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46847. _this.inputs.addKeyboard().addMouse();
  46848. return _this;
  46849. }
  46850. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46851. //-- begin properties for backward compatibility for inputs
  46852. /**
  46853. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46854. * Higher values reduce sensitivity.
  46855. */
  46856. get: function () {
  46857. var mouse = this.inputs.attached["mouse"];
  46858. if (mouse)
  46859. return mouse.angularSensibility;
  46860. return 0;
  46861. },
  46862. /**
  46863. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46864. * Higher values reduce sensitivity.
  46865. */
  46866. set: function (value) {
  46867. var mouse = this.inputs.attached["mouse"];
  46868. if (mouse)
  46869. mouse.angularSensibility = value;
  46870. },
  46871. enumerable: true,
  46872. configurable: true
  46873. });
  46874. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46875. get: function () {
  46876. var keyboard = this.inputs.attached["keyboard"];
  46877. if (keyboard)
  46878. return keyboard.keysUp;
  46879. return [];
  46880. },
  46881. set: function (value) {
  46882. var keyboard = this.inputs.attached["keyboard"];
  46883. if (keyboard)
  46884. keyboard.keysUp = value;
  46885. },
  46886. enumerable: true,
  46887. configurable: true
  46888. });
  46889. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46890. get: function () {
  46891. var keyboard = this.inputs.attached["keyboard"];
  46892. if (keyboard)
  46893. return keyboard.keysDown;
  46894. return [];
  46895. },
  46896. set: function (value) {
  46897. var keyboard = this.inputs.attached["keyboard"];
  46898. if (keyboard)
  46899. keyboard.keysDown = value;
  46900. },
  46901. enumerable: true,
  46902. configurable: true
  46903. });
  46904. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46905. get: function () {
  46906. var keyboard = this.inputs.attached["keyboard"];
  46907. if (keyboard)
  46908. return keyboard.keysLeft;
  46909. return [];
  46910. },
  46911. set: function (value) {
  46912. var keyboard = this.inputs.attached["keyboard"];
  46913. if (keyboard)
  46914. keyboard.keysLeft = value;
  46915. },
  46916. enumerable: true,
  46917. configurable: true
  46918. });
  46919. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46920. get: function () {
  46921. var keyboard = this.inputs.attached["keyboard"];
  46922. if (keyboard)
  46923. return keyboard.keysRight;
  46924. return [];
  46925. },
  46926. set: function (value) {
  46927. var keyboard = this.inputs.attached["keyboard"];
  46928. if (keyboard)
  46929. keyboard.keysRight = value;
  46930. },
  46931. enumerable: true,
  46932. configurable: true
  46933. });
  46934. // Controls
  46935. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46936. this.inputs.attachElement(element, noPreventDefault);
  46937. };
  46938. FreeCamera.prototype.detachControl = function (element) {
  46939. this.inputs.detachElement(element);
  46940. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46941. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46942. };
  46943. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46944. get: function () {
  46945. return this._collisionMask;
  46946. },
  46947. set: function (mask) {
  46948. this._collisionMask = !isNaN(mask) ? mask : -1;
  46949. },
  46950. enumerable: true,
  46951. configurable: true
  46952. });
  46953. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46954. var globalPosition;
  46955. if (this.parent) {
  46956. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46957. }
  46958. else {
  46959. globalPosition = this.position;
  46960. }
  46961. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46962. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46963. if (!this._collider) {
  46964. this._collider = new BABYLON.Collider();
  46965. }
  46966. this._collider._radius = this.ellipsoid;
  46967. this._collider.collisionMask = this._collisionMask;
  46968. //no need for clone, as long as gravity is not on.
  46969. var actualDisplacement = displacement;
  46970. //add gravity to the direction to prevent the dual-collision checking
  46971. if (this.applyGravity) {
  46972. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46973. actualDisplacement = displacement.add(this.getScene().gravity);
  46974. }
  46975. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46976. };
  46977. FreeCamera.prototype._checkInputs = function () {
  46978. if (!this._localDirection) {
  46979. this._localDirection = BABYLON.Vector3.Zero();
  46980. this._transformedDirection = BABYLON.Vector3.Zero();
  46981. }
  46982. this.inputs.checkInputs();
  46983. _super.prototype._checkInputs.call(this);
  46984. };
  46985. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46986. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46987. };
  46988. FreeCamera.prototype._updatePosition = function () {
  46989. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46990. this._collideWithWorld(this.cameraDirection);
  46991. }
  46992. else {
  46993. _super.prototype._updatePosition.call(this);
  46994. }
  46995. };
  46996. FreeCamera.prototype.dispose = function () {
  46997. this.inputs.clear();
  46998. _super.prototype.dispose.call(this);
  46999. };
  47000. FreeCamera.prototype.getClassName = function () {
  47001. return "FreeCamera";
  47002. };
  47003. __decorate([
  47004. BABYLON.serializeAsVector3()
  47005. ], FreeCamera.prototype, "ellipsoid", void 0);
  47006. __decorate([
  47007. BABYLON.serializeAsVector3()
  47008. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47009. __decorate([
  47010. BABYLON.serialize()
  47011. ], FreeCamera.prototype, "checkCollisions", void 0);
  47012. __decorate([
  47013. BABYLON.serialize()
  47014. ], FreeCamera.prototype, "applyGravity", void 0);
  47015. return FreeCamera;
  47016. }(BABYLON.TargetCamera));
  47017. BABYLON.FreeCamera = FreeCamera;
  47018. })(BABYLON || (BABYLON = {}));
  47019. //# sourceMappingURL=babylon.freeCamera.js.map
  47020. var BABYLON;
  47021. (function (BABYLON) {
  47022. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47023. function ArcRotateCameraKeyboardMoveInput() {
  47024. this._keys = new Array();
  47025. this.keysUp = [38];
  47026. this.keysDown = [40];
  47027. this.keysLeft = [37];
  47028. this.keysRight = [39];
  47029. this.keysReset = [220];
  47030. this.panningSensibility = 50.0;
  47031. this.zoomingSensibility = 25.0;
  47032. this.useAltToZoom = true;
  47033. }
  47034. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47035. var _this = this;
  47036. if (this._onCanvasBlurObserver) {
  47037. return;
  47038. }
  47039. this._scene = this.camera.getScene();
  47040. this._engine = this._scene.getEngine();
  47041. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47042. _this._keys = [];
  47043. });
  47044. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47045. var evt = info.event;
  47046. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47047. _this._ctrlPressed = evt.ctrlKey;
  47048. _this._altPressed = evt.altKey;
  47049. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47050. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47051. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47052. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47053. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47054. var index = _this._keys.indexOf(evt.keyCode);
  47055. if (index === -1) {
  47056. _this._keys.push(evt.keyCode);
  47057. }
  47058. if (evt.preventDefault) {
  47059. if (!noPreventDefault) {
  47060. evt.preventDefault();
  47061. }
  47062. }
  47063. }
  47064. }
  47065. else {
  47066. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47067. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47068. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47069. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47070. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47071. var index = _this._keys.indexOf(evt.keyCode);
  47072. if (index >= 0) {
  47073. _this._keys.splice(index, 1);
  47074. }
  47075. if (evt.preventDefault) {
  47076. if (!noPreventDefault) {
  47077. evt.preventDefault();
  47078. }
  47079. }
  47080. }
  47081. }
  47082. });
  47083. };
  47084. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47085. if (this._scene) {
  47086. if (this._onKeyboardObserver) {
  47087. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47088. }
  47089. if (this._onCanvasBlurObserver) {
  47090. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47091. }
  47092. this._onKeyboardObserver = null;
  47093. this._onCanvasBlurObserver = null;
  47094. }
  47095. this._keys = [];
  47096. };
  47097. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47098. if (this._onKeyboardObserver) {
  47099. var camera = this.camera;
  47100. for (var index = 0; index < this._keys.length; index++) {
  47101. var keyCode = this._keys[index];
  47102. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47103. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47104. camera.inertialPanningX -= 1 / this.panningSensibility;
  47105. }
  47106. else {
  47107. camera.inertialAlphaOffset -= 0.01;
  47108. }
  47109. }
  47110. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47111. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47112. camera.inertialPanningY += 1 / this.panningSensibility;
  47113. }
  47114. else if (this._altPressed && this.useAltToZoom) {
  47115. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47116. }
  47117. else {
  47118. camera.inertialBetaOffset -= 0.01;
  47119. }
  47120. }
  47121. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47122. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47123. camera.inertialPanningX += 1 / this.panningSensibility;
  47124. }
  47125. else {
  47126. camera.inertialAlphaOffset += 0.01;
  47127. }
  47128. }
  47129. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47130. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47131. camera.inertialPanningY -= 1 / this.panningSensibility;
  47132. }
  47133. else if (this._altPressed && this.useAltToZoom) {
  47134. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47135. }
  47136. else {
  47137. camera.inertialBetaOffset += 0.01;
  47138. }
  47139. }
  47140. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47141. camera.restoreState();
  47142. }
  47143. }
  47144. }
  47145. };
  47146. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47147. return "ArcRotateCameraKeyboardMoveInput";
  47148. };
  47149. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47150. return "keyboard";
  47151. };
  47152. __decorate([
  47153. BABYLON.serialize()
  47154. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47155. __decorate([
  47156. BABYLON.serialize()
  47157. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47158. __decorate([
  47159. BABYLON.serialize()
  47160. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47161. __decorate([
  47162. BABYLON.serialize()
  47163. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47164. __decorate([
  47165. BABYLON.serialize()
  47166. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47167. __decorate([
  47168. BABYLON.serialize()
  47169. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47170. __decorate([
  47171. BABYLON.serialize()
  47172. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47173. __decorate([
  47174. BABYLON.serialize()
  47175. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47176. return ArcRotateCameraKeyboardMoveInput;
  47177. }());
  47178. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47179. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47180. })(BABYLON || (BABYLON = {}));
  47181. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47182. var BABYLON;
  47183. (function (BABYLON) {
  47184. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47185. function ArcRotateCameraMouseWheelInput() {
  47186. this.wheelPrecision = 3.0;
  47187. /**
  47188. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47189. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47190. */
  47191. this.wheelDeltaPercentage = 0;
  47192. }
  47193. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47194. var _this = this;
  47195. this._wheel = function (p, s) {
  47196. //sanity check - this should be a PointerWheel event.
  47197. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47198. return;
  47199. var event = p.event;
  47200. var delta = 0;
  47201. if (event.wheelDelta) {
  47202. if (_this.wheelDeltaPercentage) {
  47203. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47204. if (event.wheelDelta > 0) {
  47205. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47206. }
  47207. else {
  47208. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47209. }
  47210. }
  47211. else {
  47212. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47213. }
  47214. }
  47215. else if (event.detail) {
  47216. delta = -event.detail / _this.wheelPrecision;
  47217. }
  47218. if (delta)
  47219. _this.camera.inertialRadiusOffset += delta;
  47220. if (event.preventDefault) {
  47221. if (!noPreventDefault) {
  47222. event.preventDefault();
  47223. }
  47224. }
  47225. };
  47226. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47227. };
  47228. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47229. if (this._observer && element) {
  47230. this.camera.getScene().onPointerObservable.remove(this._observer);
  47231. this._observer = null;
  47232. this._wheel = null;
  47233. }
  47234. };
  47235. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47236. return "ArcRotateCameraMouseWheelInput";
  47237. };
  47238. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47239. return "mousewheel";
  47240. };
  47241. __decorate([
  47242. BABYLON.serialize()
  47243. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47244. __decorate([
  47245. BABYLON.serialize()
  47246. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47247. return ArcRotateCameraMouseWheelInput;
  47248. }());
  47249. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47250. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47251. })(BABYLON || (BABYLON = {}));
  47252. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47253. var BABYLON;
  47254. (function (BABYLON) {
  47255. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47256. function ArcRotateCameraPointersInput() {
  47257. this.buttons = [0, 1, 2];
  47258. this.angularSensibilityX = 1000.0;
  47259. this.angularSensibilityY = 1000.0;
  47260. this.pinchPrecision = 12.0;
  47261. /**
  47262. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47263. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47264. */
  47265. this.pinchDeltaPercentage = 0;
  47266. this.panningSensibility = 1000.0;
  47267. this.multiTouchPanning = true;
  47268. this.multiTouchPanAndZoom = true;
  47269. this._isPanClick = false;
  47270. this.pinchInwards = true;
  47271. }
  47272. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47273. var _this = this;
  47274. var engine = this.camera.getEngine();
  47275. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47276. var pointA = null;
  47277. var pointB = null;
  47278. var previousPinchSquaredDistance = 0;
  47279. var initialDistance = 0;
  47280. var twoFingerActivityCount = 0;
  47281. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47282. this._pointerInput = function (p, s) {
  47283. var evt = p.event;
  47284. var isTouch = p.event.pointerType === "touch";
  47285. if (engine.isInVRExclusivePointerMode) {
  47286. return;
  47287. }
  47288. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47289. return;
  47290. }
  47291. var srcElement = (evt.srcElement || evt.target);
  47292. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47293. try {
  47294. srcElement.setPointerCapture(evt.pointerId);
  47295. }
  47296. catch (e) {
  47297. //Nothing to do with the error. Execution will continue.
  47298. }
  47299. // Manage panning with pan button click
  47300. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47301. // manage pointers
  47302. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47303. if (pointA === null) {
  47304. pointA = cacheSoloPointer;
  47305. }
  47306. else if (pointB === null) {
  47307. pointB = cacheSoloPointer;
  47308. }
  47309. if (!noPreventDefault) {
  47310. evt.preventDefault();
  47311. element.focus();
  47312. }
  47313. }
  47314. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47315. _this.camera.restoreState();
  47316. }
  47317. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47318. try {
  47319. srcElement.releasePointerCapture(evt.pointerId);
  47320. }
  47321. catch (e) {
  47322. //Nothing to do with the error.
  47323. }
  47324. cacheSoloPointer = null;
  47325. previousPinchSquaredDistance = 0;
  47326. previousMultiTouchPanPosition.isPaning = false;
  47327. previousMultiTouchPanPosition.isPinching = false;
  47328. twoFingerActivityCount = 0;
  47329. initialDistance = 0;
  47330. if (!isTouch) {
  47331. pointB = null; // Mouse and pen are mono pointer
  47332. }
  47333. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47334. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47335. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47336. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47337. if (engine._badOS) {
  47338. pointA = pointB = null;
  47339. }
  47340. else {
  47341. //only remove the impacted pointer in case of multitouch allowing on most
  47342. //platforms switching from rotate to zoom and pan seamlessly.
  47343. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47344. pointA = pointB;
  47345. pointB = null;
  47346. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47347. }
  47348. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47349. pointB = null;
  47350. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47351. }
  47352. else {
  47353. pointA = pointB = null;
  47354. }
  47355. }
  47356. if (!noPreventDefault) {
  47357. evt.preventDefault();
  47358. }
  47359. }
  47360. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47361. if (!noPreventDefault) {
  47362. evt.preventDefault();
  47363. }
  47364. // One button down
  47365. if (pointA && pointB === null && cacheSoloPointer) {
  47366. if (_this.panningSensibility !== 0 &&
  47367. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47368. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47369. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47370. }
  47371. else {
  47372. var offsetX = evt.clientX - cacheSoloPointer.x;
  47373. var offsetY = evt.clientY - cacheSoloPointer.y;
  47374. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47375. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47376. }
  47377. cacheSoloPointer.x = evt.clientX;
  47378. cacheSoloPointer.y = evt.clientY;
  47379. }
  47380. // Two buttons down: pinch/pan
  47381. else if (pointA && pointB) {
  47382. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47383. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47384. ed.x = evt.clientX;
  47385. ed.y = evt.clientY;
  47386. var direction = _this.pinchInwards ? 1 : -1;
  47387. var distX = pointA.x - pointB.x;
  47388. var distY = pointA.y - pointB.y;
  47389. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47390. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47391. if (previousPinchSquaredDistance === 0) {
  47392. initialDistance = pinchDistance;
  47393. previousPinchSquaredDistance = pinchSquaredDistance;
  47394. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47395. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47396. return;
  47397. }
  47398. if (_this.multiTouchPanAndZoom) {
  47399. if (_this.pinchDeltaPercentage) {
  47400. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47401. }
  47402. else {
  47403. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47404. (_this.pinchPrecision *
  47405. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47406. direction);
  47407. }
  47408. if (_this.panningSensibility !== 0) {
  47409. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47410. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47411. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47412. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47413. previousMultiTouchPanPosition.x = pointersCenterX;
  47414. previousMultiTouchPanPosition.y = pointersCenterY;
  47415. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47416. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47417. }
  47418. }
  47419. else {
  47420. twoFingerActivityCount++;
  47421. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47422. if (_this.pinchDeltaPercentage) {
  47423. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47424. }
  47425. else {
  47426. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47427. (_this.pinchPrecision *
  47428. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47429. direction);
  47430. }
  47431. previousMultiTouchPanPosition.isPaning = false;
  47432. previousMultiTouchPanPosition.isPinching = true;
  47433. }
  47434. else {
  47435. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47436. if (!previousMultiTouchPanPosition.isPaning) {
  47437. previousMultiTouchPanPosition.isPaning = true;
  47438. previousMultiTouchPanPosition.isPinching = false;
  47439. previousMultiTouchPanPosition.x = ed.x;
  47440. previousMultiTouchPanPosition.y = ed.y;
  47441. return;
  47442. }
  47443. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47444. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47445. }
  47446. }
  47447. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47448. previousMultiTouchPanPosition.x = ed.x;
  47449. previousMultiTouchPanPosition.y = ed.y;
  47450. }
  47451. }
  47452. previousPinchSquaredDistance = pinchSquaredDistance;
  47453. }
  47454. }
  47455. };
  47456. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47457. this._onContextMenu = function (evt) {
  47458. evt.preventDefault();
  47459. };
  47460. if (!this.camera._useCtrlForPanning) {
  47461. element.addEventListener("contextmenu", this._onContextMenu, false);
  47462. }
  47463. this._onLostFocus = function () {
  47464. //this._keys = [];
  47465. pointA = pointB = null;
  47466. previousPinchSquaredDistance = 0;
  47467. previousMultiTouchPanPosition.isPaning = false;
  47468. previousMultiTouchPanPosition.isPinching = false;
  47469. twoFingerActivityCount = 0;
  47470. cacheSoloPointer = null;
  47471. initialDistance = 0;
  47472. };
  47473. this._onMouseMove = function (evt) {
  47474. if (!engine.isPointerLock) {
  47475. return;
  47476. }
  47477. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47478. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47479. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47480. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47481. if (!noPreventDefault) {
  47482. evt.preventDefault();
  47483. }
  47484. };
  47485. this._onGestureStart = function (e) {
  47486. if (window.MSGesture === undefined) {
  47487. return;
  47488. }
  47489. if (!_this._MSGestureHandler) {
  47490. _this._MSGestureHandler = new MSGesture();
  47491. _this._MSGestureHandler.target = element;
  47492. }
  47493. _this._MSGestureHandler.addPointer(e.pointerId);
  47494. };
  47495. this._onGesture = function (e) {
  47496. _this.camera.radius *= e.scale;
  47497. if (e.preventDefault) {
  47498. if (!noPreventDefault) {
  47499. e.stopPropagation();
  47500. e.preventDefault();
  47501. }
  47502. }
  47503. };
  47504. element.addEventListener("mousemove", this._onMouseMove, false);
  47505. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47506. element.addEventListener("MSGestureChange", this._onGesture, false);
  47507. BABYLON.Tools.RegisterTopRootEvents([
  47508. { name: "blur", handler: this._onLostFocus }
  47509. ]);
  47510. };
  47511. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47512. if (this._onLostFocus) {
  47513. BABYLON.Tools.UnregisterTopRootEvents([
  47514. { name: "blur", handler: this._onLostFocus }
  47515. ]);
  47516. }
  47517. if (element && this._observer) {
  47518. this.camera.getScene().onPointerObservable.remove(this._observer);
  47519. this._observer = null;
  47520. if (this._onContextMenu) {
  47521. element.removeEventListener("contextmenu", this._onContextMenu);
  47522. }
  47523. if (this._onMouseMove) {
  47524. element.removeEventListener("mousemove", this._onMouseMove);
  47525. }
  47526. if (this._onGestureStart) {
  47527. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47528. }
  47529. if (this._onGesture) {
  47530. element.removeEventListener("MSGestureChange", this._onGesture);
  47531. }
  47532. this._isPanClick = false;
  47533. this.pinchInwards = true;
  47534. this._onMouseMove = null;
  47535. this._onGestureStart = null;
  47536. this._onGesture = null;
  47537. this._MSGestureHandler = null;
  47538. this._onLostFocus = null;
  47539. this._onContextMenu = null;
  47540. }
  47541. };
  47542. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47543. return "ArcRotateCameraPointersInput";
  47544. };
  47545. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47546. return "pointers";
  47547. };
  47548. __decorate([
  47549. BABYLON.serialize()
  47550. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47551. __decorate([
  47552. BABYLON.serialize()
  47553. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47554. __decorate([
  47555. BABYLON.serialize()
  47556. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47557. __decorate([
  47558. BABYLON.serialize()
  47559. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47560. __decorate([
  47561. BABYLON.serialize()
  47562. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47563. __decorate([
  47564. BABYLON.serialize()
  47565. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47566. __decorate([
  47567. BABYLON.serialize()
  47568. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47569. __decorate([
  47570. BABYLON.serialize()
  47571. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47572. return ArcRotateCameraPointersInput;
  47573. }());
  47574. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47575. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47576. })(BABYLON || (BABYLON = {}));
  47577. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47578. var BABYLON;
  47579. (function (BABYLON) {
  47580. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47581. __extends(ArcRotateCameraInputsManager, _super);
  47582. function ArcRotateCameraInputsManager(camera) {
  47583. return _super.call(this, camera) || this;
  47584. }
  47585. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47586. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47587. return this;
  47588. };
  47589. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47590. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47591. return this;
  47592. };
  47593. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47594. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47595. return this;
  47596. };
  47597. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47598. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47599. return this;
  47600. };
  47601. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47602. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47603. return this;
  47604. };
  47605. return ArcRotateCameraInputsManager;
  47606. }(BABYLON.CameraInputsManager));
  47607. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47608. })(BABYLON || (BABYLON = {}));
  47609. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47610. var BABYLON;
  47611. (function (BABYLON) {
  47612. var ArcRotateCamera = /** @class */ (function (_super) {
  47613. __extends(ArcRotateCamera, _super);
  47614. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47615. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47616. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47617. _this.inertialAlphaOffset = 0;
  47618. _this.inertialBetaOffset = 0;
  47619. _this.inertialRadiusOffset = 0;
  47620. _this.lowerAlphaLimit = null;
  47621. _this.upperAlphaLimit = null;
  47622. _this.lowerBetaLimit = 0.01;
  47623. _this.upperBetaLimit = Math.PI;
  47624. _this.lowerRadiusLimit = null;
  47625. _this.upperRadiusLimit = null;
  47626. _this.inertialPanningX = 0;
  47627. _this.inertialPanningY = 0;
  47628. _this.pinchToPanMaxDistance = 20;
  47629. _this.panningDistanceLimit = null;
  47630. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47631. _this.panningInertia = 0.9;
  47632. //-- end properties for backward compatibility for inputs
  47633. _this.zoomOnFactor = 1;
  47634. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47635. _this.allowUpsideDown = true;
  47636. _this._viewMatrix = new BABYLON.Matrix();
  47637. // Panning
  47638. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47639. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47640. _this.checkCollisions = false;
  47641. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47642. _this._previousPosition = BABYLON.Vector3.Zero();
  47643. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47644. _this._newPosition = BABYLON.Vector3.Zero();
  47645. _this._computationVector = BABYLON.Vector3.Zero();
  47646. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47647. if (collidedMesh === void 0) { collidedMesh = null; }
  47648. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47649. newPosition.multiplyInPlace(_this._collider._radius);
  47650. }
  47651. if (!collidedMesh) {
  47652. _this._previousPosition.copyFrom(_this.position);
  47653. }
  47654. else {
  47655. _this.setPosition(newPosition);
  47656. if (_this.onCollide) {
  47657. _this.onCollide(collidedMesh);
  47658. }
  47659. }
  47660. // Recompute because of constraints
  47661. var cosa = Math.cos(_this.alpha);
  47662. var sina = Math.sin(_this.alpha);
  47663. var cosb = Math.cos(_this.beta);
  47664. var sinb = Math.sin(_this.beta);
  47665. if (sinb === 0) {
  47666. sinb = 0.0001;
  47667. }
  47668. var target = _this._getTargetPosition();
  47669. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47670. target.addToRef(_this._computationVector, _this._newPosition);
  47671. _this.position.copyFrom(_this._newPosition);
  47672. var up = _this.upVector;
  47673. if (_this.allowUpsideDown && _this.beta < 0) {
  47674. up = up.clone();
  47675. up = up.negate();
  47676. }
  47677. _this._computeViewMatrix(_this.position, target, up);
  47678. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47679. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47680. _this._collisionTriggered = false;
  47681. };
  47682. _this._target = BABYLON.Vector3.Zero();
  47683. if (target) {
  47684. _this.setTarget(target);
  47685. }
  47686. _this.alpha = alpha;
  47687. _this.beta = beta;
  47688. _this.radius = radius;
  47689. _this.getViewMatrix();
  47690. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47691. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47692. return _this;
  47693. }
  47694. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47695. get: function () {
  47696. return this._target;
  47697. },
  47698. set: function (value) {
  47699. this.setTarget(value);
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47705. //-- begin properties for backward compatibility for inputs
  47706. get: function () {
  47707. var pointers = this.inputs.attached["pointers"];
  47708. if (pointers)
  47709. return pointers.angularSensibilityX;
  47710. return 0;
  47711. },
  47712. set: function (value) {
  47713. var pointers = this.inputs.attached["pointers"];
  47714. if (pointers) {
  47715. pointers.angularSensibilityX = value;
  47716. }
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47722. get: function () {
  47723. var pointers = this.inputs.attached["pointers"];
  47724. if (pointers)
  47725. return pointers.angularSensibilityY;
  47726. return 0;
  47727. },
  47728. set: function (value) {
  47729. var pointers = this.inputs.attached["pointers"];
  47730. if (pointers) {
  47731. pointers.angularSensibilityY = value;
  47732. }
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47738. get: function () {
  47739. var pointers = this.inputs.attached["pointers"];
  47740. if (pointers)
  47741. return pointers.pinchPrecision;
  47742. return 0;
  47743. },
  47744. set: function (value) {
  47745. var pointers = this.inputs.attached["pointers"];
  47746. if (pointers) {
  47747. pointers.pinchPrecision = value;
  47748. }
  47749. },
  47750. enumerable: true,
  47751. configurable: true
  47752. });
  47753. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47754. get: function () {
  47755. var pointers = this.inputs.attached["pointers"];
  47756. if (pointers)
  47757. return pointers.pinchDeltaPercentage;
  47758. return 0;
  47759. },
  47760. set: function (value) {
  47761. var pointers = this.inputs.attached["pointers"];
  47762. if (pointers) {
  47763. pointers.pinchDeltaPercentage = value;
  47764. }
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47770. get: function () {
  47771. var pointers = this.inputs.attached["pointers"];
  47772. if (pointers)
  47773. return pointers.panningSensibility;
  47774. return 0;
  47775. },
  47776. set: function (value) {
  47777. var pointers = this.inputs.attached["pointers"];
  47778. if (pointers) {
  47779. pointers.panningSensibility = value;
  47780. }
  47781. },
  47782. enumerable: true,
  47783. configurable: true
  47784. });
  47785. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47786. get: function () {
  47787. var keyboard = this.inputs.attached["keyboard"];
  47788. if (keyboard)
  47789. return keyboard.keysUp;
  47790. return [];
  47791. },
  47792. set: function (value) {
  47793. var keyboard = this.inputs.attached["keyboard"];
  47794. if (keyboard)
  47795. keyboard.keysUp = value;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47801. get: function () {
  47802. var keyboard = this.inputs.attached["keyboard"];
  47803. if (keyboard)
  47804. return keyboard.keysDown;
  47805. return [];
  47806. },
  47807. set: function (value) {
  47808. var keyboard = this.inputs.attached["keyboard"];
  47809. if (keyboard)
  47810. keyboard.keysDown = value;
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47816. get: function () {
  47817. var keyboard = this.inputs.attached["keyboard"];
  47818. if (keyboard)
  47819. return keyboard.keysLeft;
  47820. return [];
  47821. },
  47822. set: function (value) {
  47823. var keyboard = this.inputs.attached["keyboard"];
  47824. if (keyboard)
  47825. keyboard.keysLeft = value;
  47826. },
  47827. enumerable: true,
  47828. configurable: true
  47829. });
  47830. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47831. get: function () {
  47832. var keyboard = this.inputs.attached["keyboard"];
  47833. if (keyboard)
  47834. return keyboard.keysRight;
  47835. return [];
  47836. },
  47837. set: function (value) {
  47838. var keyboard = this.inputs.attached["keyboard"];
  47839. if (keyboard)
  47840. keyboard.keysRight = value;
  47841. },
  47842. enumerable: true,
  47843. configurable: true
  47844. });
  47845. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47846. get: function () {
  47847. var mousewheel = this.inputs.attached["mousewheel"];
  47848. if (mousewheel)
  47849. return mousewheel.wheelPrecision;
  47850. return 0;
  47851. },
  47852. set: function (value) {
  47853. var mousewheel = this.inputs.attached["mousewheel"];
  47854. if (mousewheel)
  47855. mousewheel.wheelPrecision = value;
  47856. },
  47857. enumerable: true,
  47858. configurable: true
  47859. });
  47860. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47861. get: function () {
  47862. var mousewheel = this.inputs.attached["mousewheel"];
  47863. if (mousewheel)
  47864. return mousewheel.wheelDeltaPercentage;
  47865. return 0;
  47866. },
  47867. set: function (value) {
  47868. var mousewheel = this.inputs.attached["mousewheel"];
  47869. if (mousewheel)
  47870. mousewheel.wheelDeltaPercentage = value;
  47871. },
  47872. enumerable: true,
  47873. configurable: true
  47874. });
  47875. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47876. get: function () {
  47877. return this._bouncingBehavior;
  47878. },
  47879. enumerable: true,
  47880. configurable: true
  47881. });
  47882. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47883. get: function () {
  47884. return this._bouncingBehavior != null;
  47885. },
  47886. set: function (value) {
  47887. if (value === this.useBouncingBehavior) {
  47888. return;
  47889. }
  47890. if (value) {
  47891. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47892. this.addBehavior(this._bouncingBehavior);
  47893. }
  47894. else if (this._bouncingBehavior) {
  47895. this.removeBehavior(this._bouncingBehavior);
  47896. this._bouncingBehavior = null;
  47897. }
  47898. },
  47899. enumerable: true,
  47900. configurable: true
  47901. });
  47902. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47903. get: function () {
  47904. return this._framingBehavior;
  47905. },
  47906. enumerable: true,
  47907. configurable: true
  47908. });
  47909. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47910. get: function () {
  47911. return this._framingBehavior != null;
  47912. },
  47913. set: function (value) {
  47914. if (value === this.useFramingBehavior) {
  47915. return;
  47916. }
  47917. if (value) {
  47918. this._framingBehavior = new BABYLON.FramingBehavior();
  47919. this.addBehavior(this._framingBehavior);
  47920. }
  47921. else if (this._framingBehavior) {
  47922. this.removeBehavior(this._framingBehavior);
  47923. this._framingBehavior = null;
  47924. }
  47925. },
  47926. enumerable: true,
  47927. configurable: true
  47928. });
  47929. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47930. get: function () {
  47931. return this._autoRotationBehavior;
  47932. },
  47933. enumerable: true,
  47934. configurable: true
  47935. });
  47936. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47937. get: function () {
  47938. return this._autoRotationBehavior != null;
  47939. },
  47940. set: function (value) {
  47941. if (value === this.useAutoRotationBehavior) {
  47942. return;
  47943. }
  47944. if (value) {
  47945. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47946. this.addBehavior(this._autoRotationBehavior);
  47947. }
  47948. else if (this._autoRotationBehavior) {
  47949. this.removeBehavior(this._autoRotationBehavior);
  47950. this._autoRotationBehavior = null;
  47951. }
  47952. },
  47953. enumerable: true,
  47954. configurable: true
  47955. });
  47956. // Cache
  47957. ArcRotateCamera.prototype._initCache = function () {
  47958. _super.prototype._initCache.call(this);
  47959. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47960. this._cache.alpha = undefined;
  47961. this._cache.beta = undefined;
  47962. this._cache.radius = undefined;
  47963. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47964. };
  47965. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47966. if (!ignoreParentClass) {
  47967. _super.prototype._updateCache.call(this);
  47968. }
  47969. this._cache._target.copyFrom(this._getTargetPosition());
  47970. this._cache.alpha = this.alpha;
  47971. this._cache.beta = this.beta;
  47972. this._cache.radius = this.radius;
  47973. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47974. };
  47975. ArcRotateCamera.prototype._getTargetPosition = function () {
  47976. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47977. var pos = this._targetHost.getAbsolutePosition();
  47978. if (this._targetBoundingCenter) {
  47979. pos.addToRef(this._targetBoundingCenter, this._target);
  47980. }
  47981. else {
  47982. this._target.copyFrom(pos);
  47983. }
  47984. }
  47985. var lockedTargetPosition = this._getLockedTargetPosition();
  47986. if (lockedTargetPosition) {
  47987. return lockedTargetPosition;
  47988. }
  47989. return this._target;
  47990. };
  47991. ArcRotateCamera.prototype.storeState = function () {
  47992. this._storedAlpha = this.alpha;
  47993. this._storedBeta = this.beta;
  47994. this._storedRadius = this.radius;
  47995. this._storedTarget = this._getTargetPosition().clone();
  47996. return _super.prototype.storeState.call(this);
  47997. };
  47998. /**
  47999. * Restored camera state. You must call storeState() first
  48000. */
  48001. ArcRotateCamera.prototype._restoreStateValues = function () {
  48002. if (!_super.prototype._restoreStateValues.call(this)) {
  48003. return false;
  48004. }
  48005. this.alpha = this._storedAlpha;
  48006. this.beta = this._storedBeta;
  48007. this.radius = this._storedRadius;
  48008. this.setTarget(this._storedTarget.clone());
  48009. this.inertialAlphaOffset = 0;
  48010. this.inertialBetaOffset = 0;
  48011. this.inertialRadiusOffset = 0;
  48012. this.inertialPanningX = 0;
  48013. this.inertialPanningY = 0;
  48014. return true;
  48015. };
  48016. // Synchronized
  48017. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48018. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48019. return false;
  48020. return this._cache._target.equals(this._getTargetPosition())
  48021. && this._cache.alpha === this.alpha
  48022. && this._cache.beta === this.beta
  48023. && this._cache.radius === this.radius
  48024. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48025. };
  48026. // Methods
  48027. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48028. var _this = this;
  48029. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48030. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48031. this._useCtrlForPanning = useCtrlForPanning;
  48032. this._panningMouseButton = panningMouseButton;
  48033. this.inputs.attachElement(element, noPreventDefault);
  48034. this._reset = function () {
  48035. _this.inertialAlphaOffset = 0;
  48036. _this.inertialBetaOffset = 0;
  48037. _this.inertialRadiusOffset = 0;
  48038. _this.inertialPanningX = 0;
  48039. _this.inertialPanningY = 0;
  48040. };
  48041. };
  48042. ArcRotateCamera.prototype.detachControl = function (element) {
  48043. this.inputs.detachElement(element);
  48044. if (this._reset) {
  48045. this._reset();
  48046. }
  48047. };
  48048. ArcRotateCamera.prototype._checkInputs = function () {
  48049. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48050. if (this._collisionTriggered) {
  48051. return;
  48052. }
  48053. this.inputs.checkInputs();
  48054. // Inertia
  48055. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48056. var inertialAlphaOffset = this.inertialAlphaOffset;
  48057. if (this.beta <= 0)
  48058. inertialAlphaOffset *= -1;
  48059. if (this.getScene().useRightHandedSystem)
  48060. inertialAlphaOffset *= -1;
  48061. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48062. inertialAlphaOffset *= -1;
  48063. this.alpha += inertialAlphaOffset;
  48064. this.beta += this.inertialBetaOffset;
  48065. this.radius -= this.inertialRadiusOffset;
  48066. this.inertialAlphaOffset *= this.inertia;
  48067. this.inertialBetaOffset *= this.inertia;
  48068. this.inertialRadiusOffset *= this.inertia;
  48069. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48070. this.inertialAlphaOffset = 0;
  48071. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48072. this.inertialBetaOffset = 0;
  48073. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48074. this.inertialRadiusOffset = 0;
  48075. }
  48076. // Panning inertia
  48077. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48078. if (!this._localDirection) {
  48079. this._localDirection = BABYLON.Vector3.Zero();
  48080. this._transformedDirection = BABYLON.Vector3.Zero();
  48081. }
  48082. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48083. this._localDirection.multiplyInPlace(this.panningAxis);
  48084. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48085. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48086. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48087. if (!this.panningAxis.y) {
  48088. this._transformedDirection.y = 0;
  48089. }
  48090. if (!this._targetHost) {
  48091. if (this.panningDistanceLimit) {
  48092. this._transformedDirection.addInPlace(this._target);
  48093. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48094. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48095. this._target.copyFrom(this._transformedDirection);
  48096. }
  48097. }
  48098. else {
  48099. this._target.addInPlace(this._transformedDirection);
  48100. }
  48101. }
  48102. this.inertialPanningX *= this.panningInertia;
  48103. this.inertialPanningY *= this.panningInertia;
  48104. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48105. this.inertialPanningX = 0;
  48106. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48107. this.inertialPanningY = 0;
  48108. }
  48109. // Limits
  48110. this._checkLimits();
  48111. _super.prototype._checkInputs.call(this);
  48112. };
  48113. ArcRotateCamera.prototype._checkLimits = function () {
  48114. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48115. if (this.allowUpsideDown && this.beta > Math.PI) {
  48116. this.beta = this.beta - (2 * Math.PI);
  48117. }
  48118. }
  48119. else {
  48120. if (this.beta < this.lowerBetaLimit) {
  48121. this.beta = this.lowerBetaLimit;
  48122. }
  48123. }
  48124. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48125. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48126. this.beta = this.beta + (2 * Math.PI);
  48127. }
  48128. }
  48129. else {
  48130. if (this.beta > this.upperBetaLimit) {
  48131. this.beta = this.upperBetaLimit;
  48132. }
  48133. }
  48134. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48135. this.alpha = this.lowerAlphaLimit;
  48136. }
  48137. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48138. this.alpha = this.upperAlphaLimit;
  48139. }
  48140. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48141. this.radius = this.lowerRadiusLimit;
  48142. }
  48143. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48144. this.radius = this.upperRadiusLimit;
  48145. }
  48146. };
  48147. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48148. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48149. this.radius = this._computationVector.length();
  48150. if (this.radius === 0) {
  48151. this.radius = 0.0001; // Just to avoid division by zero
  48152. }
  48153. // Alpha
  48154. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48155. if (this._computationVector.z < 0) {
  48156. this.alpha = 2 * Math.PI - this.alpha;
  48157. }
  48158. // Beta
  48159. this.beta = Math.acos(this._computationVector.y / this.radius);
  48160. this._checkLimits();
  48161. };
  48162. ArcRotateCamera.prototype.setPosition = function (position) {
  48163. if (this.position.equals(position)) {
  48164. return;
  48165. }
  48166. this.position.copyFrom(position);
  48167. this.rebuildAnglesAndRadius();
  48168. };
  48169. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48170. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48171. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48172. if (target.getBoundingInfo) {
  48173. if (toBoundingCenter) {
  48174. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48175. }
  48176. else {
  48177. this._targetBoundingCenter = null;
  48178. }
  48179. this._targetHost = target;
  48180. this._target = this._getTargetPosition();
  48181. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48182. }
  48183. else {
  48184. var newTarget = target;
  48185. var currentTarget = this._getTargetPosition();
  48186. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48187. return;
  48188. }
  48189. this._targetHost = null;
  48190. this._target = newTarget;
  48191. this._targetBoundingCenter = null;
  48192. this.onMeshTargetChangedObservable.notifyObservers(null);
  48193. }
  48194. this.rebuildAnglesAndRadius();
  48195. };
  48196. ArcRotateCamera.prototype._getViewMatrix = function () {
  48197. // Compute
  48198. var cosa = Math.cos(this.alpha);
  48199. var sina = Math.sin(this.alpha);
  48200. var cosb = Math.cos(this.beta);
  48201. var sinb = Math.sin(this.beta);
  48202. if (sinb === 0) {
  48203. sinb = 0.0001;
  48204. }
  48205. var target = this._getTargetPosition();
  48206. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48207. target.addToRef(this._computationVector, this._newPosition);
  48208. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48209. if (!this._collider) {
  48210. this._collider = new BABYLON.Collider();
  48211. }
  48212. this._collider._radius = this.collisionRadius;
  48213. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48214. this._collisionTriggered = true;
  48215. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48216. }
  48217. else {
  48218. this.position.copyFrom(this._newPosition);
  48219. var up = this.upVector;
  48220. if (this.allowUpsideDown && sinb < 0) {
  48221. up = up.clone();
  48222. up = up.negate();
  48223. }
  48224. this._computeViewMatrix(this.position, target, up);
  48225. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48226. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48227. }
  48228. this._currentTarget = target;
  48229. return this._viewMatrix;
  48230. };
  48231. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48232. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48233. meshes = meshes || this.getScene().meshes;
  48234. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48235. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48236. this.radius = distance * this.zoomOnFactor;
  48237. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48238. };
  48239. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48240. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48241. var meshesOrMinMaxVector;
  48242. var distance;
  48243. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48244. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48245. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48246. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48247. }
  48248. else { //minMaxVector and distance
  48249. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48250. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48251. distance = minMaxVectorAndDistance.distance;
  48252. }
  48253. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48254. if (!doNotUpdateMaxZ) {
  48255. this.maxZ = distance * 2;
  48256. }
  48257. };
  48258. /**
  48259. * @override
  48260. * Override Camera.createRigCamera
  48261. */
  48262. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48263. var alphaShift = 0;
  48264. switch (this.cameraRigMode) {
  48265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48266. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48267. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48268. case BABYLON.Camera.RIG_MODE_VR:
  48269. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48270. break;
  48271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48272. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48273. break;
  48274. }
  48275. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48276. rigCam._cameraRigParams = {};
  48277. return rigCam;
  48278. };
  48279. /**
  48280. * @override
  48281. * Override Camera._updateRigCameras
  48282. */
  48283. ArcRotateCamera.prototype._updateRigCameras = function () {
  48284. var camLeft = this._rigCameras[0];
  48285. var camRight = this._rigCameras[1];
  48286. camLeft.beta = camRight.beta = this.beta;
  48287. camLeft.radius = camRight.radius = this.radius;
  48288. switch (this.cameraRigMode) {
  48289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48290. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48291. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48292. case BABYLON.Camera.RIG_MODE_VR:
  48293. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48294. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48295. break;
  48296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48297. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48298. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48299. break;
  48300. }
  48301. _super.prototype._updateRigCameras.call(this);
  48302. };
  48303. ArcRotateCamera.prototype.dispose = function () {
  48304. this.inputs.clear();
  48305. _super.prototype.dispose.call(this);
  48306. };
  48307. ArcRotateCamera.prototype.getClassName = function () {
  48308. return "ArcRotateCamera";
  48309. };
  48310. __decorate([
  48311. BABYLON.serialize()
  48312. ], ArcRotateCamera.prototype, "alpha", void 0);
  48313. __decorate([
  48314. BABYLON.serialize()
  48315. ], ArcRotateCamera.prototype, "beta", void 0);
  48316. __decorate([
  48317. BABYLON.serialize()
  48318. ], ArcRotateCamera.prototype, "radius", void 0);
  48319. __decorate([
  48320. BABYLON.serializeAsVector3("target")
  48321. ], ArcRotateCamera.prototype, "_target", void 0);
  48322. __decorate([
  48323. BABYLON.serialize()
  48324. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48325. __decorate([
  48326. BABYLON.serialize()
  48327. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48328. __decorate([
  48329. BABYLON.serialize()
  48330. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48331. __decorate([
  48332. BABYLON.serialize()
  48333. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48334. __decorate([
  48335. BABYLON.serialize()
  48336. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48337. __decorate([
  48338. BABYLON.serialize()
  48339. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48340. __decorate([
  48341. BABYLON.serialize()
  48342. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48343. __decorate([
  48344. BABYLON.serialize()
  48345. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48346. __decorate([
  48347. BABYLON.serialize()
  48348. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48349. __decorate([
  48350. BABYLON.serialize()
  48351. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48352. __decorate([
  48353. BABYLON.serialize()
  48354. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48358. __decorate([
  48359. BABYLON.serialize()
  48360. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48361. __decorate([
  48362. BABYLON.serializeAsVector3()
  48363. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48370. __decorate([
  48371. BABYLON.serialize()
  48372. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48373. return ArcRotateCamera;
  48374. }(BABYLON.TargetCamera));
  48375. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48376. })(BABYLON || (BABYLON = {}));
  48377. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48378. var BABYLON;
  48379. (function (BABYLON) {
  48380. /**
  48381. * The HemisphericLight simulates the ambient environment light,
  48382. * so the passed direction is the light reflection direction, not the incoming direction.
  48383. */
  48384. var HemisphericLight = /** @class */ (function (_super) {
  48385. __extends(HemisphericLight, _super);
  48386. /**
  48387. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48388. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48389. * The HemisphericLight can't cast shadows.
  48390. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48391. * @param name The friendly name of the light
  48392. * @param direction The direction of the light reflection
  48393. * @param scene The scene the light belongs to
  48394. */
  48395. function HemisphericLight(name, direction, scene) {
  48396. var _this = _super.call(this, name, scene) || this;
  48397. /**
  48398. * The groundColor is the light in the opposite direction to the one specified during creation.
  48399. * 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.
  48400. */
  48401. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48402. _this.direction = direction || BABYLON.Vector3.Up();
  48403. return _this;
  48404. }
  48405. HemisphericLight.prototype._buildUniformLayout = function () {
  48406. this._uniformBuffer.addUniform("vLightData", 4);
  48407. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48408. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48409. this._uniformBuffer.addUniform("vLightGround", 3);
  48410. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48411. this._uniformBuffer.addUniform("depthValues", 2);
  48412. this._uniformBuffer.create();
  48413. };
  48414. /**
  48415. * Returns the string "HemisphericLight".
  48416. * @return The class name
  48417. */
  48418. HemisphericLight.prototype.getClassName = function () {
  48419. return "HemisphericLight";
  48420. };
  48421. /**
  48422. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48423. * Returns the updated direction.
  48424. * @param target The target the direction should point to
  48425. * @return The computed direction
  48426. */
  48427. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48428. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48429. return this.direction;
  48430. };
  48431. /**
  48432. * Returns the shadow generator associated to the light.
  48433. * @returns Always null for hemispheric lights because it does not support shadows.
  48434. */
  48435. HemisphericLight.prototype.getShadowGenerator = function () {
  48436. return null;
  48437. };
  48438. /**
  48439. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48440. * @param effect The effect to update
  48441. * @param lightIndex The index of the light in the effect to update
  48442. * @returns The hemispheric light
  48443. */
  48444. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48445. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48446. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48447. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48448. return this;
  48449. };
  48450. /**
  48451. * @hidden internal use only.
  48452. */
  48453. HemisphericLight.prototype._getWorldMatrix = function () {
  48454. if (!this._worldMatrix) {
  48455. this._worldMatrix = BABYLON.Matrix.Identity();
  48456. }
  48457. return this._worldMatrix;
  48458. };
  48459. /**
  48460. * Returns the integer 3.
  48461. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48462. */
  48463. HemisphericLight.prototype.getTypeID = function () {
  48464. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48465. };
  48466. __decorate([
  48467. BABYLON.serializeAsColor3()
  48468. ], HemisphericLight.prototype, "groundColor", void 0);
  48469. __decorate([
  48470. BABYLON.serializeAsVector3()
  48471. ], HemisphericLight.prototype, "direction", void 0);
  48472. return HemisphericLight;
  48473. }(BABYLON.Light));
  48474. BABYLON.HemisphericLight = HemisphericLight;
  48475. })(BABYLON || (BABYLON = {}));
  48476. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48477. var BABYLON;
  48478. (function (BABYLON) {
  48479. /**
  48480. * Base implementation IShadowLight
  48481. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48482. */
  48483. var ShadowLight = /** @class */ (function (_super) {
  48484. __extends(ShadowLight, _super);
  48485. function ShadowLight() {
  48486. var _this = _super !== null && _super.apply(this, arguments) || this;
  48487. _this._needProjectionMatrixCompute = true;
  48488. return _this;
  48489. }
  48490. ShadowLight.prototype._setPosition = function (value) {
  48491. this._position = value;
  48492. };
  48493. Object.defineProperty(ShadowLight.prototype, "position", {
  48494. /**
  48495. * Sets the position the shadow will be casted from. Also use as the light position for both
  48496. * point and spot lights.
  48497. */
  48498. get: function () {
  48499. return this._position;
  48500. },
  48501. /**
  48502. * Sets the position the shadow will be casted from. Also use as the light position for both
  48503. * point and spot lights.
  48504. */
  48505. set: function (value) {
  48506. this._setPosition(value);
  48507. },
  48508. enumerable: true,
  48509. configurable: true
  48510. });
  48511. ShadowLight.prototype._setDirection = function (value) {
  48512. this._direction = value;
  48513. };
  48514. Object.defineProperty(ShadowLight.prototype, "direction", {
  48515. /**
  48516. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48517. * Also use as the light direction on spot and directional lights.
  48518. */
  48519. get: function () {
  48520. return this._direction;
  48521. },
  48522. /**
  48523. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48524. * Also use as the light direction on spot and directional lights.
  48525. */
  48526. set: function (value) {
  48527. this._setDirection(value);
  48528. },
  48529. enumerable: true,
  48530. configurable: true
  48531. });
  48532. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48533. /**
  48534. * Gets the shadow projection clipping minimum z value.
  48535. */
  48536. get: function () {
  48537. return this._shadowMinZ;
  48538. },
  48539. /**
  48540. * Sets the shadow projection clipping minimum z value.
  48541. */
  48542. set: function (value) {
  48543. this._shadowMinZ = value;
  48544. this.forceProjectionMatrixCompute();
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48550. /**
  48551. * Sets the shadow projection clipping maximum z value.
  48552. */
  48553. get: function () {
  48554. return this._shadowMaxZ;
  48555. },
  48556. /**
  48557. * Gets the shadow projection clipping maximum z value.
  48558. */
  48559. set: function (value) {
  48560. this._shadowMaxZ = value;
  48561. this.forceProjectionMatrixCompute();
  48562. },
  48563. enumerable: true,
  48564. configurable: true
  48565. });
  48566. /**
  48567. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48568. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48569. */
  48570. ShadowLight.prototype.computeTransformedInformation = function () {
  48571. if (this.parent && this.parent.getWorldMatrix) {
  48572. if (!this.transformedPosition) {
  48573. this.transformedPosition = BABYLON.Vector3.Zero();
  48574. }
  48575. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48576. // In case the direction is present.
  48577. if (this.direction) {
  48578. if (!this.transformedDirection) {
  48579. this.transformedDirection = BABYLON.Vector3.Zero();
  48580. }
  48581. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48582. }
  48583. return true;
  48584. }
  48585. return false;
  48586. };
  48587. /**
  48588. * Return the depth scale used for the shadow map.
  48589. * @returns the depth scale.
  48590. */
  48591. ShadowLight.prototype.getDepthScale = function () {
  48592. return 50.0;
  48593. };
  48594. /**
  48595. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48596. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48597. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48598. */
  48599. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48600. return this.transformedDirection ? this.transformedDirection : this.direction;
  48601. };
  48602. /**
  48603. * Returns the ShadowLight absolute position in the World.
  48604. * @returns the position vector in world space
  48605. */
  48606. ShadowLight.prototype.getAbsolutePosition = function () {
  48607. return this.transformedPosition ? this.transformedPosition : this.position;
  48608. };
  48609. /**
  48610. * Sets the ShadowLight direction toward the passed target.
  48611. * @param target The point tot target in local space
  48612. * @returns the updated ShadowLight direction
  48613. */
  48614. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48615. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48616. return this.direction;
  48617. };
  48618. /**
  48619. * Returns the light rotation in euler definition.
  48620. * @returns the x y z rotation in local space.
  48621. */
  48622. ShadowLight.prototype.getRotation = function () {
  48623. this.direction.normalize();
  48624. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48625. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48626. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48627. };
  48628. /**
  48629. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48630. * @returns true if a cube texture needs to be use
  48631. */
  48632. ShadowLight.prototype.needCube = function () {
  48633. return false;
  48634. };
  48635. /**
  48636. * Detects if the projection matrix requires to be recomputed this frame.
  48637. * @returns true if it requires to be recomputed otherwise, false.
  48638. */
  48639. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48640. return this._needProjectionMatrixCompute;
  48641. };
  48642. /**
  48643. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48644. */
  48645. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48646. this._needProjectionMatrixCompute = true;
  48647. };
  48648. /**
  48649. * Get the world matrix of the sahdow lights.
  48650. * @hidden Internal Use Only
  48651. */
  48652. ShadowLight.prototype._getWorldMatrix = function () {
  48653. if (!this._worldMatrix) {
  48654. this._worldMatrix = BABYLON.Matrix.Identity();
  48655. }
  48656. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48657. return this._worldMatrix;
  48658. };
  48659. /**
  48660. * Gets the minZ used for shadow according to both the scene and the light.
  48661. * @param activeCamera The camera we are returning the min for
  48662. * @returns the depth min z
  48663. */
  48664. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48665. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48666. };
  48667. /**
  48668. * Gets the maxZ used for shadow according to both the scene and the light.
  48669. * @param activeCamera The camera we are returning the max for
  48670. * @returns the depth max z
  48671. */
  48672. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48673. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48674. };
  48675. /**
  48676. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48677. * @param matrix The materix to updated with the projection information
  48678. * @param viewMatrix The transform matrix of the light
  48679. * @param renderList The list of mesh to render in the map
  48680. * @returns The current light
  48681. */
  48682. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48683. if (this.customProjectionMatrixBuilder) {
  48684. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48685. }
  48686. else {
  48687. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48688. }
  48689. return this;
  48690. };
  48691. __decorate([
  48692. BABYLON.serializeAsVector3()
  48693. ], ShadowLight.prototype, "position", null);
  48694. __decorate([
  48695. BABYLON.serializeAsVector3()
  48696. ], ShadowLight.prototype, "direction", null);
  48697. __decorate([
  48698. BABYLON.serialize()
  48699. ], ShadowLight.prototype, "shadowMinZ", null);
  48700. __decorate([
  48701. BABYLON.serialize()
  48702. ], ShadowLight.prototype, "shadowMaxZ", null);
  48703. return ShadowLight;
  48704. }(BABYLON.Light));
  48705. BABYLON.ShadowLight = ShadowLight;
  48706. })(BABYLON || (BABYLON = {}));
  48707. //# sourceMappingURL=babylon.shadowLight.js.map
  48708. var BABYLON;
  48709. (function (BABYLON) {
  48710. /**
  48711. * A point light is a light defined by an unique point in world space.
  48712. * The light is emitted in every direction from this point.
  48713. * A good example of a point light is a standard light bulb.
  48714. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48715. */
  48716. var PointLight = /** @class */ (function (_super) {
  48717. __extends(PointLight, _super);
  48718. /**
  48719. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48720. * A PointLight emits the light in every direction.
  48721. * It can cast shadows.
  48722. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48723. * ```javascript
  48724. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48725. * ```
  48726. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48727. * @param name The light friendly name
  48728. * @param position The position of the point light in the scene
  48729. * @param scene The scene the lights belongs to
  48730. */
  48731. function PointLight(name, position, scene) {
  48732. var _this = _super.call(this, name, scene) || this;
  48733. _this._shadowAngle = Math.PI / 2;
  48734. _this.position = position;
  48735. return _this;
  48736. }
  48737. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48738. /**
  48739. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48740. * This specifies what angle the shadow will use to be created.
  48741. *
  48742. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48743. */
  48744. get: function () {
  48745. return this._shadowAngle;
  48746. },
  48747. /**
  48748. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48749. * This specifies what angle the shadow will use to be created.
  48750. *
  48751. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48752. */
  48753. set: function (value) {
  48754. this._shadowAngle = value;
  48755. this.forceProjectionMatrixCompute();
  48756. },
  48757. enumerable: true,
  48758. configurable: true
  48759. });
  48760. Object.defineProperty(PointLight.prototype, "direction", {
  48761. /**
  48762. * Gets the direction if it has been set.
  48763. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48764. */
  48765. get: function () {
  48766. return this._direction;
  48767. },
  48768. /**
  48769. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48770. */
  48771. set: function (value) {
  48772. var previousNeedCube = this.needCube();
  48773. this._direction = value;
  48774. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48775. this._shadowGenerator.recreateShadowMap();
  48776. }
  48777. },
  48778. enumerable: true,
  48779. configurable: true
  48780. });
  48781. /**
  48782. * Returns the string "PointLight"
  48783. * @returns the class name
  48784. */
  48785. PointLight.prototype.getClassName = function () {
  48786. return "PointLight";
  48787. };
  48788. /**
  48789. * Returns the integer 0.
  48790. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48791. */
  48792. PointLight.prototype.getTypeID = function () {
  48793. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48794. };
  48795. /**
  48796. * Specifies wether or not the shadowmap should be a cube texture.
  48797. * @returns true if the shadowmap needs to be a cube texture.
  48798. */
  48799. PointLight.prototype.needCube = function () {
  48800. return !this.direction;
  48801. };
  48802. /**
  48803. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48804. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48805. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48806. */
  48807. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48808. if (this.direction) {
  48809. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48810. }
  48811. else {
  48812. switch (faceIndex) {
  48813. case 0:
  48814. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48815. case 1:
  48816. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48817. case 2:
  48818. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48819. case 3:
  48820. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48821. case 4:
  48822. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48823. case 5:
  48824. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48825. }
  48826. }
  48827. return BABYLON.Vector3.Zero();
  48828. };
  48829. /**
  48830. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48831. * - fov = PI / 2
  48832. * - aspect ratio : 1.0
  48833. * - z-near and far equal to the active camera minZ and maxZ.
  48834. * Returns the PointLight.
  48835. */
  48836. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48837. var activeCamera = this.getScene().activeCamera;
  48838. if (!activeCamera) {
  48839. return;
  48840. }
  48841. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48842. };
  48843. PointLight.prototype._buildUniformLayout = function () {
  48844. this._uniformBuffer.addUniform("vLightData", 4);
  48845. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48846. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48847. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48848. this._uniformBuffer.addUniform("depthValues", 2);
  48849. this._uniformBuffer.create();
  48850. };
  48851. /**
  48852. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48853. * @param effect The effect to update
  48854. * @param lightIndex The index of the light in the effect to update
  48855. * @returns The point light
  48856. */
  48857. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48858. if (this.computeTransformedInformation()) {
  48859. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48860. return this;
  48861. }
  48862. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48863. return this;
  48864. };
  48865. __decorate([
  48866. BABYLON.serialize()
  48867. ], PointLight.prototype, "shadowAngle", null);
  48868. return PointLight;
  48869. }(BABYLON.ShadowLight));
  48870. BABYLON.PointLight = PointLight;
  48871. })(BABYLON || (BABYLON = {}));
  48872. //# sourceMappingURL=babylon.pointLight.js.map
  48873. var BABYLON;
  48874. (function (BABYLON) {
  48875. /**
  48876. * A directional light is defined by a direction (what a surprise!).
  48877. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48878. * 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.
  48879. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48880. */
  48881. var DirectionalLight = /** @class */ (function (_super) {
  48882. __extends(DirectionalLight, _super);
  48883. /**
  48884. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48885. * The directional light is emitted from everywhere in the given direction.
  48886. * It can cast shawdows.
  48887. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48888. * @param name The friendly name of the light
  48889. * @param direction The direction of the light
  48890. * @param scene The scene the light belongs to
  48891. */
  48892. function DirectionalLight(name, direction, scene) {
  48893. var _this = _super.call(this, name, scene) || this;
  48894. _this._shadowFrustumSize = 0;
  48895. _this._shadowOrthoScale = 0.1;
  48896. /**
  48897. * Automatically compute the projection matrix to best fit (including all the casters)
  48898. * on each frame.
  48899. */
  48900. _this.autoUpdateExtends = true;
  48901. // Cache
  48902. _this._orthoLeft = Number.MAX_VALUE;
  48903. _this._orthoRight = Number.MIN_VALUE;
  48904. _this._orthoTop = Number.MIN_VALUE;
  48905. _this._orthoBottom = Number.MAX_VALUE;
  48906. _this.position = direction.scale(-1.0);
  48907. _this.direction = direction;
  48908. return _this;
  48909. }
  48910. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48911. /**
  48912. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48913. */
  48914. get: function () {
  48915. return this._shadowFrustumSize;
  48916. },
  48917. /**
  48918. * Specifies a fix frustum size for the shadow generation.
  48919. */
  48920. set: function (value) {
  48921. this._shadowFrustumSize = value;
  48922. this.forceProjectionMatrixCompute();
  48923. },
  48924. enumerable: true,
  48925. configurable: true
  48926. });
  48927. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48928. /**
  48929. * Gets the shadow projection scale against the optimal computed one.
  48930. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48931. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48932. */
  48933. get: function () {
  48934. return this._shadowOrthoScale;
  48935. },
  48936. /**
  48937. * Sets the shadow projection scale against the optimal computed one.
  48938. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48939. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48940. */
  48941. set: function (value) {
  48942. this._shadowOrthoScale = value;
  48943. this.forceProjectionMatrixCompute();
  48944. },
  48945. enumerable: true,
  48946. configurable: true
  48947. });
  48948. /**
  48949. * Returns the string "DirectionalLight".
  48950. * @return The class name
  48951. */
  48952. DirectionalLight.prototype.getClassName = function () {
  48953. return "DirectionalLight";
  48954. };
  48955. /**
  48956. * Returns the integer 1.
  48957. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48958. */
  48959. DirectionalLight.prototype.getTypeID = function () {
  48960. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48961. };
  48962. /**
  48963. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48964. * Returns the DirectionalLight Shadow projection matrix.
  48965. */
  48966. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48967. if (this.shadowFrustumSize > 0) {
  48968. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48969. }
  48970. else {
  48971. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48972. }
  48973. };
  48974. /**
  48975. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48976. * Returns the DirectionalLight Shadow projection matrix.
  48977. */
  48978. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48979. var activeCamera = this.getScene().activeCamera;
  48980. if (!activeCamera) {
  48981. return;
  48982. }
  48983. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48984. };
  48985. /**
  48986. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48987. * Returns the DirectionalLight Shadow projection matrix.
  48988. */
  48989. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48990. var activeCamera = this.getScene().activeCamera;
  48991. if (!activeCamera) {
  48992. return;
  48993. }
  48994. // Check extends
  48995. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48996. var tempVector3 = BABYLON.Vector3.Zero();
  48997. this._orthoLeft = Number.MAX_VALUE;
  48998. this._orthoRight = Number.MIN_VALUE;
  48999. this._orthoTop = Number.MIN_VALUE;
  49000. this._orthoBottom = Number.MAX_VALUE;
  49001. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49002. var mesh = renderList[meshIndex];
  49003. if (!mesh) {
  49004. continue;
  49005. }
  49006. var boundingInfo = mesh.getBoundingInfo();
  49007. var boundingBox = boundingInfo.boundingBox;
  49008. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49009. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49010. if (tempVector3.x < this._orthoLeft)
  49011. this._orthoLeft = tempVector3.x;
  49012. if (tempVector3.y < this._orthoBottom)
  49013. this._orthoBottom = tempVector3.y;
  49014. if (tempVector3.x > this._orthoRight)
  49015. this._orthoRight = tempVector3.x;
  49016. if (tempVector3.y > this._orthoTop)
  49017. this._orthoTop = tempVector3.y;
  49018. }
  49019. }
  49020. }
  49021. var xOffset = this._orthoRight - this._orthoLeft;
  49022. var yOffset = this._orthoTop - this._orthoBottom;
  49023. 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);
  49024. };
  49025. DirectionalLight.prototype._buildUniformLayout = function () {
  49026. this._uniformBuffer.addUniform("vLightData", 4);
  49027. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49028. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49029. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49030. this._uniformBuffer.addUniform("depthValues", 2);
  49031. this._uniformBuffer.create();
  49032. };
  49033. /**
  49034. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49035. * @param effect The effect to update
  49036. * @param lightIndex The index of the light in the effect to update
  49037. * @returns The directional light
  49038. */
  49039. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49040. if (this.computeTransformedInformation()) {
  49041. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49042. return this;
  49043. }
  49044. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49045. return this;
  49046. };
  49047. /**
  49048. * Gets the minZ used for shadow according to both the scene and the light.
  49049. *
  49050. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49051. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49052. * @param activeCamera The camera we are returning the min for
  49053. * @returns the depth min z
  49054. */
  49055. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49056. return 1;
  49057. };
  49058. /**
  49059. * Gets the maxZ used for shadow according to both the scene and the light.
  49060. *
  49061. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49062. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49063. * @param activeCamera The camera we are returning the max for
  49064. * @returns the depth max z
  49065. */
  49066. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49067. return 1;
  49068. };
  49069. __decorate([
  49070. BABYLON.serialize()
  49071. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49072. __decorate([
  49073. BABYLON.serialize()
  49074. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49075. __decorate([
  49076. BABYLON.serialize()
  49077. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49078. return DirectionalLight;
  49079. }(BABYLON.ShadowLight));
  49080. BABYLON.DirectionalLight = DirectionalLight;
  49081. })(BABYLON || (BABYLON = {}));
  49082. //# sourceMappingURL=babylon.directionalLight.js.map
  49083. var BABYLON;
  49084. (function (BABYLON) {
  49085. /**
  49086. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49087. * These values define a cone of light starting from the position, emitting toward the direction.
  49088. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49089. * and the exponent defines the speed of the decay of the light with distance (reach).
  49090. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49091. */
  49092. var SpotLight = /** @class */ (function (_super) {
  49093. __extends(SpotLight, _super);
  49094. /**
  49095. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49096. * It can cast shadows.
  49097. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49098. * @param name The light friendly name
  49099. * @param position The position of the spot light in the scene
  49100. * @param direction The direction of the light in the scene
  49101. * @param angle The cone angle of the light in Radians
  49102. * @param exponent The light decay speed with the distance from the emission spot
  49103. * @param scene The scene the lights belongs to
  49104. */
  49105. function SpotLight(name, position, direction, angle, exponent, scene) {
  49106. var _this = _super.call(this, name, scene) || this;
  49107. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49108. _this._projectionTextureLightNear = 1e-6;
  49109. _this._projectionTextureLightFar = 1000.0;
  49110. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49111. _this._projectionTextureViewLightDirty = true;
  49112. _this._projectionTextureProjectionLightDirty = true;
  49113. _this._projectionTextureDirty = true;
  49114. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49115. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49116. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49117. _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);
  49118. _this.position = position;
  49119. _this.direction = direction;
  49120. _this.angle = angle;
  49121. _this.exponent = exponent;
  49122. return _this;
  49123. }
  49124. Object.defineProperty(SpotLight.prototype, "angle", {
  49125. /**
  49126. * Gets the cone angle of the spot light in Radians.
  49127. */
  49128. get: function () {
  49129. return this._angle;
  49130. },
  49131. /**
  49132. * Sets the cone angle of the spot light in Radians.
  49133. */
  49134. set: function (value) {
  49135. this._angle = value;
  49136. this._projectionTextureProjectionLightDirty = true;
  49137. this.forceProjectionMatrixCompute();
  49138. },
  49139. enumerable: true,
  49140. configurable: true
  49141. });
  49142. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49143. /**
  49144. * Allows scaling the angle of the light for shadow generation only.
  49145. */
  49146. get: function () {
  49147. return this._shadowAngleScale;
  49148. },
  49149. /**
  49150. * Allows scaling the angle of the light for shadow generation only.
  49151. */
  49152. set: function (value) {
  49153. this._shadowAngleScale = value;
  49154. this.forceProjectionMatrixCompute();
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49160. /**
  49161. * Allows reading the projecton texture
  49162. */
  49163. get: function () {
  49164. return this._projectionTextureMatrix;
  49165. },
  49166. enumerable: true,
  49167. configurable: true
  49168. });
  49169. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49170. /**
  49171. * Gets the near clip of the Spotlight for texture projection.
  49172. */
  49173. get: function () {
  49174. return this._projectionTextureLightNear;
  49175. },
  49176. /**
  49177. * Sets the near clip of the Spotlight for texture projection.
  49178. */
  49179. set: function (value) {
  49180. this._projectionTextureLightNear = value;
  49181. this._projectionTextureProjectionLightDirty = true;
  49182. },
  49183. enumerable: true,
  49184. configurable: true
  49185. });
  49186. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49187. /**
  49188. * Gets the far clip of the Spotlight for texture projection.
  49189. */
  49190. get: function () {
  49191. return this._projectionTextureLightFar;
  49192. },
  49193. /**
  49194. * Sets the far clip of the Spotlight for texture projection.
  49195. */
  49196. set: function (value) {
  49197. this._projectionTextureLightFar = value;
  49198. this._projectionTextureProjectionLightDirty = true;
  49199. },
  49200. enumerable: true,
  49201. configurable: true
  49202. });
  49203. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49204. /**
  49205. * Gets the Up vector of the Spotlight for texture projection.
  49206. */
  49207. get: function () {
  49208. return this._projectionTextureUpDirection;
  49209. },
  49210. /**
  49211. * Sets the Up vector of the Spotlight for texture projection.
  49212. */
  49213. set: function (value) {
  49214. this._projectionTextureUpDirection = value;
  49215. this._projectionTextureProjectionLightDirty = true;
  49216. },
  49217. enumerable: true,
  49218. configurable: true
  49219. });
  49220. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49221. /**
  49222. * Gets the projection texture of the light.
  49223. */
  49224. get: function () {
  49225. return this._projectionTexture;
  49226. },
  49227. /**
  49228. * Sets the projection texture of the light.
  49229. */
  49230. set: function (value) {
  49231. this._projectionTexture = value;
  49232. this._projectionTextureDirty = true;
  49233. },
  49234. enumerable: true,
  49235. configurable: true
  49236. });
  49237. /**
  49238. * Returns the string "SpotLight".
  49239. * @returns the class name
  49240. */
  49241. SpotLight.prototype.getClassName = function () {
  49242. return "SpotLight";
  49243. };
  49244. /**
  49245. * Returns the integer 2.
  49246. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49247. */
  49248. SpotLight.prototype.getTypeID = function () {
  49249. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49250. };
  49251. /**
  49252. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49253. */
  49254. SpotLight.prototype._setDirection = function (value) {
  49255. _super.prototype._setDirection.call(this, value);
  49256. this._projectionTextureViewLightDirty = true;
  49257. };
  49258. /**
  49259. * Overrides the position setter to recompute the projection texture view light Matrix.
  49260. */
  49261. SpotLight.prototype._setPosition = function (value) {
  49262. _super.prototype._setPosition.call(this, value);
  49263. this._projectionTextureViewLightDirty = true;
  49264. };
  49265. /**
  49266. * 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.
  49267. * Returns the SpotLight.
  49268. */
  49269. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49270. var activeCamera = this.getScene().activeCamera;
  49271. if (!activeCamera) {
  49272. return;
  49273. }
  49274. this._shadowAngleScale = this._shadowAngleScale || 1;
  49275. var angle = this._shadowAngleScale * this._angle;
  49276. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49277. };
  49278. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49279. this._projectionTextureViewLightDirty = false;
  49280. this._projectionTextureDirty = true;
  49281. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49282. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49283. };
  49284. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49285. this._projectionTextureProjectionLightDirty = false;
  49286. this._projectionTextureDirty = true;
  49287. var light_far = this.projectionTextureLightFar;
  49288. var light_near = this.projectionTextureLightNear;
  49289. var P = light_far / (light_far - light_near);
  49290. var Q = -P * light_near;
  49291. var S = 1.0 / Math.tan(this._angle / 2.0);
  49292. var A = 1.0;
  49293. 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);
  49294. };
  49295. /**
  49296. * Main function for light texture projection matrix computing.
  49297. */
  49298. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49299. this._projectionTextureDirty = false;
  49300. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49301. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49302. };
  49303. SpotLight.prototype._buildUniformLayout = function () {
  49304. this._uniformBuffer.addUniform("vLightData", 4);
  49305. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49306. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49307. this._uniformBuffer.addUniform("vLightDirection", 3);
  49308. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49309. this._uniformBuffer.addUniform("depthValues", 2);
  49310. this._uniformBuffer.create();
  49311. };
  49312. /**
  49313. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49314. * @param effect The effect to update
  49315. * @param lightIndex The index of the light in the effect to update
  49316. * @returns The spot light
  49317. */
  49318. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49319. var normalizeDirection;
  49320. if (this.computeTransformedInformation()) {
  49321. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49322. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49323. }
  49324. else {
  49325. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49326. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49327. }
  49328. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49329. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49330. if (this._projectionTextureViewLightDirty) {
  49331. this._computeProjectionTextureViewLightMatrix();
  49332. }
  49333. if (this._projectionTextureProjectionLightDirty) {
  49334. this._computeProjectionTextureProjectionLightMatrix();
  49335. }
  49336. if (this._projectionTextureDirty) {
  49337. this._computeProjectionTextureMatrix();
  49338. }
  49339. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49340. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49341. }
  49342. return this;
  49343. };
  49344. /**
  49345. * Disposes the light and the associated resources.
  49346. */
  49347. SpotLight.prototype.dispose = function () {
  49348. _super.prototype.dispose.call(this);
  49349. if (this._projectionTexture) {
  49350. this._projectionTexture.dispose();
  49351. }
  49352. };
  49353. __decorate([
  49354. BABYLON.serialize()
  49355. ], SpotLight.prototype, "angle", null);
  49356. __decorate([
  49357. BABYLON.serialize()
  49358. ], SpotLight.prototype, "shadowAngleScale", null);
  49359. __decorate([
  49360. BABYLON.serialize()
  49361. ], SpotLight.prototype, "exponent", void 0);
  49362. __decorate([
  49363. BABYLON.serialize()
  49364. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49365. __decorate([
  49366. BABYLON.serialize()
  49367. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49368. __decorate([
  49369. BABYLON.serialize()
  49370. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49371. __decorate([
  49372. BABYLON.serializeAsTexture("projectedLightTexture")
  49373. ], SpotLight.prototype, "_projectionTexture", void 0);
  49374. return SpotLight;
  49375. }(BABYLON.ShadowLight));
  49376. BABYLON.SpotLight = SpotLight;
  49377. })(BABYLON || (BABYLON = {}));
  49378. //# sourceMappingURL=babylon.spotLight.js.map
  49379. var BABYLON;
  49380. (function (BABYLON) {
  49381. /**
  49382. * Class used to override all child animations of a given target
  49383. */
  49384. var AnimationPropertiesOverride = /** @class */ (function () {
  49385. function AnimationPropertiesOverride() {
  49386. /**
  49387. * Gets or sets a value indicating if animation blending must be used
  49388. */
  49389. this.enableBlending = false;
  49390. /**
  49391. * Gets or sets the blending speed to use when enableBlending is true
  49392. */
  49393. this.blendingSpeed = 0.01;
  49394. /**
  49395. * Gets or sets the default loop mode to use
  49396. */
  49397. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49398. }
  49399. return AnimationPropertiesOverride;
  49400. }());
  49401. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49402. })(BABYLON || (BABYLON = {}));
  49403. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49404. var BABYLON;
  49405. (function (BABYLON) {
  49406. /**
  49407. * Represents the range of an animation
  49408. */
  49409. var AnimationRange = /** @class */ (function () {
  49410. /**
  49411. * Initializes the range of an animation
  49412. * @param name The name of the animation range
  49413. * @param from The starting frame of the animation
  49414. * @param to The ending frame of the animation
  49415. */
  49416. function AnimationRange(
  49417. /**The name of the animation range**/
  49418. name,
  49419. /**The starting frame of the animation */
  49420. from,
  49421. /**The ending frame of the animation*/
  49422. to) {
  49423. this.name = name;
  49424. this.from = from;
  49425. this.to = to;
  49426. }
  49427. /**
  49428. * Makes a copy of the animation range
  49429. * @returns A copy of the animation range
  49430. */
  49431. AnimationRange.prototype.clone = function () {
  49432. return new AnimationRange(this.name, this.from, this.to);
  49433. };
  49434. return AnimationRange;
  49435. }());
  49436. BABYLON.AnimationRange = AnimationRange;
  49437. /**
  49438. * Composed of a frame, and an action function
  49439. */
  49440. var AnimationEvent = /** @class */ (function () {
  49441. /**
  49442. * Initializes the animation event
  49443. * @param frame The frame for which the event is triggered
  49444. * @param action The event to perform when triggered
  49445. * @param onlyOnce Specifies if the event should be triggered only once
  49446. */
  49447. function AnimationEvent(
  49448. /** The frame for which the event is triggered **/
  49449. frame,
  49450. /** The event to perform when triggered **/
  49451. action,
  49452. /** Specifies if the event should be triggered only once**/
  49453. onlyOnce) {
  49454. this.frame = frame;
  49455. this.action = action;
  49456. this.onlyOnce = onlyOnce;
  49457. /**
  49458. * Specifies if the animation event is done
  49459. */
  49460. this.isDone = false;
  49461. }
  49462. /** @hidden */
  49463. AnimationEvent.prototype._clone = function () {
  49464. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49465. };
  49466. return AnimationEvent;
  49467. }());
  49468. BABYLON.AnimationEvent = AnimationEvent;
  49469. /**
  49470. * A cursor which tracks a point on a path
  49471. */
  49472. var PathCursor = /** @class */ (function () {
  49473. /**
  49474. * Initializes the path cursor
  49475. * @param path The path to track
  49476. */
  49477. function PathCursor(path) {
  49478. this.path = path;
  49479. /**
  49480. * Stores path cursor callbacks for when an onchange event is triggered
  49481. */
  49482. this._onchange = new Array();
  49483. /**
  49484. * The value of the path cursor
  49485. */
  49486. this.value = 0;
  49487. /**
  49488. * The animation array of the path cursor
  49489. */
  49490. this.animations = new Array();
  49491. }
  49492. /**
  49493. * Gets the cursor point on the path
  49494. * @returns A point on the path cursor at the cursor location
  49495. */
  49496. PathCursor.prototype.getPoint = function () {
  49497. var point = this.path.getPointAtLengthPosition(this.value);
  49498. return new BABYLON.Vector3(point.x, 0, point.y);
  49499. };
  49500. /**
  49501. * Moves the cursor ahead by the step amount
  49502. * @param step The amount to move the cursor forward
  49503. * @returns This path cursor
  49504. */
  49505. PathCursor.prototype.moveAhead = function (step) {
  49506. if (step === void 0) { step = 0.002; }
  49507. this.move(step);
  49508. return this;
  49509. };
  49510. /**
  49511. * Moves the cursor behind by the step amount
  49512. * @param step The amount to move the cursor back
  49513. * @returns This path cursor
  49514. */
  49515. PathCursor.prototype.moveBack = function (step) {
  49516. if (step === void 0) { step = 0.002; }
  49517. this.move(-step);
  49518. return this;
  49519. };
  49520. /**
  49521. * Moves the cursor by the step amount
  49522. * If the step amount is greater than one, an exception is thrown
  49523. * @param step The amount to move the cursor
  49524. * @returns This path cursor
  49525. */
  49526. PathCursor.prototype.move = function (step) {
  49527. if (Math.abs(step) > 1) {
  49528. throw "step size should be less than 1.";
  49529. }
  49530. this.value += step;
  49531. this.ensureLimits();
  49532. this.raiseOnChange();
  49533. return this;
  49534. };
  49535. /**
  49536. * Ensures that the value is limited between zero and one
  49537. * @returns This path cursor
  49538. */
  49539. PathCursor.prototype.ensureLimits = function () {
  49540. while (this.value > 1) {
  49541. this.value -= 1;
  49542. }
  49543. while (this.value < 0) {
  49544. this.value += 1;
  49545. }
  49546. return this;
  49547. };
  49548. /**
  49549. * Runs onchange callbacks on change (used by the animation engine)
  49550. * @returns This path cursor
  49551. */
  49552. PathCursor.prototype.raiseOnChange = function () {
  49553. var _this = this;
  49554. this._onchange.forEach(function (f) { return f(_this); });
  49555. return this;
  49556. };
  49557. /**
  49558. * Executes a function on change
  49559. * @param f A path cursor onchange callback
  49560. * @returns This path cursor
  49561. */
  49562. PathCursor.prototype.onchange = function (f) {
  49563. this._onchange.push(f);
  49564. return this;
  49565. };
  49566. return PathCursor;
  49567. }());
  49568. BABYLON.PathCursor = PathCursor;
  49569. /**
  49570. * Enum for the animation key frame interpolation type
  49571. */
  49572. var AnimationKeyInterpolation;
  49573. (function (AnimationKeyInterpolation) {
  49574. /**
  49575. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49576. */
  49577. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49578. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49579. /**
  49580. * Class used to store any kind of animation
  49581. */
  49582. var Animation = /** @class */ (function () {
  49583. /**
  49584. * Initializes the animation
  49585. * @param name Name of the animation
  49586. * @param targetProperty Property to animate
  49587. * @param framePerSecond The frames per second of the animation
  49588. * @param dataType The data type of the animation
  49589. * @param loopMode The loop mode of the animation
  49590. * @param enableBlendings Specifies if blending should be enabled
  49591. */
  49592. function Animation(
  49593. /**Name of the animation */
  49594. name,
  49595. /**Property to animate */
  49596. targetProperty,
  49597. /**The frames per second of the animation */
  49598. framePerSecond,
  49599. /**The data type of the animation */
  49600. dataType,
  49601. /**The loop mode of the animation */
  49602. loopMode,
  49603. /**Specifies if blending should be enabled */
  49604. enableBlending) {
  49605. this.name = name;
  49606. this.targetProperty = targetProperty;
  49607. this.framePerSecond = framePerSecond;
  49608. this.dataType = dataType;
  49609. this.loopMode = loopMode;
  49610. this.enableBlending = enableBlending;
  49611. /**
  49612. * @hidden Internal use only
  49613. */
  49614. this._runtimeAnimations = new Array();
  49615. /**
  49616. * The set of event that will be linked to this animation
  49617. */
  49618. this._events = new Array();
  49619. /**
  49620. * Stores the blending speed of the animation
  49621. */
  49622. this.blendingSpeed = 0.01;
  49623. /**
  49624. * Stores the animation ranges for the animation
  49625. */
  49626. this._ranges = {};
  49627. this.targetPropertyPath = targetProperty.split(".");
  49628. this.dataType = dataType;
  49629. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49630. }
  49631. /**
  49632. * @hidden Internal use
  49633. */
  49634. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49635. var dataType = undefined;
  49636. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49637. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49638. }
  49639. else if (from instanceof BABYLON.Quaternion) {
  49640. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49641. }
  49642. else if (from instanceof BABYLON.Vector3) {
  49643. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49644. }
  49645. else if (from instanceof BABYLON.Vector2) {
  49646. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49647. }
  49648. else if (from instanceof BABYLON.Color3) {
  49649. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49650. }
  49651. else if (from instanceof BABYLON.Size) {
  49652. dataType = Animation.ANIMATIONTYPE_SIZE;
  49653. }
  49654. if (dataType == undefined) {
  49655. return null;
  49656. }
  49657. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49658. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49659. animation.setKeys(keys);
  49660. if (easingFunction !== undefined) {
  49661. animation.setEasingFunction(easingFunction);
  49662. }
  49663. return animation;
  49664. };
  49665. /**
  49666. * Sets up an animation
  49667. * @param property The property to animate
  49668. * @param animationType The animation type to apply
  49669. * @param framePerSecond The frames per second of the animation
  49670. * @param easingFunction The easing function used in the animation
  49671. * @returns The created animation
  49672. */
  49673. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49674. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49675. animation.setEasingFunction(easingFunction);
  49676. return animation;
  49677. };
  49678. /**
  49679. * Create and start an animation on a node
  49680. * @param name defines the name of the global animation that will be run on all nodes
  49681. * @param node defines the root node where the animation will take place
  49682. * @param targetProperty defines property to animate
  49683. * @param framePerSecond defines the number of frame per second yo use
  49684. * @param totalFrame defines the number of frames in total
  49685. * @param from defines the initial value
  49686. * @param to defines the final value
  49687. * @param loopMode defines which loop mode you want to use (off by default)
  49688. * @param easingFunction defines the easing function to use (linear by default)
  49689. * @param onAnimationEnd defines the callback to call when animation end
  49690. * @returns the animatable created for this animation
  49691. */
  49692. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49693. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49694. if (!animation) {
  49695. return null;
  49696. }
  49697. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49698. };
  49699. /**
  49700. * Create and start an animation on a node and its descendants
  49701. * @param name defines the name of the global animation that will be run on all nodes
  49702. * @param node defines the root node where the animation will take place
  49703. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49704. * @param targetProperty defines property to animate
  49705. * @param framePerSecond defines the number of frame per second to use
  49706. * @param totalFrame defines the number of frames in total
  49707. * @param from defines the initial value
  49708. * @param to defines the final value
  49709. * @param loopMode defines which loop mode you want to use (off by default)
  49710. * @param easingFunction defines the easing function to use (linear by default)
  49711. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49712. * @returns the list of animatables created for all nodes
  49713. * @example https://www.babylonjs-playground.com/#MH0VLI
  49714. */
  49715. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49716. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49717. if (!animation) {
  49718. return null;
  49719. }
  49720. var scene = node.getScene();
  49721. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49722. };
  49723. /**
  49724. * Creates a new animation, merges it with the existing animations and starts it
  49725. * @param name Name of the animation
  49726. * @param node Node which contains the scene that begins the animations
  49727. * @param targetProperty Specifies which property to animate
  49728. * @param framePerSecond The frames per second of the animation
  49729. * @param totalFrame The total number of frames
  49730. * @param from The frame at the beginning of the animation
  49731. * @param to The frame at the end of the animation
  49732. * @param loopMode Specifies the loop mode of the animation
  49733. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49734. * @param onAnimationEnd Callback to run once the animation is complete
  49735. * @returns Nullable animation
  49736. */
  49737. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49738. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49739. if (!animation) {
  49740. return null;
  49741. }
  49742. node.animations.push(animation);
  49743. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49744. };
  49745. /**
  49746. * Transition property of an host to the target Value
  49747. * @param property The property to transition
  49748. * @param targetValue The target Value of the property
  49749. * @param host The object where the property to animate belongs
  49750. * @param scene Scene used to run the animation
  49751. * @param frameRate Framerate (in frame/s) to use
  49752. * @param transition The transition type we want to use
  49753. * @param duration The duration of the animation, in milliseconds
  49754. * @param onAnimationEnd Callback trigger at the end of the animation
  49755. * @returns Nullable animation
  49756. */
  49757. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49758. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49759. if (duration <= 0) {
  49760. host[property] = targetValue;
  49761. if (onAnimationEnd) {
  49762. onAnimationEnd();
  49763. }
  49764. return null;
  49765. }
  49766. var endFrame = frameRate * (duration / 1000);
  49767. transition.setKeys([{
  49768. frame: 0,
  49769. value: host[property].clone ? host[property].clone() : host[property]
  49770. },
  49771. {
  49772. frame: endFrame,
  49773. value: targetValue
  49774. }]);
  49775. if (!host.animations) {
  49776. host.animations = [];
  49777. }
  49778. host.animations.push(transition);
  49779. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49780. animation.onAnimationEnd = onAnimationEnd;
  49781. return animation;
  49782. };
  49783. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49784. /**
  49785. * Return the array of runtime animations currently using this animation
  49786. */
  49787. get: function () {
  49788. return this._runtimeAnimations;
  49789. },
  49790. enumerable: true,
  49791. configurable: true
  49792. });
  49793. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49794. /**
  49795. * Specifies if any of the runtime animations are currently running
  49796. */
  49797. get: function () {
  49798. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49799. var runtimeAnimation = _a[_i];
  49800. if (!runtimeAnimation.isStopped) {
  49801. return true;
  49802. }
  49803. }
  49804. return false;
  49805. },
  49806. enumerable: true,
  49807. configurable: true
  49808. });
  49809. // Methods
  49810. /**
  49811. * Converts the animation to a string
  49812. * @param fullDetails support for multiple levels of logging within scene loading
  49813. * @returns String form of the animation
  49814. */
  49815. Animation.prototype.toString = function (fullDetails) {
  49816. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49817. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49818. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49819. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49820. if (fullDetails) {
  49821. ret += ", Ranges: {";
  49822. var first = true;
  49823. for (var name in this._ranges) {
  49824. if (first) {
  49825. ret += ", ";
  49826. first = false;
  49827. }
  49828. ret += name;
  49829. }
  49830. ret += "}";
  49831. }
  49832. return ret;
  49833. };
  49834. /**
  49835. * Add an event to this animation
  49836. * @param event Event to add
  49837. */
  49838. Animation.prototype.addEvent = function (event) {
  49839. this._events.push(event);
  49840. };
  49841. /**
  49842. * Remove all events found at the given frame
  49843. * @param frame The frame to remove events from
  49844. */
  49845. Animation.prototype.removeEvents = function (frame) {
  49846. for (var index = 0; index < this._events.length; index++) {
  49847. if (this._events[index].frame === frame) {
  49848. this._events.splice(index, 1);
  49849. index--;
  49850. }
  49851. }
  49852. };
  49853. /**
  49854. * Retrieves all the events from the animation
  49855. * @returns Events from the animation
  49856. */
  49857. Animation.prototype.getEvents = function () {
  49858. return this._events;
  49859. };
  49860. /**
  49861. * Creates an animation range
  49862. * @param name Name of the animation range
  49863. * @param from Starting frame of the animation range
  49864. * @param to Ending frame of the animation
  49865. */
  49866. Animation.prototype.createRange = function (name, from, to) {
  49867. // check name not already in use; could happen for bones after serialized
  49868. if (!this._ranges[name]) {
  49869. this._ranges[name] = new AnimationRange(name, from, to);
  49870. }
  49871. };
  49872. /**
  49873. * Deletes an animation range by name
  49874. * @param name Name of the animation range to delete
  49875. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49876. */
  49877. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49878. if (deleteFrames === void 0) { deleteFrames = true; }
  49879. var range = this._ranges[name];
  49880. if (!range) {
  49881. return;
  49882. }
  49883. if (deleteFrames) {
  49884. var from = range.from;
  49885. var to = range.to;
  49886. // this loop MUST go high to low for multiple splices to work
  49887. for (var key = this._keys.length - 1; key >= 0; key--) {
  49888. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49889. this._keys.splice(key, 1);
  49890. }
  49891. }
  49892. }
  49893. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49894. };
  49895. /**
  49896. * Gets the animation range by name, or null if not defined
  49897. * @param name Name of the animation range
  49898. * @returns Nullable animation range
  49899. */
  49900. Animation.prototype.getRange = function (name) {
  49901. return this._ranges[name];
  49902. };
  49903. /**
  49904. * Gets the key frames from the animation
  49905. * @returns The key frames of the animation
  49906. */
  49907. Animation.prototype.getKeys = function () {
  49908. return this._keys;
  49909. };
  49910. /**
  49911. * Gets the highest frame rate of the animation
  49912. * @returns Highest frame rate of the animation
  49913. */
  49914. Animation.prototype.getHighestFrame = function () {
  49915. var ret = 0;
  49916. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49917. if (ret < this._keys[key].frame) {
  49918. ret = this._keys[key].frame;
  49919. }
  49920. }
  49921. return ret;
  49922. };
  49923. /**
  49924. * Gets the easing function of the animation
  49925. * @returns Easing function of the animation
  49926. */
  49927. Animation.prototype.getEasingFunction = function () {
  49928. return this._easingFunction;
  49929. };
  49930. /**
  49931. * Sets the easing function of the animation
  49932. * @param easingFunction A custom mathematical formula for animation
  49933. */
  49934. Animation.prototype.setEasingFunction = function (easingFunction) {
  49935. this._easingFunction = easingFunction;
  49936. };
  49937. /**
  49938. * Interpolates a scalar linearly
  49939. * @param startValue Start value of the animation curve
  49940. * @param endValue End value of the animation curve
  49941. * @param gradient Scalar amount to interpolate
  49942. * @returns Interpolated scalar value
  49943. */
  49944. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49945. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49946. };
  49947. /**
  49948. * Interpolates a scalar cubically
  49949. * @param startValue Start value of the animation curve
  49950. * @param outTangent End tangent of the animation
  49951. * @param endValue End value of the animation curve
  49952. * @param inTangent Start tangent of the animation curve
  49953. * @param gradient Scalar amount to interpolate
  49954. * @returns Interpolated scalar value
  49955. */
  49956. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49957. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49958. };
  49959. /**
  49960. * Interpolates a quaternion using a spherical linear interpolation
  49961. * @param startValue Start value of the animation curve
  49962. * @param endValue End value of the animation curve
  49963. * @param gradient Scalar amount to interpolate
  49964. * @returns Interpolated quaternion value
  49965. */
  49966. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49967. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49968. };
  49969. /**
  49970. * Interpolates a quaternion cubically
  49971. * @param startValue Start value of the animation curve
  49972. * @param outTangent End tangent of the animation curve
  49973. * @param endValue End value of the animation curve
  49974. * @param inTangent Start tangent of the animation curve
  49975. * @param gradient Scalar amount to interpolate
  49976. * @returns Interpolated quaternion value
  49977. */
  49978. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49979. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49980. };
  49981. /**
  49982. * Interpolates a Vector3 linearl
  49983. * @param startValue Start value of the animation curve
  49984. * @param endValue End value of the animation curve
  49985. * @param gradient Scalar amount to interpolate
  49986. * @returns Interpolated scalar value
  49987. */
  49988. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49989. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49990. };
  49991. /**
  49992. * Interpolates a Vector3 cubically
  49993. * @param startValue Start value of the animation curve
  49994. * @param outTangent End tangent of the animation
  49995. * @param endValue End value of the animation curve
  49996. * @param inTangent Start tangent of the animation curve
  49997. * @param gradient Scalar amount to interpolate
  49998. * @returns InterpolatedVector3 value
  49999. */
  50000. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50001. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50002. };
  50003. /**
  50004. * Interpolates a Vector2 linearly
  50005. * @param startValue Start value of the animation curve
  50006. * @param endValue End value of the animation curve
  50007. * @param gradient Scalar amount to interpolate
  50008. * @returns Interpolated Vector2 value
  50009. */
  50010. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50011. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50012. };
  50013. /**
  50014. * Interpolates a Vector2 cubically
  50015. * @param startValue Start value of the animation curve
  50016. * @param outTangent End tangent of the animation
  50017. * @param endValue End value of the animation curve
  50018. * @param inTangent Start tangent of the animation curve
  50019. * @param gradient Scalar amount to interpolate
  50020. * @returns Interpolated Vector2 value
  50021. */
  50022. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50023. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50024. };
  50025. /**
  50026. * Interpolates a size linearly
  50027. * @param startValue Start value of the animation curve
  50028. * @param endValue End value of the animation curve
  50029. * @param gradient Scalar amount to interpolate
  50030. * @returns Interpolated Size value
  50031. */
  50032. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50033. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50034. };
  50035. /**
  50036. * Interpolates a Color3 linearly
  50037. * @param startValue Start value of the animation curve
  50038. * @param endValue End value of the animation curve
  50039. * @param gradient Scalar amount to interpolate
  50040. * @returns Interpolated Color3 value
  50041. */
  50042. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50043. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50044. };
  50045. /**
  50046. * @hidden Internal use only
  50047. */
  50048. Animation.prototype._getKeyValue = function (value) {
  50049. if (typeof value === "function") {
  50050. return value();
  50051. }
  50052. return value;
  50053. };
  50054. /**
  50055. * @hidden Internal use only
  50056. */
  50057. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50058. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50059. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50060. }
  50061. var keys = this.getKeys();
  50062. // Try to get a hash to find the right key
  50063. 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));
  50064. if (keys[startKeyIndex].frame >= currentFrame) {
  50065. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50066. startKeyIndex--;
  50067. }
  50068. }
  50069. for (var key = startKeyIndex; key < keys.length; key++) {
  50070. var endKey = keys[key + 1];
  50071. if (endKey.frame >= currentFrame) {
  50072. var startKey = keys[key];
  50073. var startValue = this._getKeyValue(startKey.value);
  50074. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50075. return startValue;
  50076. }
  50077. var endValue = this._getKeyValue(endKey.value);
  50078. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50079. var frameDelta = endKey.frame - startKey.frame;
  50080. // gradient : percent of currentFrame between the frame inf and the frame sup
  50081. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50082. // check for easingFunction and correction of gradient
  50083. var easingFunction = this.getEasingFunction();
  50084. if (easingFunction != null) {
  50085. gradient = easingFunction.ease(gradient);
  50086. }
  50087. switch (this.dataType) {
  50088. // Float
  50089. case Animation.ANIMATIONTYPE_FLOAT:
  50090. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50091. switch (loopMode) {
  50092. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50093. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50094. return floatValue;
  50095. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50096. return offsetValue * repeatCount + floatValue;
  50097. }
  50098. break;
  50099. // Quaternion
  50100. case Animation.ANIMATIONTYPE_QUATERNION:
  50101. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50102. switch (loopMode) {
  50103. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50104. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50105. return quatValue;
  50106. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50107. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50108. }
  50109. return quatValue;
  50110. // Vector3
  50111. case Animation.ANIMATIONTYPE_VECTOR3:
  50112. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50113. switch (loopMode) {
  50114. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50115. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50116. return vec3Value;
  50117. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50118. return vec3Value.add(offsetValue.scale(repeatCount));
  50119. }
  50120. // Vector2
  50121. case Animation.ANIMATIONTYPE_VECTOR2:
  50122. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50123. switch (loopMode) {
  50124. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50125. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50126. return vec2Value;
  50127. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50128. return vec2Value.add(offsetValue.scale(repeatCount));
  50129. }
  50130. // Size
  50131. case Animation.ANIMATIONTYPE_SIZE:
  50132. switch (loopMode) {
  50133. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50134. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50135. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50136. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50137. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50138. }
  50139. // Color3
  50140. case Animation.ANIMATIONTYPE_COLOR3:
  50141. switch (loopMode) {
  50142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50144. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50146. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50147. }
  50148. // Matrix
  50149. case Animation.ANIMATIONTYPE_MATRIX:
  50150. switch (loopMode) {
  50151. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50152. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50153. if (Animation.AllowMatricesInterpolation) {
  50154. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50155. }
  50156. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50157. return startValue;
  50158. }
  50159. default:
  50160. break;
  50161. }
  50162. break;
  50163. }
  50164. }
  50165. return this._getKeyValue(keys[keys.length - 1].value);
  50166. };
  50167. /**
  50168. * Defines the function to use to interpolate matrices
  50169. * @param startValue defines the start matrix
  50170. * @param endValue defines the end matrix
  50171. * @param gradient defines the gradient between both matrices
  50172. * @param result defines an optional target matrix where to store the interpolation
  50173. * @returns the interpolated matrix
  50174. */
  50175. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50176. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50177. if (result) {
  50178. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50179. return result;
  50180. }
  50181. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50182. }
  50183. if (result) {
  50184. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50185. return result;
  50186. }
  50187. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50188. };
  50189. /**
  50190. * Makes a copy of the animation
  50191. * @returns Cloned animation
  50192. */
  50193. Animation.prototype.clone = function () {
  50194. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50195. clone.enableBlending = this.enableBlending;
  50196. clone.blendingSpeed = this.blendingSpeed;
  50197. if (this._keys) {
  50198. clone.setKeys(this._keys);
  50199. }
  50200. if (this._ranges) {
  50201. clone._ranges = {};
  50202. for (var name in this._ranges) {
  50203. var range = this._ranges[name];
  50204. if (!range) {
  50205. continue;
  50206. }
  50207. clone._ranges[name] = range.clone();
  50208. }
  50209. }
  50210. return clone;
  50211. };
  50212. /**
  50213. * Sets the key frames of the animation
  50214. * @param values The animation key frames to set
  50215. */
  50216. Animation.prototype.setKeys = function (values) {
  50217. this._keys = values.slice(0);
  50218. };
  50219. /**
  50220. * Serializes the animation to an object
  50221. * @returns Serialized object
  50222. */
  50223. Animation.prototype.serialize = function () {
  50224. var serializationObject = {};
  50225. serializationObject.name = this.name;
  50226. serializationObject.property = this.targetProperty;
  50227. serializationObject.framePerSecond = this.framePerSecond;
  50228. serializationObject.dataType = this.dataType;
  50229. serializationObject.loopBehavior = this.loopMode;
  50230. serializationObject.enableBlending = this.enableBlending;
  50231. serializationObject.blendingSpeed = this.blendingSpeed;
  50232. var dataType = this.dataType;
  50233. serializationObject.keys = [];
  50234. var keys = this.getKeys();
  50235. for (var index = 0; index < keys.length; index++) {
  50236. var animationKey = keys[index];
  50237. var key = {};
  50238. key.frame = animationKey.frame;
  50239. switch (dataType) {
  50240. case Animation.ANIMATIONTYPE_FLOAT:
  50241. key.values = [animationKey.value];
  50242. break;
  50243. case Animation.ANIMATIONTYPE_QUATERNION:
  50244. case Animation.ANIMATIONTYPE_MATRIX:
  50245. case Animation.ANIMATIONTYPE_VECTOR3:
  50246. case Animation.ANIMATIONTYPE_COLOR3:
  50247. key.values = animationKey.value.asArray();
  50248. break;
  50249. }
  50250. serializationObject.keys.push(key);
  50251. }
  50252. serializationObject.ranges = [];
  50253. for (var name in this._ranges) {
  50254. var source = this._ranges[name];
  50255. if (!source) {
  50256. continue;
  50257. }
  50258. var range = {};
  50259. range.name = name;
  50260. range.from = source.from;
  50261. range.to = source.to;
  50262. serializationObject.ranges.push(range);
  50263. }
  50264. return serializationObject;
  50265. };
  50266. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50267. /**
  50268. * Get the float animation type
  50269. */
  50270. get: function () {
  50271. return Animation._ANIMATIONTYPE_FLOAT;
  50272. },
  50273. enumerable: true,
  50274. configurable: true
  50275. });
  50276. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50277. /**
  50278. * Get the Vector3 animation type
  50279. */
  50280. get: function () {
  50281. return Animation._ANIMATIONTYPE_VECTOR3;
  50282. },
  50283. enumerable: true,
  50284. configurable: true
  50285. });
  50286. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50287. /**
  50288. * Get the Vectpr2 animation type
  50289. */
  50290. get: function () {
  50291. return Animation._ANIMATIONTYPE_VECTOR2;
  50292. },
  50293. enumerable: true,
  50294. configurable: true
  50295. });
  50296. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50297. /**
  50298. * Get the Size animation type
  50299. */
  50300. get: function () {
  50301. return Animation._ANIMATIONTYPE_SIZE;
  50302. },
  50303. enumerable: true,
  50304. configurable: true
  50305. });
  50306. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50307. /**
  50308. * Get the Quaternion animation type
  50309. */
  50310. get: function () {
  50311. return Animation._ANIMATIONTYPE_QUATERNION;
  50312. },
  50313. enumerable: true,
  50314. configurable: true
  50315. });
  50316. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50317. /**
  50318. * Get the Matrix animation type
  50319. */
  50320. get: function () {
  50321. return Animation._ANIMATIONTYPE_MATRIX;
  50322. },
  50323. enumerable: true,
  50324. configurable: true
  50325. });
  50326. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50327. /**
  50328. * Get the Color3 animation type
  50329. */
  50330. get: function () {
  50331. return Animation._ANIMATIONTYPE_COLOR3;
  50332. },
  50333. enumerable: true,
  50334. configurable: true
  50335. });
  50336. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50337. /**
  50338. * Get the Relative Loop Mode
  50339. */
  50340. get: function () {
  50341. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50342. },
  50343. enumerable: true,
  50344. configurable: true
  50345. });
  50346. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50347. /**
  50348. * Get the Cycle Loop Mode
  50349. */
  50350. get: function () {
  50351. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50352. },
  50353. enumerable: true,
  50354. configurable: true
  50355. });
  50356. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50357. /**
  50358. * Get the Constant Loop Mode
  50359. */
  50360. get: function () {
  50361. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50362. },
  50363. enumerable: true,
  50364. configurable: true
  50365. });
  50366. /** @hidden */
  50367. Animation._UniversalLerp = function (left, right, amount) {
  50368. var constructor = left.constructor;
  50369. if (constructor.Lerp) { // Lerp supported
  50370. return constructor.Lerp(left, right, amount);
  50371. }
  50372. else if (constructor.Slerp) { // Slerp supported
  50373. return constructor.Slerp(left, right, amount);
  50374. }
  50375. else if (left.toFixed) { // Number
  50376. return left * (1.0 - amount) + amount * right;
  50377. }
  50378. else { // Blending not supported
  50379. return right;
  50380. }
  50381. };
  50382. /**
  50383. * Parses an animation object and creates an animation
  50384. * @param parsedAnimation Parsed animation object
  50385. * @returns Animation object
  50386. */
  50387. Animation.Parse = function (parsedAnimation) {
  50388. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50389. var dataType = parsedAnimation.dataType;
  50390. var keys = [];
  50391. var data;
  50392. var index;
  50393. if (parsedAnimation.enableBlending) {
  50394. animation.enableBlending = parsedAnimation.enableBlending;
  50395. }
  50396. if (parsedAnimation.blendingSpeed) {
  50397. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50398. }
  50399. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50400. var key = parsedAnimation.keys[index];
  50401. var inTangent;
  50402. var outTangent;
  50403. switch (dataType) {
  50404. case Animation.ANIMATIONTYPE_FLOAT:
  50405. data = key.values[0];
  50406. if (key.values.length >= 1) {
  50407. inTangent = key.values[1];
  50408. }
  50409. if (key.values.length >= 2) {
  50410. outTangent = key.values[2];
  50411. }
  50412. break;
  50413. case Animation.ANIMATIONTYPE_QUATERNION:
  50414. data = BABYLON.Quaternion.FromArray(key.values);
  50415. if (key.values.length >= 8) {
  50416. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50417. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50418. inTangent = _inTangent;
  50419. }
  50420. }
  50421. if (key.values.length >= 12) {
  50422. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50423. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50424. outTangent = _outTangent;
  50425. }
  50426. }
  50427. break;
  50428. case Animation.ANIMATIONTYPE_MATRIX:
  50429. data = BABYLON.Matrix.FromArray(key.values);
  50430. break;
  50431. case Animation.ANIMATIONTYPE_COLOR3:
  50432. data = BABYLON.Color3.FromArray(key.values);
  50433. break;
  50434. case Animation.ANIMATIONTYPE_VECTOR3:
  50435. default:
  50436. data = BABYLON.Vector3.FromArray(key.values);
  50437. break;
  50438. }
  50439. var keyData = {};
  50440. keyData.frame = key.frame;
  50441. keyData.value = data;
  50442. if (inTangent != undefined) {
  50443. keyData.inTangent = inTangent;
  50444. }
  50445. if (outTangent != undefined) {
  50446. keyData.outTangent = outTangent;
  50447. }
  50448. keys.push(keyData);
  50449. }
  50450. animation.setKeys(keys);
  50451. if (parsedAnimation.ranges) {
  50452. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50453. data = parsedAnimation.ranges[index];
  50454. animation.createRange(data.name, data.from, data.to);
  50455. }
  50456. }
  50457. return animation;
  50458. };
  50459. /**
  50460. * Appends the serialized animations from the source animations
  50461. * @param source Source containing the animations
  50462. * @param destination Target to store the animations
  50463. */
  50464. Animation.AppendSerializedAnimations = function (source, destination) {
  50465. if (source.animations) {
  50466. destination.animations = [];
  50467. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50468. var animation = source.animations[animationIndex];
  50469. destination.animations.push(animation.serialize());
  50470. }
  50471. }
  50472. };
  50473. /**
  50474. * Use matrix interpolation instead of using direct key value when animating matrices
  50475. */
  50476. Animation.AllowMatricesInterpolation = false;
  50477. /**
  50478. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50479. */
  50480. Animation.AllowMatrixDecomposeForInterpolation = true;
  50481. // Statics
  50482. /**
  50483. * Float animation type
  50484. */
  50485. Animation._ANIMATIONTYPE_FLOAT = 0;
  50486. /**
  50487. * Vector3 animation type
  50488. */
  50489. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50490. /**
  50491. * Quaternion animation type
  50492. */
  50493. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50494. /**
  50495. * Matrix animation type
  50496. */
  50497. Animation._ANIMATIONTYPE_MATRIX = 3;
  50498. /**
  50499. * Color3 animation type
  50500. */
  50501. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50502. /**
  50503. * Vector2 animation type
  50504. */
  50505. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50506. /**
  50507. * Size animation type
  50508. */
  50509. Animation._ANIMATIONTYPE_SIZE = 6;
  50510. /**
  50511. * Relative Loop Mode
  50512. */
  50513. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50514. /**
  50515. * Cycle Loop Mode
  50516. */
  50517. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50518. /**
  50519. * Constant Loop Mode
  50520. */
  50521. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50522. return Animation;
  50523. }());
  50524. BABYLON.Animation = Animation;
  50525. })(BABYLON || (BABYLON = {}));
  50526. //# sourceMappingURL=babylon.animation.js.map
  50527. var BABYLON;
  50528. (function (BABYLON) {
  50529. /**
  50530. * This class defines the direct association between an animation and a target
  50531. */
  50532. var TargetedAnimation = /** @class */ (function () {
  50533. function TargetedAnimation() {
  50534. }
  50535. return TargetedAnimation;
  50536. }());
  50537. BABYLON.TargetedAnimation = TargetedAnimation;
  50538. /**
  50539. * Use this class to create coordinated animations on multiple targets
  50540. */
  50541. var AnimationGroup = /** @class */ (function () {
  50542. function AnimationGroup(name, scene) {
  50543. if (scene === void 0) { scene = null; }
  50544. this.name = name;
  50545. this._targetedAnimations = new Array();
  50546. this._animatables = new Array();
  50547. this._from = Number.MAX_VALUE;
  50548. this._to = -Number.MAX_VALUE;
  50549. this._speedRatio = 1;
  50550. this.onAnimationEndObservable = new BABYLON.Observable();
  50551. /**
  50552. * This observable will notify when all animations have ended.
  50553. */
  50554. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50555. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50556. this._scene.animationGroups.push(this);
  50557. }
  50558. Object.defineProperty(AnimationGroup.prototype, "from", {
  50559. /**
  50560. * Gets the first frame
  50561. */
  50562. get: function () {
  50563. return this._from;
  50564. },
  50565. enumerable: true,
  50566. configurable: true
  50567. });
  50568. Object.defineProperty(AnimationGroup.prototype, "to", {
  50569. /**
  50570. * Gets the last frame
  50571. */
  50572. get: function () {
  50573. return this._to;
  50574. },
  50575. enumerable: true,
  50576. configurable: true
  50577. });
  50578. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50579. /**
  50580. * Define if the animations are started
  50581. */
  50582. get: function () {
  50583. return this._isStarted;
  50584. },
  50585. enumerable: true,
  50586. configurable: true
  50587. });
  50588. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50589. /**
  50590. * Gets or sets the speed ratio to use for all animations
  50591. */
  50592. get: function () {
  50593. return this._speedRatio;
  50594. },
  50595. /**
  50596. * Gets or sets the speed ratio to use for all animations
  50597. */
  50598. set: function (value) {
  50599. if (this._speedRatio === value) {
  50600. return;
  50601. }
  50602. this._speedRatio = value;
  50603. for (var index = 0; index < this._animatables.length; index++) {
  50604. var animatable = this._animatables[index];
  50605. animatable.speedRatio = this._speedRatio;
  50606. }
  50607. },
  50608. enumerable: true,
  50609. configurable: true
  50610. });
  50611. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50612. /**
  50613. * Gets the targeted animations for this animation group
  50614. */
  50615. get: function () {
  50616. return this._targetedAnimations;
  50617. },
  50618. enumerable: true,
  50619. configurable: true
  50620. });
  50621. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50622. /**
  50623. * returning the list of animatables controlled by this animation group.
  50624. */
  50625. get: function () {
  50626. return this._animatables;
  50627. },
  50628. enumerable: true,
  50629. configurable: true
  50630. });
  50631. /**
  50632. * Add an animation (with its target) in the group
  50633. * @param animation defines the animation we want to add
  50634. * @param target defines the target of the animation
  50635. * @returns the {BABYLON.TargetedAnimation} object
  50636. */
  50637. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50638. var targetedAnimation = {
  50639. animation: animation,
  50640. target: target
  50641. };
  50642. var keys = animation.getKeys();
  50643. if (this._from > keys[0].frame) {
  50644. this._from = keys[0].frame;
  50645. }
  50646. if (this._to < keys[keys.length - 1].frame) {
  50647. this._to = keys[keys.length - 1].frame;
  50648. }
  50649. this._targetedAnimations.push(targetedAnimation);
  50650. return targetedAnimation;
  50651. };
  50652. /**
  50653. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50654. * It can add constant keys at begin or end
  50655. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50656. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50657. */
  50658. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50659. if (beginFrame === void 0) { beginFrame = null; }
  50660. if (endFrame === void 0) { endFrame = null; }
  50661. if (beginFrame == null)
  50662. beginFrame = this._from;
  50663. if (endFrame == null)
  50664. endFrame = this._to;
  50665. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50666. var targetedAnimation = this._targetedAnimations[index];
  50667. var keys = targetedAnimation.animation.getKeys();
  50668. var startKey = keys[0];
  50669. var endKey = keys[keys.length - 1];
  50670. if (startKey.frame > beginFrame) {
  50671. var newKey = {
  50672. frame: beginFrame,
  50673. value: startKey.value,
  50674. inTangent: startKey.inTangent,
  50675. outTangent: startKey.outTangent,
  50676. interpolation: startKey.interpolation
  50677. };
  50678. keys.splice(0, 0, newKey);
  50679. }
  50680. if (endKey.frame < endFrame) {
  50681. var newKey = {
  50682. frame: endFrame,
  50683. value: endKey.value,
  50684. inTangent: endKey.outTangent,
  50685. outTangent: endKey.outTangent,
  50686. interpolation: endKey.interpolation
  50687. };
  50688. keys.push(newKey);
  50689. }
  50690. }
  50691. this._from = beginFrame;
  50692. this._to = endFrame;
  50693. return this;
  50694. };
  50695. /**
  50696. * Start all animations on given targets
  50697. * @param loop defines if animations must loop
  50698. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50699. * @param from defines the from key (optional)
  50700. * @param to defines the to key (optional)
  50701. * @returns the current animation group
  50702. */
  50703. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50704. var _this = this;
  50705. if (loop === void 0) { loop = false; }
  50706. if (speedRatio === void 0) { speedRatio = 1; }
  50707. if (this._isStarted || this._targetedAnimations.length === 0) {
  50708. return this;
  50709. }
  50710. var _loop_1 = function (targetedAnimation) {
  50711. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50712. animatable.onAnimationEnd = function () {
  50713. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50714. _this._checkAnimationGroupEnded(animatable);
  50715. };
  50716. this_1._animatables.push(animatable);
  50717. };
  50718. var this_1 = this;
  50719. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50720. var targetedAnimation = _a[_i];
  50721. _loop_1(targetedAnimation);
  50722. }
  50723. this._speedRatio = speedRatio;
  50724. this._isStarted = true;
  50725. return this;
  50726. };
  50727. /**
  50728. * Pause all animations
  50729. */
  50730. AnimationGroup.prototype.pause = function () {
  50731. if (!this._isStarted) {
  50732. return this;
  50733. }
  50734. for (var index = 0; index < this._animatables.length; index++) {
  50735. var animatable = this._animatables[index];
  50736. animatable.pause();
  50737. }
  50738. return this;
  50739. };
  50740. /**
  50741. * Play all animations to initial state
  50742. * This function will start() the animations if they were not started or will restart() them if they were paused
  50743. * @param loop defines if animations must loop
  50744. */
  50745. AnimationGroup.prototype.play = function (loop) {
  50746. // only if all animatables are ready and exist
  50747. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50748. if (loop !== undefined) {
  50749. for (var index = 0; index < this._animatables.length; index++) {
  50750. var animatable = this._animatables[index];
  50751. animatable.loopAnimation = loop;
  50752. }
  50753. }
  50754. this.restart();
  50755. }
  50756. else {
  50757. this.stop();
  50758. this.start(loop, this._speedRatio);
  50759. }
  50760. return this;
  50761. };
  50762. /**
  50763. * Reset all animations to initial state
  50764. */
  50765. AnimationGroup.prototype.reset = function () {
  50766. if (!this._isStarted) {
  50767. return this;
  50768. }
  50769. for (var index = 0; index < this._animatables.length; index++) {
  50770. var animatable = this._animatables[index];
  50771. animatable.reset();
  50772. }
  50773. return this;
  50774. };
  50775. /**
  50776. * Restart animations from key 0
  50777. */
  50778. AnimationGroup.prototype.restart = function () {
  50779. if (!this._isStarted) {
  50780. return this;
  50781. }
  50782. for (var index = 0; index < this._animatables.length; index++) {
  50783. var animatable = this._animatables[index];
  50784. animatable.restart();
  50785. }
  50786. return this;
  50787. };
  50788. /**
  50789. * Stop all animations
  50790. */
  50791. AnimationGroup.prototype.stop = function () {
  50792. if (!this._isStarted) {
  50793. return this;
  50794. }
  50795. var list = this._animatables.slice();
  50796. for (var index = 0; index < list.length; index++) {
  50797. list[index].stop();
  50798. }
  50799. this._isStarted = false;
  50800. return this;
  50801. };
  50802. /**
  50803. * Set animation weight for all animatables
  50804. * @param weight defines the weight to use
  50805. * @return the animationGroup
  50806. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50807. */
  50808. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50809. for (var index = 0; index < this._animatables.length; index++) {
  50810. var animatable = this._animatables[index];
  50811. animatable.weight = weight;
  50812. }
  50813. return this;
  50814. };
  50815. /**
  50816. * Synchronize and normalize all animatables with a source animatable
  50817. * @param root defines the root animatable to synchronize with
  50818. * @return the animationGroup
  50819. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50820. */
  50821. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50822. for (var index = 0; index < this._animatables.length; index++) {
  50823. var animatable = this._animatables[index];
  50824. animatable.syncWith(root);
  50825. }
  50826. return this;
  50827. };
  50828. /**
  50829. * Goes to a specific frame in this animation group
  50830. * @param frame the frame number to go to
  50831. * @return the animationGroup
  50832. */
  50833. AnimationGroup.prototype.goToFrame = function (frame) {
  50834. if (!this._isStarted) {
  50835. return this;
  50836. }
  50837. for (var index = 0; index < this._animatables.length; index++) {
  50838. var animatable = this._animatables[index];
  50839. animatable.goToFrame(frame);
  50840. }
  50841. return this;
  50842. };
  50843. /**
  50844. * Dispose all associated resources
  50845. */
  50846. AnimationGroup.prototype.dispose = function () {
  50847. this._targetedAnimations = [];
  50848. this._animatables = [];
  50849. var index = this._scene.animationGroups.indexOf(this);
  50850. if (index > -1) {
  50851. this._scene.animationGroups.splice(index, 1);
  50852. }
  50853. };
  50854. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50855. // animatable should be taken out of the array
  50856. var idx = this._animatables.indexOf(animatable);
  50857. if (idx > -1) {
  50858. this._animatables.splice(idx, 1);
  50859. }
  50860. // all animatables were removed? animation group ended!
  50861. if (this._animatables.length === 0) {
  50862. this._isStarted = false;
  50863. this.onAnimationGroupEndObservable.notifyObservers(this);
  50864. }
  50865. };
  50866. return AnimationGroup;
  50867. }());
  50868. BABYLON.AnimationGroup = AnimationGroup;
  50869. })(BABYLON || (BABYLON = {}));
  50870. //# sourceMappingURL=babylon.animationGroup.js.map
  50871. var BABYLON;
  50872. (function (BABYLON) {
  50873. /**
  50874. * Defines a runtime animation
  50875. */
  50876. var RuntimeAnimation = /** @class */ (function () {
  50877. /**
  50878. * Create a new RuntimeAnimation object
  50879. * @param target defines the target of the animation
  50880. * @param animation defines the source animation object
  50881. * @param scene defines the hosting scene
  50882. * @param host defines the initiating Animatable
  50883. */
  50884. function RuntimeAnimation(target, animation, scene, host) {
  50885. var _this = this;
  50886. this._events = new Array();
  50887. /**
  50888. * The current frame of the runtime animation
  50889. */
  50890. this._currentFrame = 0;
  50891. /**
  50892. * The original value of the runtime animation
  50893. */
  50894. this._originalValue = new Array();
  50895. /**
  50896. * The offsets cache of the runtime animation
  50897. */
  50898. this._offsetsCache = {};
  50899. /**
  50900. * The high limits cache of the runtime animation
  50901. */
  50902. this._highLimitsCache = {};
  50903. /**
  50904. * Specifies if the runtime animation has been stopped
  50905. */
  50906. this._stopped = false;
  50907. /**
  50908. * The blending factor of the runtime animation
  50909. */
  50910. this._blendingFactor = 0;
  50911. /**
  50912. * The target path of the runtime animation
  50913. */
  50914. this._targetPath = "";
  50915. /**
  50916. * The weight of the runtime animation
  50917. */
  50918. this._weight = 1.0;
  50919. /**
  50920. * The ratio offset of the runtime animation
  50921. */
  50922. this._ratioOffset = 0;
  50923. /**
  50924. * The previous delay of the runtime animation
  50925. */
  50926. this._previousDelay = 0;
  50927. /**
  50928. * The previous ratio of the runtime animation
  50929. */
  50930. this._previousRatio = 0;
  50931. this._animation = animation;
  50932. this._target = target;
  50933. this._scene = scene;
  50934. this._host = host;
  50935. animation._runtimeAnimations.push(this);
  50936. // Cloning events locally
  50937. var events = animation.getEvents();
  50938. if (events && events.length > 0) {
  50939. events.forEach(function (e) {
  50940. _this._events.push(e._clone());
  50941. });
  50942. }
  50943. }
  50944. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50945. /**
  50946. * Gets the current frame of the runtime animation
  50947. */
  50948. get: function () {
  50949. return this._currentFrame;
  50950. },
  50951. enumerable: true,
  50952. configurable: true
  50953. });
  50954. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50955. /**
  50956. * Gets the weight of the runtime animation
  50957. */
  50958. get: function () {
  50959. return this._weight;
  50960. },
  50961. enumerable: true,
  50962. configurable: true
  50963. });
  50964. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50965. /**
  50966. * Gets the current value of the runtime animation
  50967. */
  50968. get: function () {
  50969. return this._currentValue;
  50970. },
  50971. enumerable: true,
  50972. configurable: true
  50973. });
  50974. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50975. /**
  50976. * Gets the target path of the runtime animation
  50977. */
  50978. get: function () {
  50979. return this._targetPath;
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50985. /**
  50986. * Gets the actual target of the runtime animation
  50987. */
  50988. get: function () {
  50989. return this._activeTarget;
  50990. },
  50991. enumerable: true,
  50992. configurable: true
  50993. });
  50994. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50995. /**
  50996. * Gets the animation from the runtime animation
  50997. */
  50998. get: function () {
  50999. return this._animation;
  51000. },
  51001. enumerable: true,
  51002. configurable: true
  51003. });
  51004. /**
  51005. * Resets the runtime animation to the beginning
  51006. * @param restoreOriginal defines whether to restore the target property to the original value
  51007. */
  51008. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51009. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51010. if (restoreOriginal) {
  51011. if (this._target instanceof Array) {
  51012. var index = 0;
  51013. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51014. var target = _a[_i];
  51015. if (this._originalValue[index] !== undefined) {
  51016. this._setValue(target, this._originalValue[index], -1);
  51017. }
  51018. index++;
  51019. }
  51020. }
  51021. else {
  51022. if (this._originalValue[0] !== undefined) {
  51023. this._setValue(this._target, this._originalValue[0], -1);
  51024. }
  51025. }
  51026. }
  51027. this._offsetsCache = {};
  51028. this._highLimitsCache = {};
  51029. this._currentFrame = 0;
  51030. this._blendingFactor = 0;
  51031. this._originalValue = new Array();
  51032. // Events
  51033. for (var index = 0; index < this._events.length; index++) {
  51034. this._events[index].isDone = false;
  51035. }
  51036. };
  51037. /**
  51038. * Specifies if the runtime animation is stopped
  51039. * @returns Boolean specifying if the runtime animation is stopped
  51040. */
  51041. RuntimeAnimation.prototype.isStopped = function () {
  51042. return this._stopped;
  51043. };
  51044. /**
  51045. * Disposes of the runtime animation
  51046. */
  51047. RuntimeAnimation.prototype.dispose = function () {
  51048. var index = this._animation.runtimeAnimations.indexOf(this);
  51049. if (index > -1) {
  51050. this._animation.runtimeAnimations.splice(index, 1);
  51051. }
  51052. };
  51053. /**
  51054. * Interpolates the animation from the current frame
  51055. * @param currentFrame The frame to interpolate the animation to
  51056. * @param repeatCount The number of times that the animation should loop
  51057. * @param loopMode The type of looping mode to use
  51058. * @param offsetValue Animation offset value
  51059. * @param highLimitValue The high limit value
  51060. * @returns The interpolated value
  51061. */
  51062. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51063. this._currentFrame = currentFrame;
  51064. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51065. this._workValue = BABYLON.Matrix.Zero();
  51066. }
  51067. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51068. };
  51069. /**
  51070. * Apply the interpolated value to the target
  51071. * @param currentValue defines the value computed by the animation
  51072. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51073. */
  51074. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51075. if (weight === void 0) { weight = 1.0; }
  51076. if (this._target instanceof Array) {
  51077. var index = 0;
  51078. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51079. var target = _a[_i];
  51080. this._setValue(target, currentValue, weight, index);
  51081. index++;
  51082. }
  51083. }
  51084. else {
  51085. this._setValue(this._target, currentValue, weight);
  51086. }
  51087. };
  51088. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51089. if (targetIndex === void 0) { targetIndex = 0; }
  51090. // Set value
  51091. var path;
  51092. var destination;
  51093. var targetPropertyPath = this._animation.targetPropertyPath;
  51094. if (targetPropertyPath.length > 1) {
  51095. var property = target[targetPropertyPath[0]];
  51096. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51097. property = property[targetPropertyPath[index]];
  51098. }
  51099. path = targetPropertyPath[targetPropertyPath.length - 1];
  51100. destination = property;
  51101. }
  51102. else {
  51103. path = targetPropertyPath[0];
  51104. destination = target;
  51105. }
  51106. this._targetPath = path;
  51107. this._activeTarget = destination;
  51108. this._weight = weight;
  51109. if (this._originalValue[targetIndex] === undefined) {
  51110. var originalValue = void 0;
  51111. if (destination.getRestPose && path === "_matrix") { // For bones
  51112. originalValue = destination.getRestPose();
  51113. }
  51114. else {
  51115. originalValue = destination[path];
  51116. }
  51117. if (originalValue && originalValue.clone) {
  51118. this._originalValue[targetIndex] = originalValue.clone();
  51119. }
  51120. else {
  51121. this._originalValue[targetIndex] = originalValue;
  51122. }
  51123. }
  51124. // Blending
  51125. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51126. if (enableBlending && this._blendingFactor <= 1.0) {
  51127. if (!this._originalBlendValue) {
  51128. var originalValue = destination[path];
  51129. if (originalValue.clone) {
  51130. this._originalBlendValue = originalValue.clone();
  51131. }
  51132. else {
  51133. this._originalBlendValue = originalValue;
  51134. }
  51135. }
  51136. if (this._originalBlendValue.m) { // Matrix
  51137. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51138. if (this._currentValue) {
  51139. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51140. }
  51141. else {
  51142. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51143. }
  51144. }
  51145. else {
  51146. if (this._currentValue) {
  51147. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51148. }
  51149. else {
  51150. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51151. }
  51152. }
  51153. }
  51154. else {
  51155. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51156. }
  51157. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51158. this._blendingFactor += blendingSpeed;
  51159. }
  51160. else {
  51161. this._currentValue = currentValue;
  51162. }
  51163. if (weight !== -1.0) {
  51164. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51165. }
  51166. else {
  51167. destination[path] = this._currentValue;
  51168. }
  51169. if (target.markAsDirty) {
  51170. target.markAsDirty(this._animation.targetProperty);
  51171. }
  51172. };
  51173. /**
  51174. * Gets the loop pmode of the runtime animation
  51175. * @returns Loop Mode
  51176. */
  51177. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51178. if (this._target && this._target.animationPropertiesOverride) {
  51179. return this._target.animationPropertiesOverride.loopMode;
  51180. }
  51181. return this._animation.loopMode;
  51182. };
  51183. /**
  51184. * Move the current animation to a given frame
  51185. * @param frame defines the frame to move to
  51186. */
  51187. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51188. var keys = this._animation.getKeys();
  51189. if (frame < keys[0].frame) {
  51190. frame = keys[0].frame;
  51191. }
  51192. else if (frame > keys[keys.length - 1].frame) {
  51193. frame = keys[keys.length - 1].frame;
  51194. }
  51195. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51196. this.setValue(currentValue, -1);
  51197. };
  51198. /**
  51199. * @hidden Internal use only
  51200. */
  51201. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51202. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51203. this._ratioOffset = this._previousRatio - newRatio;
  51204. };
  51205. /**
  51206. * Execute the current animation
  51207. * @param delay defines the delay to add to the current frame
  51208. * @param from defines the lower bound of the animation range
  51209. * @param to defines the upper bound of the animation range
  51210. * @param loop defines if the current animation must loop
  51211. * @param speedRatio defines the current speed ratio
  51212. * @param weight defines the weight of the animation (default is -1 so no weight)
  51213. * @returns a boolean indicating if the animation has ended
  51214. */
  51215. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51216. if (weight === void 0) { weight = -1.0; }
  51217. var targetPropertyPath = this._animation.targetPropertyPath;
  51218. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51219. this._stopped = true;
  51220. return false;
  51221. }
  51222. var keys = this._animation.getKeys();
  51223. // Return immediately if there is only one key frame.
  51224. if (keys.length === 1) {
  51225. this.setValue(keys[0].value, weight);
  51226. return !loop;
  51227. }
  51228. var returnValue = true;
  51229. // Adding a start key at frame 0 if missing
  51230. if (keys[0].frame !== 0) {
  51231. var newKey = { frame: 0, value: keys[0].value };
  51232. keys.splice(0, 0, newKey);
  51233. }
  51234. // Check limits
  51235. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51236. from = keys[0].frame;
  51237. }
  51238. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51239. to = keys[keys.length - 1].frame;
  51240. }
  51241. //to and from cannot be the same key
  51242. if (from === to) {
  51243. if (from > keys[0].frame) {
  51244. from--;
  51245. }
  51246. else if (to < keys[keys.length - 1].frame) {
  51247. to++;
  51248. }
  51249. }
  51250. // Compute ratio
  51251. var range = to - from;
  51252. var offsetValue;
  51253. // ratio represents the frame delta between from and to
  51254. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51255. var highLimitValue = 0;
  51256. this._previousDelay = delay;
  51257. this._previousRatio = ratio;
  51258. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51259. returnValue = false;
  51260. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51261. }
  51262. else {
  51263. // Get max value if required
  51264. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51265. var keyOffset = to.toString() + from.toString();
  51266. if (!this._offsetsCache[keyOffset]) {
  51267. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51268. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51269. switch (this._animation.dataType) {
  51270. // Float
  51271. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51272. this._offsetsCache[keyOffset] = toValue - fromValue;
  51273. break;
  51274. // Quaternion
  51275. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51276. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51277. break;
  51278. // Vector3
  51279. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51280. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51281. // Vector2
  51282. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51283. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51284. // Size
  51285. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51286. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51287. // Color3
  51288. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51289. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51290. default:
  51291. break;
  51292. }
  51293. this._highLimitsCache[keyOffset] = toValue;
  51294. }
  51295. highLimitValue = this._highLimitsCache[keyOffset];
  51296. offsetValue = this._offsetsCache[keyOffset];
  51297. }
  51298. }
  51299. if (offsetValue === undefined) {
  51300. switch (this._animation.dataType) {
  51301. // Float
  51302. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51303. offsetValue = 0;
  51304. break;
  51305. // Quaternion
  51306. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51307. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51308. break;
  51309. // Vector3
  51310. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51311. offsetValue = BABYLON.Vector3.Zero();
  51312. break;
  51313. // Vector2
  51314. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51315. offsetValue = BABYLON.Vector2.Zero();
  51316. break;
  51317. // Size
  51318. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51319. offsetValue = BABYLON.Size.Zero();
  51320. break;
  51321. // Color3
  51322. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51323. offsetValue = BABYLON.Color3.Black();
  51324. }
  51325. }
  51326. // Compute value
  51327. var repeatCount = (ratio / range) >> 0;
  51328. var currentFrame = returnValue ? from + ratio % range : to;
  51329. // Need to normalize?
  51330. if (this._host && this._host.syncRoot) {
  51331. var syncRoot = this._host.syncRoot;
  51332. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51333. currentFrame = from + (to - from) * hostNormalizedFrame;
  51334. }
  51335. // Reset events if looping
  51336. var events = this._events;
  51337. if (range > 0 && this.currentFrame > currentFrame ||
  51338. range < 0 && this.currentFrame < currentFrame) {
  51339. // Need to reset animation events
  51340. for (var index = 0; index < events.length; index++) {
  51341. if (!events[index].onlyOnce) {
  51342. // reset event, the animation is looping
  51343. events[index].isDone = false;
  51344. }
  51345. }
  51346. }
  51347. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51348. // Set value
  51349. this.setValue(currentValue, weight);
  51350. // Check events
  51351. for (var index = 0; index < events.length; index++) {
  51352. // Make sure current frame has passed event frame and that event frame is within the current range
  51353. // Also, handle both forward and reverse animations
  51354. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51355. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51356. var event = events[index];
  51357. if (!event.isDone) {
  51358. // If event should be done only once, remove it.
  51359. if (event.onlyOnce) {
  51360. events.splice(index, 1);
  51361. index--;
  51362. }
  51363. event.isDone = true;
  51364. event.action();
  51365. } // Don't do anything if the event has already be done.
  51366. }
  51367. }
  51368. if (!returnValue) {
  51369. this._stopped = true;
  51370. }
  51371. return returnValue;
  51372. };
  51373. return RuntimeAnimation;
  51374. }());
  51375. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51376. })(BABYLON || (BABYLON = {}));
  51377. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51378. var BABYLON;
  51379. (function (BABYLON) {
  51380. var Animatable = /** @class */ (function () {
  51381. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51382. if (fromFrame === void 0) { fromFrame = 0; }
  51383. if (toFrame === void 0) { toFrame = 100; }
  51384. if (loopAnimation === void 0) { loopAnimation = false; }
  51385. if (speedRatio === void 0) { speedRatio = 1.0; }
  51386. this.target = target;
  51387. this.fromFrame = fromFrame;
  51388. this.toFrame = toFrame;
  51389. this.loopAnimation = loopAnimation;
  51390. this.onAnimationEnd = onAnimationEnd;
  51391. this._localDelayOffset = null;
  51392. this._pausedDelay = null;
  51393. this._runtimeAnimations = new Array();
  51394. this._paused = false;
  51395. this._speedRatio = 1;
  51396. this._weight = -1.0;
  51397. this.animationStarted = false;
  51398. /**
  51399. * Observer raised when the animation ends
  51400. */
  51401. this.onAnimationEndObservable = new BABYLON.Observable();
  51402. this._scene = scene;
  51403. if (animations) {
  51404. this.appendAnimations(target, animations);
  51405. }
  51406. this._speedRatio = speedRatio;
  51407. scene._activeAnimatables.push(this);
  51408. }
  51409. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51410. /**
  51411. * Gets the root Animatable used to synchronize and normalize animations
  51412. */
  51413. get: function () {
  51414. return this._syncRoot;
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51420. /**
  51421. * Gets the current frame of the first RuntimeAnimation
  51422. * Used to synchronize Animatables
  51423. */
  51424. get: function () {
  51425. if (this._runtimeAnimations.length === 0) {
  51426. return 0;
  51427. }
  51428. return this._runtimeAnimations[0].currentFrame;
  51429. },
  51430. enumerable: true,
  51431. configurable: true
  51432. });
  51433. Object.defineProperty(Animatable.prototype, "weight", {
  51434. /**
  51435. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51436. */
  51437. get: function () {
  51438. return this._weight;
  51439. },
  51440. set: function (value) {
  51441. if (value === -1) { // -1 is ok and means no weight
  51442. this._weight = -1;
  51443. return;
  51444. }
  51445. // Else weight must be in [0, 1] range
  51446. this._weight = Math.min(Math.max(value, 0), 1.0);
  51447. },
  51448. enumerable: true,
  51449. configurable: true
  51450. });
  51451. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51452. /**
  51453. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51454. */
  51455. get: function () {
  51456. return this._speedRatio;
  51457. },
  51458. set: function (value) {
  51459. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51460. var animation = this._runtimeAnimations[index];
  51461. animation._prepareForSpeedRatioChange(value);
  51462. }
  51463. this._speedRatio = value;
  51464. },
  51465. enumerable: true,
  51466. configurable: true
  51467. });
  51468. // Methods
  51469. /**
  51470. * Synchronize and normalize current Animatable with a source Animatable
  51471. * This is useful when using animation weights and when animations are not of the same length
  51472. * @param root defines the root Animatable to synchronize with
  51473. * @returns the current Animatable
  51474. */
  51475. Animatable.prototype.syncWith = function (root) {
  51476. this._syncRoot = root;
  51477. if (root) {
  51478. // Make sure this animatable will animate after the root
  51479. var index = this._scene._activeAnimatables.indexOf(this);
  51480. if (index > -1) {
  51481. this._scene._activeAnimatables.splice(index, 1);
  51482. this._scene._activeAnimatables.push(this);
  51483. }
  51484. }
  51485. return this;
  51486. };
  51487. Animatable.prototype.getAnimations = function () {
  51488. return this._runtimeAnimations;
  51489. };
  51490. Animatable.prototype.appendAnimations = function (target, animations) {
  51491. for (var index = 0; index < animations.length; index++) {
  51492. var animation = animations[index];
  51493. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51494. }
  51495. };
  51496. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51497. var runtimeAnimations = this._runtimeAnimations;
  51498. for (var index = 0; index < runtimeAnimations.length; index++) {
  51499. if (runtimeAnimations[index].animation.targetProperty === property) {
  51500. return runtimeAnimations[index].animation;
  51501. }
  51502. }
  51503. return null;
  51504. };
  51505. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51506. var runtimeAnimations = this._runtimeAnimations;
  51507. for (var index = 0; index < runtimeAnimations.length; index++) {
  51508. if (runtimeAnimations[index].animation.targetProperty === property) {
  51509. return runtimeAnimations[index];
  51510. }
  51511. }
  51512. return null;
  51513. };
  51514. Animatable.prototype.reset = function () {
  51515. var runtimeAnimations = this._runtimeAnimations;
  51516. for (var index = 0; index < runtimeAnimations.length; index++) {
  51517. runtimeAnimations[index].reset(true);
  51518. }
  51519. this._localDelayOffset = null;
  51520. this._pausedDelay = null;
  51521. };
  51522. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51523. var runtimeAnimations = this._runtimeAnimations;
  51524. for (var index = 0; index < runtimeAnimations.length; index++) {
  51525. runtimeAnimations[index].animation.enableBlending = true;
  51526. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51527. }
  51528. };
  51529. Animatable.prototype.disableBlending = function () {
  51530. var runtimeAnimations = this._runtimeAnimations;
  51531. for (var index = 0; index < runtimeAnimations.length; index++) {
  51532. runtimeAnimations[index].animation.enableBlending = false;
  51533. }
  51534. };
  51535. Animatable.prototype.goToFrame = function (frame) {
  51536. var runtimeAnimations = this._runtimeAnimations;
  51537. if (runtimeAnimations[0]) {
  51538. var fps = runtimeAnimations[0].animation.framePerSecond;
  51539. var currentFrame = runtimeAnimations[0].currentFrame;
  51540. var adjustTime = frame - currentFrame;
  51541. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51542. if (this._localDelayOffset === null) {
  51543. this._localDelayOffset = 0;
  51544. }
  51545. this._localDelayOffset -= delay;
  51546. }
  51547. for (var index = 0; index < runtimeAnimations.length; index++) {
  51548. runtimeAnimations[index].goToFrame(frame);
  51549. }
  51550. };
  51551. Animatable.prototype.pause = function () {
  51552. if (this._paused) {
  51553. return;
  51554. }
  51555. this._paused = true;
  51556. };
  51557. Animatable.prototype.restart = function () {
  51558. this._paused = false;
  51559. };
  51560. Animatable.prototype._raiseOnAnimationEnd = function () {
  51561. if (this.onAnimationEnd) {
  51562. this.onAnimationEnd();
  51563. }
  51564. this.onAnimationEndObservable.notifyObservers(this);
  51565. };
  51566. Animatable.prototype.stop = function (animationName) {
  51567. if (animationName) {
  51568. var idx = this._scene._activeAnimatables.indexOf(this);
  51569. if (idx > -1) {
  51570. var runtimeAnimations = this._runtimeAnimations;
  51571. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51572. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51573. continue;
  51574. }
  51575. runtimeAnimations[index].dispose();
  51576. runtimeAnimations.splice(index, 1);
  51577. }
  51578. if (runtimeAnimations.length == 0) {
  51579. this._scene._activeAnimatables.splice(idx, 1);
  51580. this._raiseOnAnimationEnd();
  51581. }
  51582. }
  51583. }
  51584. else {
  51585. var index = this._scene._activeAnimatables.indexOf(this);
  51586. if (index > -1) {
  51587. this._scene._activeAnimatables.splice(index, 1);
  51588. var runtimeAnimations = this._runtimeAnimations;
  51589. for (var index = 0; index < runtimeAnimations.length; index++) {
  51590. runtimeAnimations[index].dispose();
  51591. }
  51592. this._raiseOnAnimationEnd();
  51593. }
  51594. }
  51595. };
  51596. /**
  51597. * Wait asynchronously for the animation to end
  51598. * @returns a promise which will be fullfilled when the animation ends
  51599. */
  51600. Animatable.prototype.waitAsync = function () {
  51601. var _this = this;
  51602. return new Promise(function (resolve, reject) {
  51603. _this.onAnimationEndObservable.add(function () {
  51604. resolve(_this);
  51605. }, undefined, undefined, _this, true);
  51606. });
  51607. };
  51608. /** @hidden */
  51609. Animatable.prototype._animate = function (delay) {
  51610. if (this._paused) {
  51611. this.animationStarted = false;
  51612. if (this._pausedDelay === null) {
  51613. this._pausedDelay = delay;
  51614. }
  51615. return true;
  51616. }
  51617. if (this._localDelayOffset === null) {
  51618. this._localDelayOffset = delay;
  51619. this._pausedDelay = null;
  51620. }
  51621. else if (this._pausedDelay !== null) {
  51622. this._localDelayOffset += delay - this._pausedDelay;
  51623. this._pausedDelay = null;
  51624. }
  51625. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51626. return true;
  51627. }
  51628. // Animating
  51629. var running = false;
  51630. var runtimeAnimations = this._runtimeAnimations;
  51631. var index;
  51632. for (index = 0; index < runtimeAnimations.length; index++) {
  51633. var animation = runtimeAnimations[index];
  51634. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51635. running = running || isRunning;
  51636. }
  51637. this.animationStarted = running;
  51638. if (!running) {
  51639. // Remove from active animatables
  51640. index = this._scene._activeAnimatables.indexOf(this);
  51641. this._scene._activeAnimatables.splice(index, 1);
  51642. // Dispose all runtime animations
  51643. for (index = 0; index < runtimeAnimations.length; index++) {
  51644. runtimeAnimations[index].dispose();
  51645. }
  51646. this._raiseOnAnimationEnd();
  51647. this.onAnimationEnd = null;
  51648. this.onAnimationEndObservable.clear();
  51649. }
  51650. return running;
  51651. };
  51652. return Animatable;
  51653. }());
  51654. BABYLON.Animatable = Animatable;
  51655. })(BABYLON || (BABYLON = {}));
  51656. //# sourceMappingURL=babylon.animatable.js.map
  51657. var BABYLON;
  51658. (function (BABYLON) {
  51659. var EasingFunction = /** @class */ (function () {
  51660. function EasingFunction() {
  51661. // Properties
  51662. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51663. }
  51664. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51665. get: function () {
  51666. return EasingFunction._EASINGMODE_EASEIN;
  51667. },
  51668. enumerable: true,
  51669. configurable: true
  51670. });
  51671. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51672. get: function () {
  51673. return EasingFunction._EASINGMODE_EASEOUT;
  51674. },
  51675. enumerable: true,
  51676. configurable: true
  51677. });
  51678. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51679. get: function () {
  51680. return EasingFunction._EASINGMODE_EASEINOUT;
  51681. },
  51682. enumerable: true,
  51683. configurable: true
  51684. });
  51685. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51686. var n = Math.min(Math.max(easingMode, 0), 2);
  51687. this._easingMode = n;
  51688. };
  51689. EasingFunction.prototype.getEasingMode = function () {
  51690. return this._easingMode;
  51691. };
  51692. EasingFunction.prototype.easeInCore = function (gradient) {
  51693. throw new Error('You must implement this method');
  51694. };
  51695. EasingFunction.prototype.ease = function (gradient) {
  51696. switch (this._easingMode) {
  51697. case EasingFunction.EASINGMODE_EASEIN:
  51698. return this.easeInCore(gradient);
  51699. case EasingFunction.EASINGMODE_EASEOUT:
  51700. return (1 - this.easeInCore(1 - gradient));
  51701. }
  51702. if (gradient >= 0.5) {
  51703. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51704. }
  51705. return (this.easeInCore(gradient * 2) * 0.5);
  51706. };
  51707. //Statics
  51708. EasingFunction._EASINGMODE_EASEIN = 0;
  51709. EasingFunction._EASINGMODE_EASEOUT = 1;
  51710. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51711. return EasingFunction;
  51712. }());
  51713. BABYLON.EasingFunction = EasingFunction;
  51714. var CircleEase = /** @class */ (function (_super) {
  51715. __extends(CircleEase, _super);
  51716. function CircleEase() {
  51717. return _super !== null && _super.apply(this, arguments) || this;
  51718. }
  51719. CircleEase.prototype.easeInCore = function (gradient) {
  51720. gradient = Math.max(0, Math.min(1, gradient));
  51721. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51722. };
  51723. return CircleEase;
  51724. }(EasingFunction));
  51725. BABYLON.CircleEase = CircleEase;
  51726. var BackEase = /** @class */ (function (_super) {
  51727. __extends(BackEase, _super);
  51728. function BackEase(amplitude) {
  51729. if (amplitude === void 0) { amplitude = 1; }
  51730. var _this = _super.call(this) || this;
  51731. _this.amplitude = amplitude;
  51732. return _this;
  51733. }
  51734. BackEase.prototype.easeInCore = function (gradient) {
  51735. var num = Math.max(0, this.amplitude);
  51736. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51737. };
  51738. return BackEase;
  51739. }(EasingFunction));
  51740. BABYLON.BackEase = BackEase;
  51741. var BounceEase = /** @class */ (function (_super) {
  51742. __extends(BounceEase, _super);
  51743. function BounceEase(bounces, bounciness) {
  51744. if (bounces === void 0) { bounces = 3; }
  51745. if (bounciness === void 0) { bounciness = 2; }
  51746. var _this = _super.call(this) || this;
  51747. _this.bounces = bounces;
  51748. _this.bounciness = bounciness;
  51749. return _this;
  51750. }
  51751. BounceEase.prototype.easeInCore = function (gradient) {
  51752. var y = Math.max(0.0, this.bounces);
  51753. var bounciness = this.bounciness;
  51754. if (bounciness <= 1.0) {
  51755. bounciness = 1.001;
  51756. }
  51757. var num9 = Math.pow(bounciness, y);
  51758. var num5 = 1.0 - bounciness;
  51759. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51760. var num15 = gradient * num4;
  51761. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51762. var num3 = Math.floor(num65);
  51763. var num13 = num3 + 1.0;
  51764. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51765. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51766. var num7 = (num8 + num12) * 0.5;
  51767. var num6 = gradient - num7;
  51768. var num2 = num7 - num8;
  51769. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51770. };
  51771. return BounceEase;
  51772. }(EasingFunction));
  51773. BABYLON.BounceEase = BounceEase;
  51774. var CubicEase = /** @class */ (function (_super) {
  51775. __extends(CubicEase, _super);
  51776. function CubicEase() {
  51777. return _super !== null && _super.apply(this, arguments) || this;
  51778. }
  51779. CubicEase.prototype.easeInCore = function (gradient) {
  51780. return (gradient * gradient * gradient);
  51781. };
  51782. return CubicEase;
  51783. }(EasingFunction));
  51784. BABYLON.CubicEase = CubicEase;
  51785. var ElasticEase = /** @class */ (function (_super) {
  51786. __extends(ElasticEase, _super);
  51787. function ElasticEase(oscillations, springiness) {
  51788. if (oscillations === void 0) { oscillations = 3; }
  51789. if (springiness === void 0) { springiness = 3; }
  51790. var _this = _super.call(this) || this;
  51791. _this.oscillations = oscillations;
  51792. _this.springiness = springiness;
  51793. return _this;
  51794. }
  51795. ElasticEase.prototype.easeInCore = function (gradient) {
  51796. var num2;
  51797. var num3 = Math.max(0.0, this.oscillations);
  51798. var num = Math.max(0.0, this.springiness);
  51799. if (num == 0) {
  51800. num2 = gradient;
  51801. }
  51802. else {
  51803. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51804. }
  51805. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51806. };
  51807. return ElasticEase;
  51808. }(EasingFunction));
  51809. BABYLON.ElasticEase = ElasticEase;
  51810. var ExponentialEase = /** @class */ (function (_super) {
  51811. __extends(ExponentialEase, _super);
  51812. function ExponentialEase(exponent) {
  51813. if (exponent === void 0) { exponent = 2; }
  51814. var _this = _super.call(this) || this;
  51815. _this.exponent = exponent;
  51816. return _this;
  51817. }
  51818. ExponentialEase.prototype.easeInCore = function (gradient) {
  51819. if (this.exponent <= 0) {
  51820. return gradient;
  51821. }
  51822. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51823. };
  51824. return ExponentialEase;
  51825. }(EasingFunction));
  51826. BABYLON.ExponentialEase = ExponentialEase;
  51827. var PowerEase = /** @class */ (function (_super) {
  51828. __extends(PowerEase, _super);
  51829. function PowerEase(power) {
  51830. if (power === void 0) { power = 2; }
  51831. var _this = _super.call(this) || this;
  51832. _this.power = power;
  51833. return _this;
  51834. }
  51835. PowerEase.prototype.easeInCore = function (gradient) {
  51836. var y = Math.max(0.0, this.power);
  51837. return Math.pow(gradient, y);
  51838. };
  51839. return PowerEase;
  51840. }(EasingFunction));
  51841. BABYLON.PowerEase = PowerEase;
  51842. var QuadraticEase = /** @class */ (function (_super) {
  51843. __extends(QuadraticEase, _super);
  51844. function QuadraticEase() {
  51845. return _super !== null && _super.apply(this, arguments) || this;
  51846. }
  51847. QuadraticEase.prototype.easeInCore = function (gradient) {
  51848. return (gradient * gradient);
  51849. };
  51850. return QuadraticEase;
  51851. }(EasingFunction));
  51852. BABYLON.QuadraticEase = QuadraticEase;
  51853. var QuarticEase = /** @class */ (function (_super) {
  51854. __extends(QuarticEase, _super);
  51855. function QuarticEase() {
  51856. return _super !== null && _super.apply(this, arguments) || this;
  51857. }
  51858. QuarticEase.prototype.easeInCore = function (gradient) {
  51859. return (gradient * gradient * gradient * gradient);
  51860. };
  51861. return QuarticEase;
  51862. }(EasingFunction));
  51863. BABYLON.QuarticEase = QuarticEase;
  51864. var QuinticEase = /** @class */ (function (_super) {
  51865. __extends(QuinticEase, _super);
  51866. function QuinticEase() {
  51867. return _super !== null && _super.apply(this, arguments) || this;
  51868. }
  51869. QuinticEase.prototype.easeInCore = function (gradient) {
  51870. return (gradient * gradient * gradient * gradient * gradient);
  51871. };
  51872. return QuinticEase;
  51873. }(EasingFunction));
  51874. BABYLON.QuinticEase = QuinticEase;
  51875. var SineEase = /** @class */ (function (_super) {
  51876. __extends(SineEase, _super);
  51877. function SineEase() {
  51878. return _super !== null && _super.apply(this, arguments) || this;
  51879. }
  51880. SineEase.prototype.easeInCore = function (gradient) {
  51881. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51882. };
  51883. return SineEase;
  51884. }(EasingFunction));
  51885. BABYLON.SineEase = SineEase;
  51886. var BezierCurveEase = /** @class */ (function (_super) {
  51887. __extends(BezierCurveEase, _super);
  51888. function BezierCurveEase(x1, y1, x2, y2) {
  51889. if (x1 === void 0) { x1 = 0; }
  51890. if (y1 === void 0) { y1 = 0; }
  51891. if (x2 === void 0) { x2 = 1; }
  51892. if (y2 === void 0) { y2 = 1; }
  51893. var _this = _super.call(this) || this;
  51894. _this.x1 = x1;
  51895. _this.y1 = y1;
  51896. _this.x2 = x2;
  51897. _this.y2 = y2;
  51898. return _this;
  51899. }
  51900. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51901. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51902. };
  51903. return BezierCurveEase;
  51904. }(EasingFunction));
  51905. BABYLON.BezierCurveEase = BezierCurveEase;
  51906. })(BABYLON || (BABYLON = {}));
  51907. //# sourceMappingURL=babylon.easing.js.map
  51908. var BABYLON;
  51909. (function (BABYLON) {
  51910. /**
  51911. * A Condition applied to an Action
  51912. */
  51913. var Condition = /** @class */ (function () {
  51914. /**
  51915. * Creates a new Condition
  51916. * @param actionManager the manager of the action the condition is applied to
  51917. */
  51918. function Condition(actionManager) {
  51919. this._actionManager = actionManager;
  51920. }
  51921. /**
  51922. * Check if the current condition is valid
  51923. * @returns a boolean
  51924. */
  51925. Condition.prototype.isValid = function () {
  51926. return true;
  51927. };
  51928. /**
  51929. * Internal only
  51930. * @hidden
  51931. */
  51932. Condition.prototype._getProperty = function (propertyPath) {
  51933. return this._actionManager._getProperty(propertyPath);
  51934. };
  51935. /**
  51936. * Internal only
  51937. * @hidden
  51938. */
  51939. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51940. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51941. };
  51942. /**
  51943. * Serialize placeholder for child classes
  51944. * @returns the serialized object
  51945. */
  51946. Condition.prototype.serialize = function () {
  51947. };
  51948. /**
  51949. * Internal only
  51950. * @hidden
  51951. */
  51952. Condition.prototype._serialize = function (serializedCondition) {
  51953. return {
  51954. type: 2,
  51955. children: [],
  51956. name: serializedCondition.name,
  51957. properties: serializedCondition.properties
  51958. };
  51959. };
  51960. return Condition;
  51961. }());
  51962. BABYLON.Condition = Condition;
  51963. /**
  51964. * Defines specific conditional operators as extensions of Condition
  51965. */
  51966. var ValueCondition = /** @class */ (function (_super) {
  51967. __extends(ValueCondition, _super);
  51968. /**
  51969. * Creates a new ValueCondition
  51970. * @param actionManager manager for the action the condition applies to
  51971. * @param target for the action
  51972. * @param propertyPath path to specify the property of the target the conditional operator uses
  51973. * @param value the value compared by the conditional operator against the current value of the property
  51974. * @param operator the conditional operator, default ValueCondition.IsEqual
  51975. */
  51976. function ValueCondition(actionManager, target,
  51977. /** path to specify the property of the target the conditional operator uses */
  51978. propertyPath,
  51979. /** the value compared by the conditional operator against the current value of the property */
  51980. value,
  51981. /** the conditional operator, default ValueCondition.IsEqual */
  51982. operator) {
  51983. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51984. var _this = _super.call(this, actionManager) || this;
  51985. _this.propertyPath = propertyPath;
  51986. _this.value = value;
  51987. _this.operator = operator;
  51988. _this._target = target;
  51989. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51990. _this._property = _this._getProperty(_this.propertyPath);
  51991. return _this;
  51992. }
  51993. Object.defineProperty(ValueCondition, "IsEqual", {
  51994. /**
  51995. * returns the number for IsEqual
  51996. */
  51997. get: function () {
  51998. return ValueCondition._IsEqual;
  51999. },
  52000. enumerable: true,
  52001. configurable: true
  52002. });
  52003. Object.defineProperty(ValueCondition, "IsDifferent", {
  52004. /**
  52005. * Returns the number for IsDifferent
  52006. */
  52007. get: function () {
  52008. return ValueCondition._IsDifferent;
  52009. },
  52010. enumerable: true,
  52011. configurable: true
  52012. });
  52013. Object.defineProperty(ValueCondition, "IsGreater", {
  52014. /**
  52015. * Returns the number for IsGreater
  52016. */
  52017. get: function () {
  52018. return ValueCondition._IsGreater;
  52019. },
  52020. enumerable: true,
  52021. configurable: true
  52022. });
  52023. Object.defineProperty(ValueCondition, "IsLesser", {
  52024. /**
  52025. * Returns the number for IsLesser
  52026. */
  52027. get: function () {
  52028. return ValueCondition._IsLesser;
  52029. },
  52030. enumerable: true,
  52031. configurable: true
  52032. });
  52033. /**
  52034. * Compares the given value with the property value for the specified conditional operator
  52035. * @returns the result of the comparison
  52036. */
  52037. ValueCondition.prototype.isValid = function () {
  52038. switch (this.operator) {
  52039. case ValueCondition.IsGreater:
  52040. return this._effectiveTarget[this._property] > this.value;
  52041. case ValueCondition.IsLesser:
  52042. return this._effectiveTarget[this._property] < this.value;
  52043. case ValueCondition.IsEqual:
  52044. case ValueCondition.IsDifferent:
  52045. var check;
  52046. if (this.value.equals) {
  52047. check = this.value.equals(this._effectiveTarget[this._property]);
  52048. }
  52049. else {
  52050. check = this.value === this._effectiveTarget[this._property];
  52051. }
  52052. return this.operator === ValueCondition.IsEqual ? check : !check;
  52053. }
  52054. return false;
  52055. };
  52056. /**
  52057. * Serialize the ValueCondition into a JSON compatible object
  52058. * @returns serialization object
  52059. */
  52060. ValueCondition.prototype.serialize = function () {
  52061. return this._serialize({
  52062. name: "ValueCondition",
  52063. properties: [
  52064. BABYLON.Action._GetTargetProperty(this._target),
  52065. { name: "propertyPath", value: this.propertyPath },
  52066. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52067. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52068. ]
  52069. });
  52070. };
  52071. /**
  52072. * Gets the name of the conditional operator for the ValueCondition
  52073. * @param operator the conditional operator
  52074. * @returns the name
  52075. */
  52076. ValueCondition.GetOperatorName = function (operator) {
  52077. switch (operator) {
  52078. case ValueCondition._IsEqual: return "IsEqual";
  52079. case ValueCondition._IsDifferent: return "IsDifferent";
  52080. case ValueCondition._IsGreater: return "IsGreater";
  52081. case ValueCondition._IsLesser: return "IsLesser";
  52082. default: return "";
  52083. }
  52084. };
  52085. /**
  52086. * Internal only
  52087. * @hidden
  52088. */
  52089. ValueCondition._IsEqual = 0;
  52090. /**
  52091. * Internal only
  52092. * @hidden
  52093. */
  52094. ValueCondition._IsDifferent = 1;
  52095. /**
  52096. * Internal only
  52097. * @hidden
  52098. */
  52099. ValueCondition._IsGreater = 2;
  52100. /**
  52101. * Internal only
  52102. * @hidden
  52103. */
  52104. ValueCondition._IsLesser = 3;
  52105. return ValueCondition;
  52106. }(Condition));
  52107. BABYLON.ValueCondition = ValueCondition;
  52108. /**
  52109. * Defines a predicate condition as an extension of Condition
  52110. */
  52111. var PredicateCondition = /** @class */ (function (_super) {
  52112. __extends(PredicateCondition, _super);
  52113. /**
  52114. * Creates a new PredicateCondition
  52115. * @param actionManager manager for the action the condition applies to
  52116. * @param predicate defines the predicate function used to validate the condition
  52117. */
  52118. function PredicateCondition(actionManager,
  52119. /** defines the predicate function used to validate the condition */
  52120. predicate) {
  52121. var _this = _super.call(this, actionManager) || this;
  52122. _this.predicate = predicate;
  52123. return _this;
  52124. }
  52125. /**
  52126. * @returns the validity of the predicate condition
  52127. */
  52128. PredicateCondition.prototype.isValid = function () {
  52129. return this.predicate();
  52130. };
  52131. return PredicateCondition;
  52132. }(Condition));
  52133. BABYLON.PredicateCondition = PredicateCondition;
  52134. /**
  52135. * Defines a state condition as an extension of Condition
  52136. */
  52137. var StateCondition = /** @class */ (function (_super) {
  52138. __extends(StateCondition, _super);
  52139. /**
  52140. * Creates a new StateCondition
  52141. * @param actionManager manager for the action the condition applies to
  52142. * @param target of the condition
  52143. * @param value to compare with target state
  52144. */
  52145. function StateCondition(actionManager, target, value) {
  52146. var _this = _super.call(this, actionManager) || this;
  52147. _this.value = value;
  52148. _this._target = target;
  52149. return _this;
  52150. }
  52151. /**
  52152. * @returns the validity of the state
  52153. */
  52154. StateCondition.prototype.isValid = function () {
  52155. return this._target.state === this.value;
  52156. };
  52157. /**
  52158. * Serialize the StateCondition into a JSON compatible object
  52159. * @returns serialization object
  52160. */
  52161. StateCondition.prototype.serialize = function () {
  52162. return this._serialize({
  52163. name: "StateCondition",
  52164. properties: [
  52165. BABYLON.Action._GetTargetProperty(this._target),
  52166. { name: "value", value: this.value }
  52167. ]
  52168. });
  52169. };
  52170. return StateCondition;
  52171. }(Condition));
  52172. BABYLON.StateCondition = StateCondition;
  52173. })(BABYLON || (BABYLON = {}));
  52174. //# sourceMappingURL=babylon.condition.js.map
  52175. var BABYLON;
  52176. (function (BABYLON) {
  52177. /**
  52178. * The action to be carried out following a trigger
  52179. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52180. */
  52181. var Action = /** @class */ (function () {
  52182. /**
  52183. * Creates a new Action
  52184. * @param triggerOptions the trigger, with or without parameters, for the action
  52185. * @param condition an optional determinant of action
  52186. */
  52187. function Action(
  52188. /** the trigger, with or without parameters, for the action */
  52189. triggerOptions, condition) {
  52190. this.triggerOptions = triggerOptions;
  52191. /**
  52192. * An event triggered prior to action being executed.
  52193. */
  52194. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52195. if (triggerOptions.parameter) {
  52196. this.trigger = triggerOptions.trigger;
  52197. this._triggerParameter = triggerOptions.parameter;
  52198. }
  52199. else {
  52200. this.trigger = triggerOptions;
  52201. }
  52202. this._nextActiveAction = this;
  52203. this._condition = condition;
  52204. }
  52205. /**
  52206. * Internal only
  52207. * @hidden
  52208. */
  52209. Action.prototype._prepare = function () {
  52210. };
  52211. /**
  52212. * Gets the trigger parameters
  52213. * @returns the trigger parameters
  52214. */
  52215. Action.prototype.getTriggerParameter = function () {
  52216. return this._triggerParameter;
  52217. };
  52218. /**
  52219. * Internal only - executes current action event
  52220. * @hidden
  52221. */
  52222. Action.prototype._executeCurrent = function (evt) {
  52223. if (this._nextActiveAction._condition) {
  52224. var condition = this._nextActiveAction._condition;
  52225. var currentRenderId = this._actionManager.getScene().getRenderId();
  52226. // We cache the current evaluation for the current frame
  52227. if (condition._evaluationId === currentRenderId) {
  52228. if (!condition._currentResult) {
  52229. return;
  52230. }
  52231. }
  52232. else {
  52233. condition._evaluationId = currentRenderId;
  52234. if (!condition.isValid()) {
  52235. condition._currentResult = false;
  52236. return;
  52237. }
  52238. condition._currentResult = true;
  52239. }
  52240. }
  52241. this.onBeforeExecuteObservable.notifyObservers(this);
  52242. this._nextActiveAction.execute(evt);
  52243. this.skipToNextActiveAction();
  52244. };
  52245. /**
  52246. * Execute placeholder for child classes
  52247. * @param evt optional action event
  52248. */
  52249. Action.prototype.execute = function (evt) {
  52250. };
  52251. /**
  52252. * Skips to next active action
  52253. */
  52254. Action.prototype.skipToNextActiveAction = function () {
  52255. if (this._nextActiveAction._child) {
  52256. if (!this._nextActiveAction._child._actionManager) {
  52257. this._nextActiveAction._child._actionManager = this._actionManager;
  52258. }
  52259. this._nextActiveAction = this._nextActiveAction._child;
  52260. }
  52261. else {
  52262. this._nextActiveAction = this;
  52263. }
  52264. };
  52265. /**
  52266. * Adds action to chain of actions, may be a DoNothingAction
  52267. * @param action defines the next action to execute
  52268. * @returns The action passed in
  52269. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52270. */
  52271. Action.prototype.then = function (action) {
  52272. this._child = action;
  52273. action._actionManager = this._actionManager;
  52274. action._prepare();
  52275. return action;
  52276. };
  52277. /**
  52278. * Internal only
  52279. * @hidden
  52280. */
  52281. Action.prototype._getProperty = function (propertyPath) {
  52282. return this._actionManager._getProperty(propertyPath);
  52283. };
  52284. /**
  52285. * Internal only
  52286. * @hidden
  52287. */
  52288. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52289. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52290. };
  52291. /**
  52292. * Serialize placeholder for child classes
  52293. * @param parent of child
  52294. * @returns the serialized object
  52295. */
  52296. Action.prototype.serialize = function (parent) {
  52297. };
  52298. /**
  52299. * Internal only called by serialize
  52300. * @hidden
  52301. */
  52302. Action.prototype._serialize = function (serializedAction, parent) {
  52303. var serializationObject = {
  52304. type: 1,
  52305. children: [],
  52306. name: serializedAction.name,
  52307. properties: serializedAction.properties || []
  52308. };
  52309. // Serialize child
  52310. if (this._child) {
  52311. this._child.serialize(serializationObject);
  52312. }
  52313. // Check if "this" has a condition
  52314. if (this._condition) {
  52315. var serializedCondition = this._condition.serialize();
  52316. serializedCondition.children.push(serializationObject);
  52317. if (parent) {
  52318. parent.children.push(serializedCondition);
  52319. }
  52320. return serializedCondition;
  52321. }
  52322. if (parent) {
  52323. parent.children.push(serializationObject);
  52324. }
  52325. return serializationObject;
  52326. };
  52327. /**
  52328. * Internal only
  52329. * @hidden
  52330. */
  52331. Action._SerializeValueAsString = function (value) {
  52332. if (typeof value === "number") {
  52333. return value.toString();
  52334. }
  52335. if (typeof value === "boolean") {
  52336. return value ? "true" : "false";
  52337. }
  52338. if (value instanceof BABYLON.Vector2) {
  52339. return value.x + ", " + value.y;
  52340. }
  52341. if (value instanceof BABYLON.Vector3) {
  52342. return value.x + ", " + value.y + ", " + value.z;
  52343. }
  52344. if (value instanceof BABYLON.Color3) {
  52345. return value.r + ", " + value.g + ", " + value.b;
  52346. }
  52347. if (value instanceof BABYLON.Color4) {
  52348. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52349. }
  52350. return value; // string
  52351. };
  52352. /**
  52353. * Internal only
  52354. * @hidden
  52355. */
  52356. Action._GetTargetProperty = function (target) {
  52357. return {
  52358. name: "target",
  52359. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52360. : target instanceof BABYLON.Light ? "LightProperties"
  52361. : target instanceof BABYLON.Camera ? "CameraProperties"
  52362. : "SceneProperties",
  52363. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52364. };
  52365. };
  52366. return Action;
  52367. }());
  52368. BABYLON.Action = Action;
  52369. })(BABYLON || (BABYLON = {}));
  52370. //# sourceMappingURL=babylon.action.js.map
  52371. var BABYLON;
  52372. (function (BABYLON) {
  52373. /**
  52374. * ActionEvent is the event being sent when an action is triggered.
  52375. */
  52376. var ActionEvent = /** @class */ (function () {
  52377. /**
  52378. * Creates a new ActionEvent
  52379. * @param source The mesh or sprite that triggered the action
  52380. * @param pointerX The X mouse cursor position at the time of the event
  52381. * @param pointerY The Y mouse cursor position at the time of the event
  52382. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52383. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52384. * @param additionalData additional data for the event
  52385. */
  52386. function ActionEvent(
  52387. /** The mesh or sprite that triggered the action */
  52388. source,
  52389. /** The X mouse cursor position at the time of the event */
  52390. pointerX,
  52391. /** The Y mouse cursor position at the time of the event */
  52392. pointerY,
  52393. /** The mesh that is currently pointed at (can be null) */
  52394. meshUnderPointer,
  52395. /** the original (browser) event that triggered the ActionEvent */
  52396. sourceEvent,
  52397. /** additional data for the event */
  52398. additionalData) {
  52399. this.source = source;
  52400. this.pointerX = pointerX;
  52401. this.pointerY = pointerY;
  52402. this.meshUnderPointer = meshUnderPointer;
  52403. this.sourceEvent = sourceEvent;
  52404. this.additionalData = additionalData;
  52405. }
  52406. /**
  52407. * Helper function to auto-create an ActionEvent from a source mesh.
  52408. * @param source The source mesh that triggered the event
  52409. * @param evt The original (browser) event
  52410. * @param additionalData additional data for the event
  52411. * @returns the new ActionEvent
  52412. */
  52413. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52414. var scene = source.getScene();
  52415. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52416. };
  52417. /**
  52418. * Helper function to auto-create an ActionEvent from a source sprite
  52419. * @param source The source sprite that triggered the event
  52420. * @param scene Scene associated with the sprite
  52421. * @param evt The original (browser) event
  52422. * @param additionalData additional data for the event
  52423. * @returns the new ActionEvent
  52424. */
  52425. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52426. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52427. };
  52428. /**
  52429. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52430. * @param scene the scene where the event occurred
  52431. * @param evt The original (browser) event
  52432. * @returns the new ActionEvent
  52433. */
  52434. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52435. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52436. };
  52437. /**
  52438. * Helper function to auto-create an ActionEvent from a primitive
  52439. * @param prim defines the target primitive
  52440. * @param pointerPos defines the pointer position
  52441. * @param evt The original (browser) event
  52442. * @param additionalData additional data for the event
  52443. * @returns the new ActionEvent
  52444. */
  52445. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52446. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52447. };
  52448. return ActionEvent;
  52449. }());
  52450. BABYLON.ActionEvent = ActionEvent;
  52451. /**
  52452. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52453. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52454. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52455. */
  52456. var ActionManager = /** @class */ (function () {
  52457. /**
  52458. * Creates a new action manager
  52459. * @param scene defines the hosting scene
  52460. */
  52461. function ActionManager(scene) {
  52462. // Members
  52463. /** Gets the list of actions */
  52464. this.actions = new Array();
  52465. /** Gets the cursor to use when hovering items */
  52466. this.hoverCursor = '';
  52467. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52468. scene._actionManagers.push(this);
  52469. }
  52470. Object.defineProperty(ActionManager, "NothingTrigger", {
  52471. /**
  52472. * Nothing
  52473. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52474. */
  52475. get: function () {
  52476. return ActionManager._NothingTrigger;
  52477. },
  52478. enumerable: true,
  52479. configurable: true
  52480. });
  52481. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52482. /**
  52483. * On pick
  52484. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52485. */
  52486. get: function () {
  52487. return ActionManager._OnPickTrigger;
  52488. },
  52489. enumerable: true,
  52490. configurable: true
  52491. });
  52492. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52493. /**
  52494. * On left pick
  52495. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52496. */
  52497. get: function () {
  52498. return ActionManager._OnLeftPickTrigger;
  52499. },
  52500. enumerable: true,
  52501. configurable: true
  52502. });
  52503. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52504. /**
  52505. * On right pick
  52506. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52507. */
  52508. get: function () {
  52509. return ActionManager._OnRightPickTrigger;
  52510. },
  52511. enumerable: true,
  52512. configurable: true
  52513. });
  52514. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52515. /**
  52516. * On center pick
  52517. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52518. */
  52519. get: function () {
  52520. return ActionManager._OnCenterPickTrigger;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52526. /**
  52527. * On pick down
  52528. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52529. */
  52530. get: function () {
  52531. return ActionManager._OnPickDownTrigger;
  52532. },
  52533. enumerable: true,
  52534. configurable: true
  52535. });
  52536. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52537. /**
  52538. * On double pick
  52539. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52540. */
  52541. get: function () {
  52542. return ActionManager._OnDoublePickTrigger;
  52543. },
  52544. enumerable: true,
  52545. configurable: true
  52546. });
  52547. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52548. /**
  52549. * On pick up
  52550. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52551. */
  52552. get: function () {
  52553. return ActionManager._OnPickUpTrigger;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52559. /**
  52560. * On pick out.
  52561. * This trigger will only be raised if you also declared a OnPickDown
  52562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52563. */
  52564. get: function () {
  52565. return ActionManager._OnPickOutTrigger;
  52566. },
  52567. enumerable: true,
  52568. configurable: true
  52569. });
  52570. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52571. /**
  52572. * On long press
  52573. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52574. */
  52575. get: function () {
  52576. return ActionManager._OnLongPressTrigger;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52582. /**
  52583. * On pointer over
  52584. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52585. */
  52586. get: function () {
  52587. return ActionManager._OnPointerOverTrigger;
  52588. },
  52589. enumerable: true,
  52590. configurable: true
  52591. });
  52592. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52593. /**
  52594. * On pointer out
  52595. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52596. */
  52597. get: function () {
  52598. return ActionManager._OnPointerOutTrigger;
  52599. },
  52600. enumerable: true,
  52601. configurable: true
  52602. });
  52603. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52604. /**
  52605. * On every frame
  52606. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52607. */
  52608. get: function () {
  52609. return ActionManager._OnEveryFrameTrigger;
  52610. },
  52611. enumerable: true,
  52612. configurable: true
  52613. });
  52614. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52615. /**
  52616. * On intersection enter
  52617. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52618. */
  52619. get: function () {
  52620. return ActionManager._OnIntersectionEnterTrigger;
  52621. },
  52622. enumerable: true,
  52623. configurable: true
  52624. });
  52625. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52626. /**
  52627. * On intersection exit
  52628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52629. */
  52630. get: function () {
  52631. return ActionManager._OnIntersectionExitTrigger;
  52632. },
  52633. enumerable: true,
  52634. configurable: true
  52635. });
  52636. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52637. /**
  52638. * On key down
  52639. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52640. */
  52641. get: function () {
  52642. return ActionManager._OnKeyDownTrigger;
  52643. },
  52644. enumerable: true,
  52645. configurable: true
  52646. });
  52647. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52648. /**
  52649. * On key up
  52650. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52651. */
  52652. get: function () {
  52653. return ActionManager._OnKeyUpTrigger;
  52654. },
  52655. enumerable: true,
  52656. configurable: true
  52657. });
  52658. // Methods
  52659. /**
  52660. * Releases all associated resources
  52661. */
  52662. ActionManager.prototype.dispose = function () {
  52663. var index = this._scene._actionManagers.indexOf(this);
  52664. for (var i = 0; i < this.actions.length; i++) {
  52665. var action = this.actions[i];
  52666. ActionManager.Triggers[action.trigger]--;
  52667. if (ActionManager.Triggers[action.trigger] === 0) {
  52668. delete ActionManager.Triggers[action.trigger];
  52669. }
  52670. }
  52671. if (index > -1) {
  52672. this._scene._actionManagers.splice(index, 1);
  52673. }
  52674. };
  52675. /**
  52676. * Gets hosting scene
  52677. * @returns the hosting scene
  52678. */
  52679. ActionManager.prototype.getScene = function () {
  52680. return this._scene;
  52681. };
  52682. /**
  52683. * Does this action manager handles actions of any of the given triggers
  52684. * @param triggers defines the triggers to be tested
  52685. * @return a boolean indicating whether one (or more) of the triggers is handled
  52686. */
  52687. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52688. for (var index = 0; index < this.actions.length; index++) {
  52689. var action = this.actions[index];
  52690. if (triggers.indexOf(action.trigger) > -1) {
  52691. return true;
  52692. }
  52693. }
  52694. return false;
  52695. };
  52696. /**
  52697. * Does this action manager handles actions of a given trigger
  52698. * @param trigger defines the trigger to be tested
  52699. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52700. * @return whether the trigger is handled
  52701. */
  52702. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52703. for (var index = 0; index < this.actions.length; index++) {
  52704. var action = this.actions[index];
  52705. if (action.trigger === trigger) {
  52706. if (parameterPredicate) {
  52707. if (parameterPredicate(action.getTriggerParameter())) {
  52708. return true;
  52709. }
  52710. }
  52711. else {
  52712. return true;
  52713. }
  52714. }
  52715. }
  52716. return false;
  52717. };
  52718. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52719. /**
  52720. * Does this action manager has pointer triggers
  52721. */
  52722. get: function () {
  52723. for (var index = 0; index < this.actions.length; index++) {
  52724. var action = this.actions[index];
  52725. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52726. return true;
  52727. }
  52728. }
  52729. return false;
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52735. /**
  52736. * Does this action manager has pick triggers
  52737. */
  52738. get: function () {
  52739. for (var index = 0; index < this.actions.length; index++) {
  52740. var action = this.actions[index];
  52741. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52742. return true;
  52743. }
  52744. }
  52745. return false;
  52746. },
  52747. enumerable: true,
  52748. configurable: true
  52749. });
  52750. Object.defineProperty(ActionManager, "HasTriggers", {
  52751. /**
  52752. * Does exist one action manager with at least one trigger
  52753. **/
  52754. get: function () {
  52755. for (var t in ActionManager.Triggers) {
  52756. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52757. return true;
  52758. }
  52759. }
  52760. return false;
  52761. },
  52762. enumerable: true,
  52763. configurable: true
  52764. });
  52765. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52766. /**
  52767. * Does exist one action manager with at least one pick trigger
  52768. **/
  52769. get: function () {
  52770. for (var t in ActionManager.Triggers) {
  52771. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52772. var t_int = parseInt(t);
  52773. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52774. return true;
  52775. }
  52776. }
  52777. }
  52778. return false;
  52779. },
  52780. enumerable: true,
  52781. configurable: true
  52782. });
  52783. /**
  52784. * Does exist one action manager that handles actions of a given trigger
  52785. * @param trigger defines the trigger to be tested
  52786. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52787. **/
  52788. ActionManager.HasSpecificTrigger = function (trigger) {
  52789. for (var t in ActionManager.Triggers) {
  52790. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52791. var t_int = parseInt(t);
  52792. if (t_int === trigger) {
  52793. return true;
  52794. }
  52795. }
  52796. }
  52797. return false;
  52798. };
  52799. /**
  52800. * Registers an action to this action manager
  52801. * @param action defines the action to be registered
  52802. * @return the action amended (prepared) after registration
  52803. */
  52804. ActionManager.prototype.registerAction = function (action) {
  52805. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52806. if (this.getScene().actionManager !== this) {
  52807. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52808. return null;
  52809. }
  52810. }
  52811. this.actions.push(action);
  52812. if (ActionManager.Triggers[action.trigger]) {
  52813. ActionManager.Triggers[action.trigger]++;
  52814. }
  52815. else {
  52816. ActionManager.Triggers[action.trigger] = 1;
  52817. }
  52818. action._actionManager = this;
  52819. action._prepare();
  52820. return action;
  52821. };
  52822. /**
  52823. * Unregisters an action to this action manager
  52824. * @param action defines the action to be unregistered
  52825. * @return a boolean indicating whether the action has been unregistered
  52826. */
  52827. ActionManager.prototype.unregisterAction = function (action) {
  52828. var index = this.actions.indexOf(action);
  52829. if (index !== -1) {
  52830. this.actions.splice(index, 1);
  52831. ActionManager.Triggers[action.trigger] -= 1;
  52832. if (ActionManager.Triggers[action.trigger] === 0) {
  52833. delete ActionManager.Triggers[action.trigger];
  52834. }
  52835. delete action._actionManager;
  52836. return true;
  52837. }
  52838. return false;
  52839. };
  52840. /**
  52841. * Process a specific trigger
  52842. * @param trigger defines the trigger to process
  52843. * @param evt defines the event details to be processed
  52844. */
  52845. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52846. for (var index = 0; index < this.actions.length; index++) {
  52847. var action = this.actions[index];
  52848. if (action.trigger === trigger) {
  52849. if (evt) {
  52850. if (trigger === ActionManager.OnKeyUpTrigger
  52851. || trigger === ActionManager.OnKeyDownTrigger) {
  52852. var parameter = action.getTriggerParameter();
  52853. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52854. if (!parameter.toLowerCase) {
  52855. continue;
  52856. }
  52857. var lowerCase = parameter.toLowerCase();
  52858. if (lowerCase !== evt.sourceEvent.key) {
  52859. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52860. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52861. if (actualkey !== lowerCase) {
  52862. continue;
  52863. }
  52864. }
  52865. }
  52866. }
  52867. }
  52868. action._executeCurrent(evt);
  52869. }
  52870. }
  52871. };
  52872. /** @hidden */
  52873. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52874. var properties = propertyPath.split(".");
  52875. for (var index = 0; index < properties.length - 1; index++) {
  52876. target = target[properties[index]];
  52877. }
  52878. return target;
  52879. };
  52880. /** @hidden */
  52881. ActionManager.prototype._getProperty = function (propertyPath) {
  52882. var properties = propertyPath.split(".");
  52883. return properties[properties.length - 1];
  52884. };
  52885. /**
  52886. * Serialize this manager to a JSON object
  52887. * @param name defines the property name to store this manager
  52888. * @returns a JSON representation of this manager
  52889. */
  52890. ActionManager.prototype.serialize = function (name) {
  52891. var root = {
  52892. children: new Array(),
  52893. name: name,
  52894. type: 3,
  52895. properties: new Array() // Empty for root but required
  52896. };
  52897. for (var i = 0; i < this.actions.length; i++) {
  52898. var triggerObject = {
  52899. type: 0,
  52900. children: new Array(),
  52901. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52902. properties: new Array()
  52903. };
  52904. var triggerOptions = this.actions[i].triggerOptions;
  52905. if (triggerOptions && typeof triggerOptions !== "number") {
  52906. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52907. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52908. }
  52909. else {
  52910. var parameter = {};
  52911. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52912. if (triggerOptions.parameter.mesh) {
  52913. parameter._meshId = triggerOptions.parameter.mesh.id;
  52914. }
  52915. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52916. }
  52917. }
  52918. // Serialize child action, recursively
  52919. this.actions[i].serialize(triggerObject);
  52920. // Add serialized trigger
  52921. root.children.push(triggerObject);
  52922. }
  52923. return root;
  52924. };
  52925. /**
  52926. * Creates a new ActionManager from a JSON data
  52927. * @param parsedActions defines the JSON data to read from
  52928. * @param object defines the hosting mesh
  52929. * @param scene defines the hosting scene
  52930. */
  52931. ActionManager.Parse = function (parsedActions, object, scene) {
  52932. var actionManager = new ActionManager(scene);
  52933. if (object === null)
  52934. scene.actionManager = actionManager;
  52935. else
  52936. object.actionManager = actionManager;
  52937. // instanciate a new object
  52938. var instanciate = function (name, params) {
  52939. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52940. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52941. newInstance.constructor.apply(newInstance, params);
  52942. return newInstance;
  52943. };
  52944. var parseParameter = function (name, value, target, propertyPath) {
  52945. if (propertyPath === null) {
  52946. // String, boolean or float
  52947. var floatValue = parseFloat(value);
  52948. if (value === "true" || value === "false")
  52949. return value === "true";
  52950. else
  52951. return isNaN(floatValue) ? value : floatValue;
  52952. }
  52953. var effectiveTarget = propertyPath.split(".");
  52954. var values = value.split(",");
  52955. // Get effective Target
  52956. for (var i = 0; i < effectiveTarget.length; i++) {
  52957. target = target[effectiveTarget[i]];
  52958. }
  52959. // Return appropriate value with its type
  52960. if (typeof (target) === "boolean")
  52961. return values[0] === "true";
  52962. if (typeof (target) === "string")
  52963. return values[0];
  52964. // Parameters with multiple values such as Vector3 etc.
  52965. var split = new Array();
  52966. for (var i = 0; i < values.length; i++)
  52967. split.push(parseFloat(values[i]));
  52968. if (target instanceof BABYLON.Vector3)
  52969. return BABYLON.Vector3.FromArray(split);
  52970. if (target instanceof BABYLON.Vector4)
  52971. return BABYLON.Vector4.FromArray(split);
  52972. if (target instanceof BABYLON.Color3)
  52973. return BABYLON.Color3.FromArray(split);
  52974. if (target instanceof BABYLON.Color4)
  52975. return BABYLON.Color4.FromArray(split);
  52976. return parseFloat(values[0]);
  52977. };
  52978. // traverse graph per trigger
  52979. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52980. if (combineArray === void 0) { combineArray = null; }
  52981. if (parsedAction.detached)
  52982. return;
  52983. var parameters = new Array();
  52984. var target = null;
  52985. var propertyPath = null;
  52986. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52987. // Parameters
  52988. if (parsedAction.type === 2)
  52989. parameters.push(actionManager);
  52990. else
  52991. parameters.push(trigger);
  52992. if (combine) {
  52993. var actions = new Array();
  52994. for (var j = 0; j < parsedAction.combine.length; j++) {
  52995. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52996. }
  52997. parameters.push(actions);
  52998. }
  52999. else {
  53000. for (var i = 0; i < parsedAction.properties.length; i++) {
  53001. var value = parsedAction.properties[i].value;
  53002. var name = parsedAction.properties[i].name;
  53003. var targetType = parsedAction.properties[i].targetType;
  53004. if (name === "target")
  53005. if (targetType !== null && targetType === "SceneProperties")
  53006. value = target = scene;
  53007. else
  53008. value = target = scene.getNodeByName(value);
  53009. else if (name === "parent")
  53010. value = scene.getNodeByName(value);
  53011. else if (name === "sound")
  53012. value = scene.getSoundByName(value);
  53013. else if (name !== "propertyPath") {
  53014. if (parsedAction.type === 2 && name === "operator")
  53015. value = BABYLON.ValueCondition[value];
  53016. else
  53017. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53018. }
  53019. else {
  53020. propertyPath = value;
  53021. }
  53022. parameters.push(value);
  53023. }
  53024. }
  53025. if (combineArray === null) {
  53026. parameters.push(condition);
  53027. }
  53028. else {
  53029. parameters.push(null);
  53030. }
  53031. // If interpolate value action
  53032. if (parsedAction.name === "InterpolateValueAction") {
  53033. var param = parameters[parameters.length - 2];
  53034. parameters[parameters.length - 1] = param;
  53035. parameters[parameters.length - 2] = condition;
  53036. }
  53037. // Action or condition(s) and not CombineAction
  53038. var newAction = instanciate(parsedAction.name, parameters);
  53039. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53040. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53041. if (action)
  53042. action.then(nothing);
  53043. else
  53044. actionManager.registerAction(nothing);
  53045. action = nothing;
  53046. }
  53047. if (combineArray === null) {
  53048. if (newAction instanceof BABYLON.Condition) {
  53049. condition = newAction;
  53050. newAction = action;
  53051. }
  53052. else {
  53053. condition = null;
  53054. if (action)
  53055. action.then(newAction);
  53056. else
  53057. actionManager.registerAction(newAction);
  53058. }
  53059. }
  53060. else {
  53061. combineArray.push(newAction);
  53062. }
  53063. for (var i = 0; i < parsedAction.children.length; i++)
  53064. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53065. };
  53066. // triggers
  53067. for (var i = 0; i < parsedActions.children.length; i++) {
  53068. var triggerParams;
  53069. var trigger = parsedActions.children[i];
  53070. if (trigger.properties.length > 0) {
  53071. var param = trigger.properties[0].value;
  53072. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53073. if (value._meshId) {
  53074. value.mesh = scene.getMeshByID(value._meshId);
  53075. }
  53076. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53077. }
  53078. else
  53079. triggerParams = ActionManager[trigger.name];
  53080. for (var j = 0; j < trigger.children.length; j++) {
  53081. if (!trigger.detached)
  53082. traverse(trigger.children[j], triggerParams, null, null);
  53083. }
  53084. }
  53085. };
  53086. /**
  53087. * Get a trigger name by index
  53088. * @param trigger defines the trigger index
  53089. * @returns a trigger name
  53090. */
  53091. ActionManager.GetTriggerName = function (trigger) {
  53092. switch (trigger) {
  53093. case 0: return "NothingTrigger";
  53094. case 1: return "OnPickTrigger";
  53095. case 2: return "OnLeftPickTrigger";
  53096. case 3: return "OnRightPickTrigger";
  53097. case 4: return "OnCenterPickTrigger";
  53098. case 5: return "OnPickDownTrigger";
  53099. case 6: return "OnPickUpTrigger";
  53100. case 7: return "OnLongPressTrigger";
  53101. case 8: return "OnPointerOverTrigger";
  53102. case 9: return "OnPointerOutTrigger";
  53103. case 10: return "OnEveryFrameTrigger";
  53104. case 11: return "OnIntersectionEnterTrigger";
  53105. case 12: return "OnIntersectionExitTrigger";
  53106. case 13: return "OnKeyDownTrigger";
  53107. case 14: return "OnKeyUpTrigger";
  53108. case 15: return "OnPickOutTrigger";
  53109. default: return "";
  53110. }
  53111. };
  53112. // Statics
  53113. ActionManager._NothingTrigger = 0;
  53114. ActionManager._OnPickTrigger = 1;
  53115. ActionManager._OnLeftPickTrigger = 2;
  53116. ActionManager._OnRightPickTrigger = 3;
  53117. ActionManager._OnCenterPickTrigger = 4;
  53118. ActionManager._OnPickDownTrigger = 5;
  53119. ActionManager._OnDoublePickTrigger = 6;
  53120. ActionManager._OnPickUpTrigger = 7;
  53121. ActionManager._OnLongPressTrigger = 8;
  53122. ActionManager._OnPointerOverTrigger = 9;
  53123. ActionManager._OnPointerOutTrigger = 10;
  53124. ActionManager._OnEveryFrameTrigger = 11;
  53125. ActionManager._OnIntersectionEnterTrigger = 12;
  53126. ActionManager._OnIntersectionExitTrigger = 13;
  53127. ActionManager._OnKeyDownTrigger = 14;
  53128. ActionManager._OnKeyUpTrigger = 15;
  53129. ActionManager._OnPickOutTrigger = 16;
  53130. /** Gets the list of active triggers */
  53131. ActionManager.Triggers = {};
  53132. return ActionManager;
  53133. }());
  53134. BABYLON.ActionManager = ActionManager;
  53135. })(BABYLON || (BABYLON = {}));
  53136. //# sourceMappingURL=babylon.actionManager.js.map
  53137. var BABYLON;
  53138. (function (BABYLON) {
  53139. var InterpolateValueAction = /** @class */ (function (_super) {
  53140. __extends(InterpolateValueAction, _super);
  53141. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53142. if (duration === void 0) { duration = 1000; }
  53143. var _this = _super.call(this, triggerOptions, condition) || this;
  53144. _this.propertyPath = propertyPath;
  53145. _this.value = value;
  53146. _this.duration = duration;
  53147. _this.stopOtherAnimations = stopOtherAnimations;
  53148. _this.onInterpolationDone = onInterpolationDone;
  53149. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53150. _this._target = _this._effectiveTarget = target;
  53151. return _this;
  53152. }
  53153. InterpolateValueAction.prototype._prepare = function () {
  53154. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53155. this._property = this._getProperty(this.propertyPath);
  53156. };
  53157. InterpolateValueAction.prototype.execute = function () {
  53158. var _this = this;
  53159. var scene = this._actionManager.getScene();
  53160. var keys = [
  53161. {
  53162. frame: 0,
  53163. value: this._effectiveTarget[this._property]
  53164. }, {
  53165. frame: 100,
  53166. value: this.value
  53167. }
  53168. ];
  53169. var dataType;
  53170. if (typeof this.value === "number") {
  53171. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53172. }
  53173. else if (this.value instanceof BABYLON.Color3) {
  53174. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53175. }
  53176. else if (this.value instanceof BABYLON.Vector3) {
  53177. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53178. }
  53179. else if (this.value instanceof BABYLON.Matrix) {
  53180. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53181. }
  53182. else if (this.value instanceof BABYLON.Quaternion) {
  53183. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53184. }
  53185. else {
  53186. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53187. return;
  53188. }
  53189. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53190. animation.setKeys(keys);
  53191. if (this.stopOtherAnimations) {
  53192. scene.stopAnimation(this._effectiveTarget);
  53193. }
  53194. var wrapper = function () {
  53195. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53196. if (_this.onInterpolationDone) {
  53197. _this.onInterpolationDone();
  53198. }
  53199. };
  53200. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53201. };
  53202. InterpolateValueAction.prototype.serialize = function (parent) {
  53203. return _super.prototype._serialize.call(this, {
  53204. name: "InterpolateValueAction",
  53205. properties: [
  53206. BABYLON.Action._GetTargetProperty(this._target),
  53207. { name: "propertyPath", value: this.propertyPath },
  53208. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53209. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53210. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53211. ]
  53212. }, parent);
  53213. };
  53214. return InterpolateValueAction;
  53215. }(BABYLON.Action));
  53216. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53217. })(BABYLON || (BABYLON = {}));
  53218. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53219. var BABYLON;
  53220. (function (BABYLON) {
  53221. var SwitchBooleanAction = /** @class */ (function (_super) {
  53222. __extends(SwitchBooleanAction, _super);
  53223. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53224. var _this = _super.call(this, triggerOptions, condition) || this;
  53225. _this.propertyPath = propertyPath;
  53226. _this._target = _this._effectiveTarget = target;
  53227. return _this;
  53228. }
  53229. SwitchBooleanAction.prototype._prepare = function () {
  53230. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53231. this._property = this._getProperty(this.propertyPath);
  53232. };
  53233. SwitchBooleanAction.prototype.execute = function () {
  53234. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53235. };
  53236. SwitchBooleanAction.prototype.serialize = function (parent) {
  53237. return _super.prototype._serialize.call(this, {
  53238. name: "SwitchBooleanAction",
  53239. properties: [
  53240. BABYLON.Action._GetTargetProperty(this._target),
  53241. { name: "propertyPath", value: this.propertyPath }
  53242. ]
  53243. }, parent);
  53244. };
  53245. return SwitchBooleanAction;
  53246. }(BABYLON.Action));
  53247. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53248. var SetStateAction = /** @class */ (function (_super) {
  53249. __extends(SetStateAction, _super);
  53250. function SetStateAction(triggerOptions, target, value, condition) {
  53251. var _this = _super.call(this, triggerOptions, condition) || this;
  53252. _this.value = value;
  53253. _this._target = target;
  53254. return _this;
  53255. }
  53256. SetStateAction.prototype.execute = function () {
  53257. this._target.state = this.value;
  53258. };
  53259. SetStateAction.prototype.serialize = function (parent) {
  53260. return _super.prototype._serialize.call(this, {
  53261. name: "SetStateAction",
  53262. properties: [
  53263. BABYLON.Action._GetTargetProperty(this._target),
  53264. { name: "value", value: this.value }
  53265. ]
  53266. }, parent);
  53267. };
  53268. return SetStateAction;
  53269. }(BABYLON.Action));
  53270. BABYLON.SetStateAction = SetStateAction;
  53271. var SetValueAction = /** @class */ (function (_super) {
  53272. __extends(SetValueAction, _super);
  53273. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53274. var _this = _super.call(this, triggerOptions, condition) || this;
  53275. _this.propertyPath = propertyPath;
  53276. _this.value = value;
  53277. _this._target = _this._effectiveTarget = target;
  53278. return _this;
  53279. }
  53280. SetValueAction.prototype._prepare = function () {
  53281. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53282. this._property = this._getProperty(this.propertyPath);
  53283. };
  53284. SetValueAction.prototype.execute = function () {
  53285. this._effectiveTarget[this._property] = this.value;
  53286. if (this._target.markAsDirty) {
  53287. this._target.markAsDirty(this._property);
  53288. }
  53289. };
  53290. SetValueAction.prototype.serialize = function (parent) {
  53291. return _super.prototype._serialize.call(this, {
  53292. name: "SetValueAction",
  53293. properties: [
  53294. BABYLON.Action._GetTargetProperty(this._target),
  53295. { name: "propertyPath", value: this.propertyPath },
  53296. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53297. ]
  53298. }, parent);
  53299. };
  53300. return SetValueAction;
  53301. }(BABYLON.Action));
  53302. BABYLON.SetValueAction = SetValueAction;
  53303. var IncrementValueAction = /** @class */ (function (_super) {
  53304. __extends(IncrementValueAction, _super);
  53305. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53306. var _this = _super.call(this, triggerOptions, condition) || this;
  53307. _this.propertyPath = propertyPath;
  53308. _this.value = value;
  53309. _this._target = _this._effectiveTarget = target;
  53310. return _this;
  53311. }
  53312. IncrementValueAction.prototype._prepare = function () {
  53313. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53314. this._property = this._getProperty(this.propertyPath);
  53315. if (typeof this._effectiveTarget[this._property] !== "number") {
  53316. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53317. }
  53318. };
  53319. IncrementValueAction.prototype.execute = function () {
  53320. this._effectiveTarget[this._property] += this.value;
  53321. if (this._target.markAsDirty) {
  53322. this._target.markAsDirty(this._property);
  53323. }
  53324. };
  53325. IncrementValueAction.prototype.serialize = function (parent) {
  53326. return _super.prototype._serialize.call(this, {
  53327. name: "IncrementValueAction",
  53328. properties: [
  53329. BABYLON.Action._GetTargetProperty(this._target),
  53330. { name: "propertyPath", value: this.propertyPath },
  53331. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53332. ]
  53333. }, parent);
  53334. };
  53335. return IncrementValueAction;
  53336. }(BABYLON.Action));
  53337. BABYLON.IncrementValueAction = IncrementValueAction;
  53338. var PlayAnimationAction = /** @class */ (function (_super) {
  53339. __extends(PlayAnimationAction, _super);
  53340. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53341. var _this = _super.call(this, triggerOptions, condition) || this;
  53342. _this.from = from;
  53343. _this.to = to;
  53344. _this.loop = loop;
  53345. _this._target = target;
  53346. return _this;
  53347. }
  53348. PlayAnimationAction.prototype._prepare = function () {
  53349. };
  53350. PlayAnimationAction.prototype.execute = function () {
  53351. var scene = this._actionManager.getScene();
  53352. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53353. };
  53354. PlayAnimationAction.prototype.serialize = function (parent) {
  53355. return _super.prototype._serialize.call(this, {
  53356. name: "PlayAnimationAction",
  53357. properties: [
  53358. BABYLON.Action._GetTargetProperty(this._target),
  53359. { name: "from", value: String(this.from) },
  53360. { name: "to", value: String(this.to) },
  53361. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53362. ]
  53363. }, parent);
  53364. };
  53365. return PlayAnimationAction;
  53366. }(BABYLON.Action));
  53367. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53368. var StopAnimationAction = /** @class */ (function (_super) {
  53369. __extends(StopAnimationAction, _super);
  53370. function StopAnimationAction(triggerOptions, target, condition) {
  53371. var _this = _super.call(this, triggerOptions, condition) || this;
  53372. _this._target = target;
  53373. return _this;
  53374. }
  53375. StopAnimationAction.prototype._prepare = function () {
  53376. };
  53377. StopAnimationAction.prototype.execute = function () {
  53378. var scene = this._actionManager.getScene();
  53379. scene.stopAnimation(this._target);
  53380. };
  53381. StopAnimationAction.prototype.serialize = function (parent) {
  53382. return _super.prototype._serialize.call(this, {
  53383. name: "StopAnimationAction",
  53384. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53385. }, parent);
  53386. };
  53387. return StopAnimationAction;
  53388. }(BABYLON.Action));
  53389. BABYLON.StopAnimationAction = StopAnimationAction;
  53390. var DoNothingAction = /** @class */ (function (_super) {
  53391. __extends(DoNothingAction, _super);
  53392. function DoNothingAction(triggerOptions, condition) {
  53393. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53394. return _super.call(this, triggerOptions, condition) || this;
  53395. }
  53396. DoNothingAction.prototype.execute = function () {
  53397. };
  53398. DoNothingAction.prototype.serialize = function (parent) {
  53399. return _super.prototype._serialize.call(this, {
  53400. name: "DoNothingAction",
  53401. properties: []
  53402. }, parent);
  53403. };
  53404. return DoNothingAction;
  53405. }(BABYLON.Action));
  53406. BABYLON.DoNothingAction = DoNothingAction;
  53407. var CombineAction = /** @class */ (function (_super) {
  53408. __extends(CombineAction, _super);
  53409. function CombineAction(triggerOptions, children, condition) {
  53410. var _this = _super.call(this, triggerOptions, condition) || this;
  53411. _this.children = children;
  53412. return _this;
  53413. }
  53414. CombineAction.prototype._prepare = function () {
  53415. for (var index = 0; index < this.children.length; index++) {
  53416. this.children[index]._actionManager = this._actionManager;
  53417. this.children[index]._prepare();
  53418. }
  53419. };
  53420. CombineAction.prototype.execute = function (evt) {
  53421. for (var index = 0; index < this.children.length; index++) {
  53422. this.children[index].execute(evt);
  53423. }
  53424. };
  53425. CombineAction.prototype.serialize = function (parent) {
  53426. var serializationObject = _super.prototype._serialize.call(this, {
  53427. name: "CombineAction",
  53428. properties: [],
  53429. combine: []
  53430. }, parent);
  53431. for (var i = 0; i < this.children.length; i++) {
  53432. serializationObject.combine.push(this.children[i].serialize(null));
  53433. }
  53434. return serializationObject;
  53435. };
  53436. return CombineAction;
  53437. }(BABYLON.Action));
  53438. BABYLON.CombineAction = CombineAction;
  53439. var ExecuteCodeAction = /** @class */ (function (_super) {
  53440. __extends(ExecuteCodeAction, _super);
  53441. function ExecuteCodeAction(triggerOptions, func, condition) {
  53442. var _this = _super.call(this, triggerOptions, condition) || this;
  53443. _this.func = func;
  53444. return _this;
  53445. }
  53446. ExecuteCodeAction.prototype.execute = function (evt) {
  53447. this.func(evt);
  53448. };
  53449. return ExecuteCodeAction;
  53450. }(BABYLON.Action));
  53451. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53452. var SetParentAction = /** @class */ (function (_super) {
  53453. __extends(SetParentAction, _super);
  53454. function SetParentAction(triggerOptions, target, parent, condition) {
  53455. var _this = _super.call(this, triggerOptions, condition) || this;
  53456. _this._target = target;
  53457. _this._parent = parent;
  53458. return _this;
  53459. }
  53460. SetParentAction.prototype._prepare = function () {
  53461. };
  53462. SetParentAction.prototype.execute = function () {
  53463. if (this._target.parent === this._parent) {
  53464. return;
  53465. }
  53466. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53467. invertParentWorldMatrix.invert();
  53468. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53469. this._target.parent = this._parent;
  53470. };
  53471. SetParentAction.prototype.serialize = function (parent) {
  53472. return _super.prototype._serialize.call(this, {
  53473. name: "SetParentAction",
  53474. properties: [
  53475. BABYLON.Action._GetTargetProperty(this._target),
  53476. BABYLON.Action._GetTargetProperty(this._parent),
  53477. ]
  53478. }, parent);
  53479. };
  53480. return SetParentAction;
  53481. }(BABYLON.Action));
  53482. BABYLON.SetParentAction = SetParentAction;
  53483. var PlaySoundAction = /** @class */ (function (_super) {
  53484. __extends(PlaySoundAction, _super);
  53485. function PlaySoundAction(triggerOptions, sound, condition) {
  53486. var _this = _super.call(this, triggerOptions, condition) || this;
  53487. _this._sound = sound;
  53488. return _this;
  53489. }
  53490. PlaySoundAction.prototype._prepare = function () {
  53491. };
  53492. PlaySoundAction.prototype.execute = function () {
  53493. if (this._sound !== undefined)
  53494. this._sound.play();
  53495. };
  53496. PlaySoundAction.prototype.serialize = function (parent) {
  53497. return _super.prototype._serialize.call(this, {
  53498. name: "PlaySoundAction",
  53499. properties: [{ name: "sound", value: this._sound.name }]
  53500. }, parent);
  53501. };
  53502. return PlaySoundAction;
  53503. }(BABYLON.Action));
  53504. BABYLON.PlaySoundAction = PlaySoundAction;
  53505. var StopSoundAction = /** @class */ (function (_super) {
  53506. __extends(StopSoundAction, _super);
  53507. function StopSoundAction(triggerOptions, sound, condition) {
  53508. var _this = _super.call(this, triggerOptions, condition) || this;
  53509. _this._sound = sound;
  53510. return _this;
  53511. }
  53512. StopSoundAction.prototype._prepare = function () {
  53513. };
  53514. StopSoundAction.prototype.execute = function () {
  53515. if (this._sound !== undefined)
  53516. this._sound.stop();
  53517. };
  53518. StopSoundAction.prototype.serialize = function (parent) {
  53519. return _super.prototype._serialize.call(this, {
  53520. name: "StopSoundAction",
  53521. properties: [{ name: "sound", value: this._sound.name }]
  53522. }, parent);
  53523. };
  53524. return StopSoundAction;
  53525. }(BABYLON.Action));
  53526. BABYLON.StopSoundAction = StopSoundAction;
  53527. })(BABYLON || (BABYLON = {}));
  53528. //# sourceMappingURL=babylon.directActions.js.map
  53529. var BABYLON;
  53530. (function (BABYLON) {
  53531. var SpriteManager = /** @class */ (function () {
  53532. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53533. if (epsilon === void 0) { epsilon = 0.01; }
  53534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53535. this.name = name;
  53536. this.sprites = new Array();
  53537. this.renderingGroupId = 0;
  53538. this.layerMask = 0x0FFFFFFF;
  53539. this.fogEnabled = true;
  53540. this.isPickable = false;
  53541. /**
  53542. * An event triggered when the manager is disposed.
  53543. */
  53544. this.onDisposeObservable = new BABYLON.Observable();
  53545. this._vertexBuffers = {};
  53546. this._capacity = capacity;
  53547. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53548. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53549. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53550. if (cellSize.width && cellSize.height) {
  53551. this.cellWidth = cellSize.width;
  53552. this.cellHeight = cellSize.height;
  53553. }
  53554. else if (cellSize !== undefined) {
  53555. this.cellWidth = cellSize;
  53556. this.cellHeight = cellSize;
  53557. }
  53558. else {
  53559. return;
  53560. }
  53561. this._epsilon = epsilon;
  53562. this._scene = scene;
  53563. this._scene.spriteManagers.push(this);
  53564. var indices = [];
  53565. var index = 0;
  53566. for (var count = 0; count < capacity; count++) {
  53567. indices.push(index);
  53568. indices.push(index + 1);
  53569. indices.push(index + 2);
  53570. indices.push(index);
  53571. indices.push(index + 2);
  53572. indices.push(index + 3);
  53573. index += 4;
  53574. }
  53575. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53576. // VBO
  53577. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53578. this._vertexData = new Float32Array(capacity * 16 * 4);
  53579. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53580. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53581. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53582. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53583. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53584. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53585. this._vertexBuffers["options"] = options;
  53586. this._vertexBuffers["cellInfo"] = cellInfo;
  53587. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53588. // Effects
  53589. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53590. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53591. }
  53592. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53593. set: function (callback) {
  53594. if (this._onDisposeObserver) {
  53595. this.onDisposeObservable.remove(this._onDisposeObserver);
  53596. }
  53597. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53598. },
  53599. enumerable: true,
  53600. configurable: true
  53601. });
  53602. Object.defineProperty(SpriteManager.prototype, "texture", {
  53603. get: function () {
  53604. return this._spriteTexture;
  53605. },
  53606. set: function (value) {
  53607. this._spriteTexture = value;
  53608. },
  53609. enumerable: true,
  53610. configurable: true
  53611. });
  53612. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53613. var arrayOffset = index * 16;
  53614. if (offsetX === 0)
  53615. offsetX = this._epsilon;
  53616. else if (offsetX === 1)
  53617. offsetX = 1 - this._epsilon;
  53618. if (offsetY === 0)
  53619. offsetY = this._epsilon;
  53620. else if (offsetY === 1)
  53621. offsetY = 1 - this._epsilon;
  53622. this._vertexData[arrayOffset] = sprite.position.x;
  53623. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53624. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53625. this._vertexData[arrayOffset + 3] = sprite.angle;
  53626. this._vertexData[arrayOffset + 4] = sprite.width;
  53627. this._vertexData[arrayOffset + 5] = sprite.height;
  53628. this._vertexData[arrayOffset + 6] = offsetX;
  53629. this._vertexData[arrayOffset + 7] = offsetY;
  53630. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53631. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53632. var offset = (sprite.cellIndex / rowSize) >> 0;
  53633. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53634. this._vertexData[arrayOffset + 11] = offset;
  53635. // Color
  53636. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53637. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53638. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53639. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53640. };
  53641. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53642. var count = Math.min(this._capacity, this.sprites.length);
  53643. var min = BABYLON.Vector3.Zero();
  53644. var max = BABYLON.Vector3.Zero();
  53645. var distance = Number.MAX_VALUE;
  53646. var currentSprite = null;
  53647. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53648. var cameraView = camera.getViewMatrix();
  53649. for (var index = 0; index < count; index++) {
  53650. var sprite = this.sprites[index];
  53651. if (!sprite) {
  53652. continue;
  53653. }
  53654. if (predicate) {
  53655. if (!predicate(sprite)) {
  53656. continue;
  53657. }
  53658. }
  53659. else if (!sprite.isPickable) {
  53660. continue;
  53661. }
  53662. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53663. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53664. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53665. if (ray.intersectsBoxMinMax(min, max)) {
  53666. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53667. if (distance > currentDistance) {
  53668. distance = currentDistance;
  53669. currentSprite = sprite;
  53670. if (fastCheck) {
  53671. break;
  53672. }
  53673. }
  53674. }
  53675. }
  53676. if (currentSprite) {
  53677. var result = new BABYLON.PickingInfo();
  53678. result.hit = true;
  53679. result.pickedSprite = currentSprite;
  53680. result.distance = distance;
  53681. return result;
  53682. }
  53683. return null;
  53684. };
  53685. SpriteManager.prototype.render = function () {
  53686. // Check
  53687. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53688. return;
  53689. var engine = this._scene.getEngine();
  53690. var baseSize = this._spriteTexture.getBaseSize();
  53691. // Sprites
  53692. var deltaTime = engine.getDeltaTime();
  53693. var max = Math.min(this._capacity, this.sprites.length);
  53694. var rowSize = baseSize.width / this.cellWidth;
  53695. var offset = 0;
  53696. for (var index = 0; index < max; index++) {
  53697. var sprite = this.sprites[index];
  53698. if (!sprite || !sprite.isVisible) {
  53699. continue;
  53700. }
  53701. sprite._animate(deltaTime);
  53702. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53703. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53704. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53705. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53706. }
  53707. this._buffer.update(this._vertexData);
  53708. // Render
  53709. var effect = this._effectBase;
  53710. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53711. effect = this._effectFog;
  53712. }
  53713. engine.enableEffect(effect);
  53714. var viewMatrix = this._scene.getViewMatrix();
  53715. effect.setTexture("diffuseSampler", this._spriteTexture);
  53716. effect.setMatrix("view", viewMatrix);
  53717. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53718. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53719. // Fog
  53720. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53721. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53722. effect.setColor3("vFogColor", this._scene.fogColor);
  53723. }
  53724. // VBOs
  53725. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53726. // Draw order
  53727. engine.setDepthFunctionToLessOrEqual();
  53728. effect.setBool("alphaTest", true);
  53729. engine.setColorWrite(false);
  53730. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53731. engine.setColorWrite(true);
  53732. effect.setBool("alphaTest", false);
  53733. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53734. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53735. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53736. };
  53737. SpriteManager.prototype.dispose = function () {
  53738. if (this._buffer) {
  53739. this._buffer.dispose();
  53740. this._buffer = null;
  53741. }
  53742. if (this._indexBuffer) {
  53743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53744. this._indexBuffer = null;
  53745. }
  53746. if (this._spriteTexture) {
  53747. this._spriteTexture.dispose();
  53748. this._spriteTexture = null;
  53749. }
  53750. // Remove from scene
  53751. var index = this._scene.spriteManagers.indexOf(this);
  53752. this._scene.spriteManagers.splice(index, 1);
  53753. // Callback
  53754. this.onDisposeObservable.notifyObservers(this);
  53755. this.onDisposeObservable.clear();
  53756. };
  53757. return SpriteManager;
  53758. }());
  53759. BABYLON.SpriteManager = SpriteManager;
  53760. })(BABYLON || (BABYLON = {}));
  53761. //# sourceMappingURL=babylon.spriteManager.js.map
  53762. var BABYLON;
  53763. (function (BABYLON) {
  53764. var Sprite = /** @class */ (function () {
  53765. function Sprite(name, manager) {
  53766. this.name = name;
  53767. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53768. this.width = 1.0;
  53769. this.height = 1.0;
  53770. this.angle = 0;
  53771. this.cellIndex = 0;
  53772. this.invertU = 0;
  53773. this.invertV = 0;
  53774. this.animations = new Array();
  53775. this.isPickable = false;
  53776. this._animationStarted = false;
  53777. this._loopAnimation = false;
  53778. this._fromIndex = 0;
  53779. this._toIndex = 0;
  53780. this._delay = 0;
  53781. this._direction = 1;
  53782. this._time = 0;
  53783. /**
  53784. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53785. */
  53786. this.isVisible = true;
  53787. this._manager = manager;
  53788. this._manager.sprites.push(this);
  53789. this.position = BABYLON.Vector3.Zero();
  53790. }
  53791. Object.defineProperty(Sprite.prototype, "size", {
  53792. get: function () {
  53793. return this.width;
  53794. },
  53795. set: function (value) {
  53796. this.width = value;
  53797. this.height = value;
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53803. this._fromIndex = from;
  53804. this._toIndex = to;
  53805. this._loopAnimation = loop;
  53806. this._delay = delay;
  53807. this._animationStarted = true;
  53808. this._direction = from < to ? 1 : -1;
  53809. this.cellIndex = from;
  53810. this._time = 0;
  53811. this._onAnimationEnd = onAnimationEnd;
  53812. };
  53813. Sprite.prototype.stopAnimation = function () {
  53814. this._animationStarted = false;
  53815. };
  53816. Sprite.prototype._animate = function (deltaTime) {
  53817. if (!this._animationStarted)
  53818. return;
  53819. this._time += deltaTime;
  53820. if (this._time > this._delay) {
  53821. this._time = this._time % this._delay;
  53822. this.cellIndex += this._direction;
  53823. if (this.cellIndex > this._toIndex) {
  53824. if (this._loopAnimation) {
  53825. this.cellIndex = this._fromIndex;
  53826. }
  53827. else {
  53828. this.cellIndex = this._toIndex;
  53829. this._animationStarted = false;
  53830. if (this._onAnimationEnd) {
  53831. this._onAnimationEnd();
  53832. }
  53833. if (this.disposeWhenFinishedAnimating) {
  53834. this.dispose();
  53835. }
  53836. }
  53837. }
  53838. }
  53839. };
  53840. Sprite.prototype.dispose = function () {
  53841. for (var i = 0; i < this._manager.sprites.length; i++) {
  53842. if (this._manager.sprites[i] == this) {
  53843. this._manager.sprites.splice(i, 1);
  53844. }
  53845. }
  53846. };
  53847. return Sprite;
  53848. }());
  53849. BABYLON.Sprite = Sprite;
  53850. })(BABYLON || (BABYLON = {}));
  53851. //# sourceMappingURL=babylon.sprite.js.map
  53852. var BABYLON;
  53853. (function (BABYLON) {
  53854. var IntersectionInfo = /** @class */ (function () {
  53855. function IntersectionInfo(bu, bv, distance) {
  53856. this.bu = bu;
  53857. this.bv = bv;
  53858. this.distance = distance;
  53859. this.faceId = 0;
  53860. this.subMeshId = 0;
  53861. }
  53862. return IntersectionInfo;
  53863. }());
  53864. BABYLON.IntersectionInfo = IntersectionInfo;
  53865. /**
  53866. * Information about the result of picking within a scene
  53867. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53868. */
  53869. var PickingInfo = /** @class */ (function () {
  53870. function PickingInfo() {
  53871. /**
  53872. * If the pick collided with an object
  53873. */
  53874. this.hit = false;
  53875. /**
  53876. * Distance away where the pick collided
  53877. */
  53878. this.distance = 0;
  53879. /**
  53880. * The location of pick collision
  53881. */
  53882. this.pickedPoint = null;
  53883. /**
  53884. * The mesh corrisponding the the pick collision
  53885. */
  53886. this.pickedMesh = null;
  53887. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53888. this.bu = 0;
  53889. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53890. this.bv = 0;
  53891. /** The id of the face on the mesh that was picked */
  53892. this.faceId = -1;
  53893. /** Id of the the submesh that was picked */
  53894. this.subMeshId = 0;
  53895. /** If a sprite was picked, this will be the sprite the pick collided with */
  53896. this.pickedSprite = null;
  53897. /**
  53898. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53899. */
  53900. this.originMesh = null;
  53901. /**
  53902. * The ray that was used to perform the picking.
  53903. */
  53904. this.ray = null;
  53905. }
  53906. /**
  53907. * Gets the normal corrispodning to the face the pick collided with
  53908. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53909. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53910. * @returns The normal corrispodning to the face the pick collided with
  53911. */
  53912. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53913. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53914. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53915. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53916. return null;
  53917. }
  53918. var indices = this.pickedMesh.getIndices();
  53919. if (!indices) {
  53920. return null;
  53921. }
  53922. var result;
  53923. if (useVerticesNormals) {
  53924. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53925. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53926. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53927. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53928. normal0 = normal0.scale(this.bu);
  53929. normal1 = normal1.scale(this.bv);
  53930. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53931. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53932. }
  53933. else {
  53934. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53935. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53936. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53937. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53938. var p1p2 = vertex1.subtract(vertex2);
  53939. var p3p2 = vertex3.subtract(vertex2);
  53940. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53941. }
  53942. if (useWorldCoordinates) {
  53943. var wm = this.pickedMesh.getWorldMatrix();
  53944. if (this.pickedMesh.nonUniformScaling) {
  53945. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53946. wm = BABYLON.Tmp.Matrix[0];
  53947. wm.setTranslationFromFloats(0, 0, 0);
  53948. wm.invert();
  53949. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53950. wm = BABYLON.Tmp.Matrix[1];
  53951. }
  53952. result = BABYLON.Vector3.TransformNormal(result, wm);
  53953. }
  53954. result.normalize();
  53955. return result;
  53956. };
  53957. /**
  53958. * Gets the texture coordinates of where the pick occured
  53959. * @returns the vector containing the coordnates of the texture
  53960. */
  53961. PickingInfo.prototype.getTextureCoordinates = function () {
  53962. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53963. return null;
  53964. }
  53965. var indices = this.pickedMesh.getIndices();
  53966. if (!indices) {
  53967. return null;
  53968. }
  53969. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53970. if (!uvs) {
  53971. return null;
  53972. }
  53973. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53974. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53975. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53976. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53977. uv1 = uv1.scale(this.bu);
  53978. uv2 = uv2.scale(this.bv);
  53979. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53980. };
  53981. return PickingInfo;
  53982. }());
  53983. BABYLON.PickingInfo = PickingInfo;
  53984. })(BABYLON || (BABYLON = {}));
  53985. //# sourceMappingURL=babylon.pickingInfo.js.map
  53986. var BABYLON;
  53987. (function (BABYLON) {
  53988. var Ray = /** @class */ (function () {
  53989. function Ray(origin, direction, length) {
  53990. if (length === void 0) { length = Number.MAX_VALUE; }
  53991. this.origin = origin;
  53992. this.direction = direction;
  53993. this.length = length;
  53994. }
  53995. // Methods
  53996. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53997. var d = 0.0;
  53998. var maxValue = Number.MAX_VALUE;
  53999. var inv;
  54000. var min;
  54001. var max;
  54002. var temp;
  54003. if (Math.abs(this.direction.x) < 0.0000001) {
  54004. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54005. return false;
  54006. }
  54007. }
  54008. else {
  54009. inv = 1.0 / this.direction.x;
  54010. min = (minimum.x - this.origin.x) * inv;
  54011. max = (maximum.x - this.origin.x) * inv;
  54012. if (max === -Infinity) {
  54013. max = Infinity;
  54014. }
  54015. if (min > max) {
  54016. temp = min;
  54017. min = max;
  54018. max = temp;
  54019. }
  54020. d = Math.max(min, d);
  54021. maxValue = Math.min(max, maxValue);
  54022. if (d > maxValue) {
  54023. return false;
  54024. }
  54025. }
  54026. if (Math.abs(this.direction.y) < 0.0000001) {
  54027. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54028. return false;
  54029. }
  54030. }
  54031. else {
  54032. inv = 1.0 / this.direction.y;
  54033. min = (minimum.y - this.origin.y) * inv;
  54034. max = (maximum.y - this.origin.y) * inv;
  54035. if (max === -Infinity) {
  54036. max = Infinity;
  54037. }
  54038. if (min > max) {
  54039. temp = min;
  54040. min = max;
  54041. max = temp;
  54042. }
  54043. d = Math.max(min, d);
  54044. maxValue = Math.min(max, maxValue);
  54045. if (d > maxValue) {
  54046. return false;
  54047. }
  54048. }
  54049. if (Math.abs(this.direction.z) < 0.0000001) {
  54050. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54051. return false;
  54052. }
  54053. }
  54054. else {
  54055. inv = 1.0 / this.direction.z;
  54056. min = (minimum.z - this.origin.z) * inv;
  54057. max = (maximum.z - this.origin.z) * inv;
  54058. if (max === -Infinity) {
  54059. max = Infinity;
  54060. }
  54061. if (min > max) {
  54062. temp = min;
  54063. min = max;
  54064. max = temp;
  54065. }
  54066. d = Math.max(min, d);
  54067. maxValue = Math.min(max, maxValue);
  54068. if (d > maxValue) {
  54069. return false;
  54070. }
  54071. }
  54072. return true;
  54073. };
  54074. Ray.prototype.intersectsBox = function (box) {
  54075. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54076. };
  54077. Ray.prototype.intersectsSphere = function (sphere) {
  54078. var x = sphere.center.x - this.origin.x;
  54079. var y = sphere.center.y - this.origin.y;
  54080. var z = sphere.center.z - this.origin.z;
  54081. var pyth = (x * x) + (y * y) + (z * z);
  54082. var rr = sphere.radius * sphere.radius;
  54083. if (pyth <= rr) {
  54084. return true;
  54085. }
  54086. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54087. if (dot < 0.0) {
  54088. return false;
  54089. }
  54090. var temp = pyth - (dot * dot);
  54091. return temp <= rr;
  54092. };
  54093. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54094. if (!this._edge1) {
  54095. this._edge1 = BABYLON.Vector3.Zero();
  54096. this._edge2 = BABYLON.Vector3.Zero();
  54097. this._pvec = BABYLON.Vector3.Zero();
  54098. this._tvec = BABYLON.Vector3.Zero();
  54099. this._qvec = BABYLON.Vector3.Zero();
  54100. }
  54101. vertex1.subtractToRef(vertex0, this._edge1);
  54102. vertex2.subtractToRef(vertex0, this._edge2);
  54103. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54104. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54105. if (det === 0) {
  54106. return null;
  54107. }
  54108. var invdet = 1 / det;
  54109. this.origin.subtractToRef(vertex0, this._tvec);
  54110. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54111. if (bu < 0 || bu > 1.0) {
  54112. return null;
  54113. }
  54114. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54115. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54116. if (bv < 0 || bu + bv > 1.0) {
  54117. return null;
  54118. }
  54119. //check if the distance is longer than the predefined length.
  54120. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54121. if (distance > this.length) {
  54122. return null;
  54123. }
  54124. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54125. };
  54126. Ray.prototype.intersectsPlane = function (plane) {
  54127. var distance;
  54128. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54129. if (Math.abs(result1) < 9.99999997475243E-07) {
  54130. return null;
  54131. }
  54132. else {
  54133. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54134. distance = (-plane.d - result2) / result1;
  54135. if (distance < 0.0) {
  54136. if (distance < -9.99999997475243E-07) {
  54137. return null;
  54138. }
  54139. else {
  54140. return 0;
  54141. }
  54142. }
  54143. return distance;
  54144. }
  54145. };
  54146. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54147. var tm = BABYLON.Tmp.Matrix[0];
  54148. mesh.getWorldMatrix().invertToRef(tm);
  54149. if (this._tmpRay) {
  54150. Ray.TransformToRef(this, tm, this._tmpRay);
  54151. }
  54152. else {
  54153. this._tmpRay = Ray.Transform(this, tm);
  54154. }
  54155. return mesh.intersects(this._tmpRay, fastCheck);
  54156. };
  54157. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54158. if (results) {
  54159. results.length = 0;
  54160. }
  54161. else {
  54162. results = [];
  54163. }
  54164. for (var i = 0; i < meshes.length; i++) {
  54165. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54166. if (pickInfo.hit) {
  54167. results.push(pickInfo);
  54168. }
  54169. }
  54170. results.sort(this._comparePickingInfo);
  54171. return results;
  54172. };
  54173. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54174. if (pickingInfoA.distance < pickingInfoB.distance) {
  54175. return -1;
  54176. }
  54177. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54178. return 1;
  54179. }
  54180. else {
  54181. return 0;
  54182. }
  54183. };
  54184. /**
  54185. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54186. * @param sega the first point of the segment to test the intersection against
  54187. * @param segb the second point of the segment to test the intersection against
  54188. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54189. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54190. */
  54191. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54192. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54193. var u = segb.subtract(sega);
  54194. var v = rsegb.subtract(this.origin);
  54195. var w = sega.subtract(this.origin);
  54196. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54197. var b = BABYLON.Vector3.Dot(u, v);
  54198. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54199. var d = BABYLON.Vector3.Dot(u, w);
  54200. var e = BABYLON.Vector3.Dot(v, w);
  54201. var D = a * c - b * b; // always >= 0
  54202. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54203. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54204. // compute the line parameters of the two closest points
  54205. if (D < Ray.smallnum) { // the lines are almost parallel
  54206. sN = 0.0; // force using point P0 on segment S1
  54207. sD = 1.0; // to prevent possible division by 0.0 later
  54208. tN = e;
  54209. tD = c;
  54210. }
  54211. else { // get the closest points on the infinite lines
  54212. sN = (b * e - c * d);
  54213. tN = (a * e - b * d);
  54214. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54215. sN = 0.0;
  54216. tN = e;
  54217. tD = c;
  54218. }
  54219. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54220. sN = sD;
  54221. tN = e + b;
  54222. tD = c;
  54223. }
  54224. }
  54225. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54226. tN = 0.0;
  54227. // recompute sc for this edge
  54228. if (-d < 0.0) {
  54229. sN = 0.0;
  54230. }
  54231. else if (-d > a)
  54232. sN = sD;
  54233. else {
  54234. sN = -d;
  54235. sD = a;
  54236. }
  54237. }
  54238. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54239. tN = tD;
  54240. // recompute sc for this edge
  54241. if ((-d + b) < 0.0) {
  54242. sN = 0;
  54243. }
  54244. else if ((-d + b) > a) {
  54245. sN = sD;
  54246. }
  54247. else {
  54248. sN = (-d + b);
  54249. sD = a;
  54250. }
  54251. }
  54252. // finally do the division to get sc and tc
  54253. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54254. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54255. // get the difference of the two closest points
  54256. var qtc = v.multiplyByFloats(tc, tc, tc);
  54257. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54258. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54259. if (isIntersected) {
  54260. return qtc.length();
  54261. }
  54262. return -1;
  54263. };
  54264. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54265. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54266. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54267. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54268. this.direction.normalize();
  54269. return this;
  54270. };
  54271. // Statics
  54272. Ray.Zero = function () {
  54273. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54274. };
  54275. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54276. var result = Ray.Zero();
  54277. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54278. };
  54279. /**
  54280. * 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
  54281. * transformed to the given world matrix.
  54282. * @param origin The origin point
  54283. * @param end The end point
  54284. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54285. */
  54286. Ray.CreateNewFromTo = function (origin, end, world) {
  54287. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54288. var direction = end.subtract(origin);
  54289. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54290. direction.normalize();
  54291. return Ray.Transform(new Ray(origin, direction, length), world);
  54292. };
  54293. Ray.Transform = function (ray, matrix) {
  54294. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54295. Ray.TransformToRef(ray, matrix, result);
  54296. return result;
  54297. };
  54298. Ray.TransformToRef = function (ray, matrix, result) {
  54299. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54300. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54301. result.length = ray.length;
  54302. var dir = result.direction;
  54303. var len = dir.length();
  54304. if (!(len === 0 || len === 1)) {
  54305. var num = 1.0 / len;
  54306. dir.x *= num;
  54307. dir.y *= num;
  54308. dir.z *= num;
  54309. result.length *= len;
  54310. }
  54311. };
  54312. Ray.smallnum = 0.00000001;
  54313. Ray.rayl = 10e8;
  54314. return Ray;
  54315. }());
  54316. BABYLON.Ray = Ray;
  54317. })(BABYLON || (BABYLON = {}));
  54318. //# sourceMappingURL=babylon.ray.js.map
  54319. var BABYLON;
  54320. (function (BABYLON) {
  54321. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54322. if (boxMin.x > sphereCenter.x + sphereRadius)
  54323. return false;
  54324. if (sphereCenter.x - sphereRadius > boxMax.x)
  54325. return false;
  54326. if (boxMin.y > sphereCenter.y + sphereRadius)
  54327. return false;
  54328. if (sphereCenter.y - sphereRadius > boxMax.y)
  54329. return false;
  54330. if (boxMin.z > sphereCenter.z + sphereRadius)
  54331. return false;
  54332. if (sphereCenter.z - sphereRadius > boxMax.z)
  54333. return false;
  54334. return true;
  54335. };
  54336. var getLowestRoot = (function () {
  54337. var result = { root: 0, found: false };
  54338. return function (a, b, c, maxR) {
  54339. result.root = 0;
  54340. result.found = false;
  54341. var determinant = b * b - 4.0 * a * c;
  54342. if (determinant < 0)
  54343. return result;
  54344. var sqrtD = Math.sqrt(determinant);
  54345. var r1 = (-b - sqrtD) / (2.0 * a);
  54346. var r2 = (-b + sqrtD) / (2.0 * a);
  54347. if (r1 > r2) {
  54348. var temp = r2;
  54349. r2 = r1;
  54350. r1 = temp;
  54351. }
  54352. if (r1 > 0 && r1 < maxR) {
  54353. result.root = r1;
  54354. result.found = true;
  54355. return result;
  54356. }
  54357. if (r2 > 0 && r2 < maxR) {
  54358. result.root = r2;
  54359. result.found = true;
  54360. return result;
  54361. }
  54362. return result;
  54363. };
  54364. })();
  54365. var Collider = /** @class */ (function () {
  54366. function Collider() {
  54367. this._collisionPoint = BABYLON.Vector3.Zero();
  54368. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54369. this._tempVector = BABYLON.Vector3.Zero();
  54370. this._tempVector2 = BABYLON.Vector3.Zero();
  54371. this._tempVector3 = BABYLON.Vector3.Zero();
  54372. this._tempVector4 = BABYLON.Vector3.Zero();
  54373. this._edge = BABYLON.Vector3.Zero();
  54374. this._baseToVertex = BABYLON.Vector3.Zero();
  54375. this._destinationPoint = BABYLON.Vector3.Zero();
  54376. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54377. this._displacementVector = BABYLON.Vector3.Zero();
  54378. this._radius = BABYLON.Vector3.One();
  54379. this._retry = 0;
  54380. this._basePointWorld = BABYLON.Vector3.Zero();
  54381. this._velocityWorld = BABYLON.Vector3.Zero();
  54382. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54383. this._collisionMask = -1;
  54384. }
  54385. Object.defineProperty(Collider.prototype, "collisionMask", {
  54386. get: function () {
  54387. return this._collisionMask;
  54388. },
  54389. set: function (mask) {
  54390. this._collisionMask = !isNaN(mask) ? mask : -1;
  54391. },
  54392. enumerable: true,
  54393. configurable: true
  54394. });
  54395. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54396. /**
  54397. * Gets the plane normal used to compute the sliding response (in local space)
  54398. */
  54399. get: function () {
  54400. return this._slidePlaneNormal;
  54401. },
  54402. enumerable: true,
  54403. configurable: true
  54404. });
  54405. // Methods
  54406. Collider.prototype._initialize = function (source, dir, e) {
  54407. this._velocity = dir;
  54408. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54409. this._basePoint = source;
  54410. source.multiplyToRef(this._radius, this._basePointWorld);
  54411. dir.multiplyToRef(this._radius, this._velocityWorld);
  54412. this._velocityWorldLength = this._velocityWorld.length();
  54413. this._epsilon = e;
  54414. this.collisionFound = false;
  54415. };
  54416. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54417. pa.subtractToRef(point, this._tempVector);
  54418. pb.subtractToRef(point, this._tempVector2);
  54419. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54420. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54421. if (d < 0)
  54422. return false;
  54423. pc.subtractToRef(point, this._tempVector3);
  54424. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54425. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54426. if (d < 0)
  54427. return false;
  54428. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54429. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54430. return d >= 0;
  54431. };
  54432. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54433. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54434. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54435. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54436. return false;
  54437. }
  54438. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54439. return false;
  54440. return true;
  54441. };
  54442. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54443. var t0;
  54444. var embeddedInPlane = false;
  54445. //defensive programming, actually not needed.
  54446. if (!trianglePlaneArray) {
  54447. trianglePlaneArray = [];
  54448. }
  54449. if (!trianglePlaneArray[faceIndex]) {
  54450. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54451. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54452. }
  54453. var trianglePlane = trianglePlaneArray[faceIndex];
  54454. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54455. return;
  54456. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54457. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54458. if (normalDotVelocity == 0) {
  54459. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54460. return;
  54461. embeddedInPlane = true;
  54462. t0 = 0;
  54463. }
  54464. else {
  54465. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54466. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54467. if (t0 > t1) {
  54468. var temp = t1;
  54469. t1 = t0;
  54470. t0 = temp;
  54471. }
  54472. if (t0 > 1.0 || t1 < 0.0)
  54473. return;
  54474. if (t0 < 0)
  54475. t0 = 0;
  54476. if (t0 > 1.0)
  54477. t0 = 1.0;
  54478. }
  54479. this._collisionPoint.copyFromFloats(0, 0, 0);
  54480. var found = false;
  54481. var t = 1.0;
  54482. if (!embeddedInPlane) {
  54483. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54484. this._velocity.scaleToRef(t0, this._tempVector);
  54485. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54486. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54487. found = true;
  54488. t = t0;
  54489. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54490. }
  54491. }
  54492. if (!found) {
  54493. var velocitySquaredLength = this._velocity.lengthSquared();
  54494. var a = velocitySquaredLength;
  54495. this._basePoint.subtractToRef(p1, this._tempVector);
  54496. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54497. var c = this._tempVector.lengthSquared() - 1.0;
  54498. var lowestRoot = getLowestRoot(a, b, c, t);
  54499. if (lowestRoot.found) {
  54500. t = lowestRoot.root;
  54501. found = true;
  54502. this._collisionPoint.copyFrom(p1);
  54503. }
  54504. this._basePoint.subtractToRef(p2, this._tempVector);
  54505. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54506. c = this._tempVector.lengthSquared() - 1.0;
  54507. lowestRoot = getLowestRoot(a, b, c, t);
  54508. if (lowestRoot.found) {
  54509. t = lowestRoot.root;
  54510. found = true;
  54511. this._collisionPoint.copyFrom(p2);
  54512. }
  54513. this._basePoint.subtractToRef(p3, this._tempVector);
  54514. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54515. c = this._tempVector.lengthSquared() - 1.0;
  54516. lowestRoot = getLowestRoot(a, b, c, t);
  54517. if (lowestRoot.found) {
  54518. t = lowestRoot.root;
  54519. found = true;
  54520. this._collisionPoint.copyFrom(p3);
  54521. }
  54522. p2.subtractToRef(p1, this._edge);
  54523. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54524. var edgeSquaredLength = this._edge.lengthSquared();
  54525. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54526. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54527. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54528. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54529. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54530. lowestRoot = getLowestRoot(a, b, c, t);
  54531. if (lowestRoot.found) {
  54532. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54533. if (f >= 0.0 && f <= 1.0) {
  54534. t = lowestRoot.root;
  54535. found = true;
  54536. this._edge.scaleInPlace(f);
  54537. p1.addToRef(this._edge, this._collisionPoint);
  54538. }
  54539. }
  54540. p3.subtractToRef(p2, this._edge);
  54541. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54542. edgeSquaredLength = this._edge.lengthSquared();
  54543. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54544. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54545. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54546. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54547. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54548. lowestRoot = getLowestRoot(a, b, c, t);
  54549. if (lowestRoot.found) {
  54550. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54551. if (f >= 0.0 && f <= 1.0) {
  54552. t = lowestRoot.root;
  54553. found = true;
  54554. this._edge.scaleInPlace(f);
  54555. p2.addToRef(this._edge, this._collisionPoint);
  54556. }
  54557. }
  54558. p1.subtractToRef(p3, this._edge);
  54559. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54560. edgeSquaredLength = this._edge.lengthSquared();
  54561. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54562. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54563. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54564. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54565. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54566. lowestRoot = getLowestRoot(a, b, c, t);
  54567. if (lowestRoot.found) {
  54568. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54569. if (f >= 0.0 && f <= 1.0) {
  54570. t = lowestRoot.root;
  54571. found = true;
  54572. this._edge.scaleInPlace(f);
  54573. p3.addToRef(this._edge, this._collisionPoint);
  54574. }
  54575. }
  54576. }
  54577. if (found) {
  54578. var distToCollision = t * this._velocity.length();
  54579. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54580. if (!this.intersectionPoint) {
  54581. this.intersectionPoint = this._collisionPoint.clone();
  54582. }
  54583. else {
  54584. this.intersectionPoint.copyFrom(this._collisionPoint);
  54585. }
  54586. this._nearestDistance = distToCollision;
  54587. this.collisionFound = true;
  54588. }
  54589. }
  54590. };
  54591. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54592. for (var i = indexStart; i < indexEnd; i += 3) {
  54593. var p1 = pts[indices[i] - decal];
  54594. var p2 = pts[indices[i + 1] - decal];
  54595. var p3 = pts[indices[i + 2] - decal];
  54596. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54597. }
  54598. };
  54599. Collider.prototype._getResponse = function (pos, vel) {
  54600. pos.addToRef(vel, this._destinationPoint);
  54601. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54602. this._basePoint.addToRef(vel, pos);
  54603. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54604. this._slidePlaneNormal.normalize();
  54605. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54606. pos.addInPlace(this._displacementVector);
  54607. this.intersectionPoint.addInPlace(this._displacementVector);
  54608. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54609. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54610. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54611. };
  54612. return Collider;
  54613. }());
  54614. BABYLON.Collider = Collider;
  54615. })(BABYLON || (BABYLON = {}));
  54616. //# sourceMappingURL=babylon.collider.js.map
  54617. var BABYLON;
  54618. (function (BABYLON) {
  54619. //WebWorker code will be inserted to this variable.
  54620. BABYLON.CollisionWorker = "";
  54621. /** Defines supported task for worker process */
  54622. var WorkerTaskType;
  54623. (function (WorkerTaskType) {
  54624. /** Initialization */
  54625. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54626. /** Update of geometry */
  54627. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54628. /** Evaluate collision */
  54629. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54630. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54631. /** Defines kind of replies returned by worker */
  54632. var WorkerReplyType;
  54633. (function (WorkerReplyType) {
  54634. /** Success */
  54635. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54636. /** Unkown error */
  54637. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54638. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54639. var CollisionCoordinatorWorker = /** @class */ (function () {
  54640. function CollisionCoordinatorWorker() {
  54641. var _this = this;
  54642. this._scaledPosition = BABYLON.Vector3.Zero();
  54643. this._scaledVelocity = BABYLON.Vector3.Zero();
  54644. this.onMeshUpdated = function (transformNode) {
  54645. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54646. };
  54647. this.onGeometryUpdated = function (geometry) {
  54648. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54649. };
  54650. this._afterRender = function () {
  54651. if (!_this._init)
  54652. return;
  54653. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54654. return;
  54655. }
  54656. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54657. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54658. if (_this._runningUpdated > 4) {
  54659. return;
  54660. }
  54661. ++_this._runningUpdated;
  54662. var payload = {
  54663. updatedMeshes: _this._addUpdateMeshesList,
  54664. updatedGeometries: _this._addUpdateGeometriesList,
  54665. removedGeometries: _this._toRemoveGeometryArray,
  54666. removedMeshes: _this._toRemoveMeshesArray
  54667. };
  54668. var message = {
  54669. payload: payload,
  54670. taskType: WorkerTaskType.UPDATE
  54671. };
  54672. var serializable = [];
  54673. for (var id in payload.updatedGeometries) {
  54674. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54675. //prepare transferables
  54676. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54677. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54678. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54679. }
  54680. }
  54681. _this._worker.postMessage(message, serializable);
  54682. _this._addUpdateMeshesList = {};
  54683. _this._addUpdateGeometriesList = {};
  54684. _this._toRemoveGeometryArray = [];
  54685. _this._toRemoveMeshesArray = [];
  54686. };
  54687. this._onMessageFromWorker = function (e) {
  54688. var returnData = e.data;
  54689. if (returnData.error != WorkerReplyType.SUCCESS) {
  54690. //TODO what errors can be returned from the worker?
  54691. BABYLON.Tools.Warn("error returned from worker!");
  54692. return;
  54693. }
  54694. switch (returnData.taskType) {
  54695. case WorkerTaskType.INIT:
  54696. _this._init = true;
  54697. //Update the worked with ALL of the scene's current state
  54698. _this._scene.meshes.forEach(function (mesh) {
  54699. _this.onMeshAdded(mesh);
  54700. });
  54701. _this._scene.getGeometries().forEach(function (geometry) {
  54702. _this.onGeometryAdded(geometry);
  54703. });
  54704. break;
  54705. case WorkerTaskType.UPDATE:
  54706. _this._runningUpdated--;
  54707. break;
  54708. case WorkerTaskType.COLLIDE:
  54709. var returnPayload = returnData.payload;
  54710. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54711. return;
  54712. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54713. if (callback) {
  54714. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54715. if (mesh) {
  54716. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54717. }
  54718. }
  54719. //cleanup
  54720. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54721. break;
  54722. }
  54723. };
  54724. this._collisionsCallbackArray = [];
  54725. this._init = false;
  54726. this._runningUpdated = 0;
  54727. this._addUpdateMeshesList = {};
  54728. this._addUpdateGeometriesList = {};
  54729. this._toRemoveGeometryArray = [];
  54730. this._toRemoveMeshesArray = [];
  54731. }
  54732. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54733. if (!this._init)
  54734. return;
  54735. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54736. return;
  54737. position.divideToRef(collider._radius, this._scaledPosition);
  54738. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54739. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54740. var payload = {
  54741. collider: {
  54742. position: this._scaledPosition.asArray(),
  54743. velocity: this._scaledVelocity.asArray(),
  54744. radius: collider._radius.asArray()
  54745. },
  54746. collisionId: collisionIndex,
  54747. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54748. maximumRetry: maximumRetry
  54749. };
  54750. var message = {
  54751. payload: payload,
  54752. taskType: WorkerTaskType.COLLIDE
  54753. };
  54754. this._worker.postMessage(message);
  54755. };
  54756. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54757. this._scene = scene;
  54758. this._scene.registerAfterRender(this._afterRender);
  54759. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54760. this._worker = new Worker(workerUrl);
  54761. this._worker.onmessage = this._onMessageFromWorker;
  54762. var message = {
  54763. payload: {},
  54764. taskType: WorkerTaskType.INIT
  54765. };
  54766. this._worker.postMessage(message);
  54767. };
  54768. CollisionCoordinatorWorker.prototype.destroy = function () {
  54769. this._scene.unregisterAfterRender(this._afterRender);
  54770. this._worker.terminate();
  54771. };
  54772. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54773. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54774. this.onMeshUpdated(mesh);
  54775. };
  54776. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54777. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54778. };
  54779. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54780. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54781. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54782. this.onGeometryUpdated(geometry);
  54783. };
  54784. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54785. this._toRemoveGeometryArray.push(geometry.id);
  54786. };
  54787. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54788. var submeshes = [];
  54789. if (mesh.subMeshes) {
  54790. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54791. var boundingInfo = sm.getBoundingInfo();
  54792. return {
  54793. position: idx,
  54794. verticesStart: sm.verticesStart,
  54795. verticesCount: sm.verticesCount,
  54796. indexStart: sm.indexStart,
  54797. indexCount: sm.indexCount,
  54798. hasMaterial: !!sm.getMaterial(),
  54799. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54800. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54801. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54802. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54803. };
  54804. });
  54805. }
  54806. var geometryId = null;
  54807. if (mesh instanceof BABYLON.Mesh) {
  54808. var geometry = mesh.geometry;
  54809. geometryId = geometry ? geometry.id : null;
  54810. }
  54811. else if (mesh instanceof BABYLON.InstancedMesh) {
  54812. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54813. geometryId = geometry ? geometry.id : null;
  54814. }
  54815. var boundingInfo = mesh.getBoundingInfo();
  54816. return {
  54817. uniqueId: mesh.uniqueId,
  54818. id: mesh.id,
  54819. name: mesh.name,
  54820. geometryId: geometryId,
  54821. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54822. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54823. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54824. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54825. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54826. subMeshes: submeshes,
  54827. checkCollisions: mesh.checkCollisions
  54828. };
  54829. };
  54830. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54831. return {
  54832. id: geometry.id,
  54833. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54834. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54835. indices: new Uint32Array(geometry.getIndices() || []),
  54836. };
  54837. };
  54838. return CollisionCoordinatorWorker;
  54839. }());
  54840. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54841. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54842. function CollisionCoordinatorLegacy() {
  54843. this._scaledPosition = BABYLON.Vector3.Zero();
  54844. this._scaledVelocity = BABYLON.Vector3.Zero();
  54845. this._finalPosition = BABYLON.Vector3.Zero();
  54846. }
  54847. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54848. position.divideToRef(collider._radius, this._scaledPosition);
  54849. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54850. collider.collidedMesh = null;
  54851. collider._retry = 0;
  54852. collider._initialVelocity = this._scaledVelocity;
  54853. collider._initialPosition = this._scaledPosition;
  54854. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54855. this._finalPosition.multiplyInPlace(collider._radius);
  54856. //run the callback
  54857. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54858. };
  54859. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54860. this._scene = scene;
  54861. };
  54862. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54863. //Legacy need no destruction method.
  54864. };
  54865. //No update in legacy mode
  54866. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54867. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54868. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54869. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54870. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54871. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54872. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54873. if (excludedMesh === void 0) { excludedMesh = null; }
  54874. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54875. if (collider._retry >= maximumRetry) {
  54876. finalPosition.copyFrom(position);
  54877. return;
  54878. }
  54879. // Check if this is a mesh else camera or -1
  54880. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54881. collider._initialize(position, velocity, closeDistance);
  54882. // Check all meshes
  54883. for (var index = 0; index < this._scene.meshes.length; index++) {
  54884. var mesh = this._scene.meshes[index];
  54885. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54886. mesh._checkCollision(collider);
  54887. }
  54888. }
  54889. if (!collider.collisionFound) {
  54890. position.addToRef(velocity, finalPosition);
  54891. return;
  54892. }
  54893. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54894. collider._getResponse(position, velocity);
  54895. }
  54896. if (velocity.length() <= closeDistance) {
  54897. finalPosition.copyFrom(position);
  54898. return;
  54899. }
  54900. collider._retry++;
  54901. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54902. };
  54903. return CollisionCoordinatorLegacy;
  54904. }());
  54905. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54906. })(BABYLON || (BABYLON = {}));
  54907. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54908. var BABYLON;
  54909. (function (BABYLON) {
  54910. /**
  54911. * A particle represents one of the element emitted by a particle system.
  54912. * This is mainly define by its coordinates, direction, velocity and age.
  54913. */
  54914. var Particle = /** @class */ (function () {
  54915. /**
  54916. * Creates a new instance Particle
  54917. * @param particleSystem the particle system the particle belongs to
  54918. */
  54919. function Particle(
  54920. /**
  54921. * particleSystem the particle system the particle belongs to.
  54922. */
  54923. particleSystem) {
  54924. this.particleSystem = particleSystem;
  54925. /**
  54926. * The world position of the particle in the scene.
  54927. */
  54928. this.position = BABYLON.Vector3.Zero();
  54929. /**
  54930. * The world direction of the particle in the scene.
  54931. */
  54932. this.direction = BABYLON.Vector3.Zero();
  54933. /**
  54934. * The color of the particle.
  54935. */
  54936. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54937. /**
  54938. * The color change of the particle per step.
  54939. */
  54940. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54941. /**
  54942. * Defines how long will the life of the particle be.
  54943. */
  54944. this.lifeTime = 1.0;
  54945. /**
  54946. * The current age of the particle.
  54947. */
  54948. this.age = 0;
  54949. /**
  54950. * The current size of the particle.
  54951. */
  54952. this.size = 0;
  54953. /**
  54954. * The current scale of the particle.
  54955. */
  54956. this.scale = new BABYLON.Vector2(1, 1);
  54957. /**
  54958. * The current angle of the particle.
  54959. */
  54960. this.angle = 0;
  54961. /**
  54962. * Defines how fast is the angle changing.
  54963. */
  54964. this.angularSpeed = 0;
  54965. /**
  54966. * Defines the cell index used by the particle to be rendered from a sprite.
  54967. */
  54968. this.cellIndex = 0;
  54969. this._currentFrameCounter = 0;
  54970. /** @hidden */
  54971. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54972. /** @hidden */
  54973. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54974. if (!this.particleSystem.isAnimationSheetEnabled) {
  54975. return;
  54976. }
  54977. this.updateCellInfoFromSystem();
  54978. }
  54979. Particle.prototype.updateCellInfoFromSystem = function () {
  54980. this.cellIndex = this.particleSystem.startSpriteCellID;
  54981. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54982. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54983. }
  54984. else {
  54985. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54986. }
  54987. };
  54988. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54989. // (ageOffset / scaledUpdateSpeed) / available cells
  54990. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54991. this._currentFrameCounter += scaledUpdateSpeed;
  54992. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54993. this._currentFrameCounter = 0;
  54994. this.cellIndex++;
  54995. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54996. this.cellIndex = this.particleSystem.endSpriteCellID;
  54997. }
  54998. }
  54999. };
  55000. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55001. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55002. this.cellIndex++;
  55003. this._currentFrameCounter = 0;
  55004. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55005. if (this.particleSystem.spriteCellLoop) {
  55006. this.cellIndex = this.particleSystem.startSpriteCellID;
  55007. }
  55008. else {
  55009. this.cellIndex = this.particleSystem.endSpriteCellID;
  55010. }
  55011. }
  55012. }
  55013. else {
  55014. this._currentFrameCounter++;
  55015. }
  55016. };
  55017. /**
  55018. * Copy the properties of particle to another one.
  55019. * @param other the particle to copy the information to.
  55020. */
  55021. Particle.prototype.copyTo = function (other) {
  55022. other.position.copyFrom(this.position);
  55023. if (this._initialDirection) {
  55024. if (other._initialDirection) {
  55025. other._initialDirection.copyFrom(this._initialDirection);
  55026. }
  55027. else {
  55028. other._initialDirection = this._initialDirection.clone();
  55029. }
  55030. }
  55031. else {
  55032. other._initialDirection = null;
  55033. }
  55034. other.direction.copyFrom(this.direction);
  55035. other.color.copyFrom(this.color);
  55036. other.colorStep.copyFrom(this.colorStep);
  55037. other.lifeTime = this.lifeTime;
  55038. other.age = this.age;
  55039. other.size = this.size;
  55040. other.scale.copyFrom(this.scale);
  55041. other.angle = this.angle;
  55042. other.angularSpeed = this.angularSpeed;
  55043. other.particleSystem = this.particleSystem;
  55044. other.cellIndex = this.cellIndex;
  55045. if (this._currentColorGradient) {
  55046. other._currentColorGradient = this._currentColorGradient;
  55047. other._currentColor1.copyFrom(this._currentColor1);
  55048. other._currentColor2.copyFrom(this._currentColor2);
  55049. }
  55050. };
  55051. return Particle;
  55052. }());
  55053. BABYLON.Particle = Particle;
  55054. })(BABYLON || (BABYLON = {}));
  55055. //# sourceMappingURL=babylon.particle.js.map
  55056. var BABYLON;
  55057. (function (BABYLON) {
  55058. /**
  55059. * This represents a particle system in Babylon.
  55060. * 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.
  55061. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55062. * @example https://doc.babylonjs.com/babylon101/particles
  55063. */
  55064. var ParticleSystem = /** @class */ (function () {
  55065. /**
  55066. * Instantiates a particle system.
  55067. * 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.
  55068. * @param name The name of the particle system
  55069. * @param capacity The max number of particles alive at the same time
  55070. * @param scene The scene the particle system belongs to
  55071. * @param customEffect a custom effect used to change the way particles are rendered by default
  55072. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55073. * @param epsilon Offset used to render the particles
  55074. */
  55075. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55076. if (customEffect === void 0) { customEffect = null; }
  55077. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55078. if (epsilon === void 0) { epsilon = 0.01; }
  55079. var _this = this;
  55080. /**
  55081. * List of animations used by the particle system.
  55082. */
  55083. this.animations = [];
  55084. /**
  55085. * The rendering group used by the Particle system to chose when to render.
  55086. */
  55087. this.renderingGroupId = 0;
  55088. /**
  55089. * The emitter represents the Mesh or position we are attaching the particle system to.
  55090. */
  55091. this.emitter = null;
  55092. /**
  55093. * The maximum number of particles to emit per frame
  55094. */
  55095. this.emitRate = 10;
  55096. /**
  55097. * If you want to launch only a few particles at once, that can be done, as well.
  55098. */
  55099. this.manualEmitCount = -1;
  55100. /**
  55101. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55102. */
  55103. this.updateSpeed = 0.01;
  55104. /**
  55105. * The amount of time the particle system is running (depends of the overall update speed).
  55106. */
  55107. this.targetStopDuration = 0;
  55108. /**
  55109. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55110. */
  55111. this.disposeOnStop = false;
  55112. /**
  55113. * Minimum power of emitting particles.
  55114. */
  55115. this.minEmitPower = 1;
  55116. /**
  55117. * Maximum power of emitting particles.
  55118. */
  55119. this.maxEmitPower = 1;
  55120. /**
  55121. * Minimum life time of emitting particles.
  55122. */
  55123. this.minLifeTime = 1;
  55124. /**
  55125. * Maximum life time of emitting particles.
  55126. */
  55127. this.maxLifeTime = 1;
  55128. /**
  55129. * Minimum Size of emitting particles.
  55130. */
  55131. this.minSize = 1;
  55132. /**
  55133. * Maximum Size of emitting particles.
  55134. */
  55135. this.maxSize = 1;
  55136. /**
  55137. * Minimum scale of emitting particles on X axis.
  55138. */
  55139. this.minScaleX = 1;
  55140. /**
  55141. * Maximum scale of emitting particles on X axis.
  55142. */
  55143. this.maxScaleX = 1;
  55144. /**
  55145. * Minimum scale of emitting particles on Y axis.
  55146. */
  55147. this.minScaleY = 1;
  55148. /**
  55149. * Maximum scale of emitting particles on Y axis.
  55150. */
  55151. this.maxScaleY = 1;
  55152. /**
  55153. * Gets or sets the minimal initial rotation in radians.
  55154. */
  55155. this.minInitialRotation = 0;
  55156. /**
  55157. * Gets or sets the maximal initial rotation in radians.
  55158. */
  55159. this.maxInitialRotation = 0;
  55160. /**
  55161. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55162. */
  55163. this.minAngularSpeed = 0;
  55164. /**
  55165. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55166. */
  55167. this.maxAngularSpeed = 0;
  55168. /**
  55169. * The layer mask we are rendering the particles through.
  55170. */
  55171. this.layerMask = 0x0FFFFFFF;
  55172. /**
  55173. * This can help using your own shader to render the particle system.
  55174. * The according effect will be created
  55175. */
  55176. this.customShader = null;
  55177. /**
  55178. * By default particle system starts as soon as they are created. This prevents the
  55179. * automatic start to happen and let you decide when to start emitting particles.
  55180. */
  55181. this.preventAutoStart = false;
  55182. /**
  55183. * Callback triggered when the particle animation is ending.
  55184. */
  55185. this.onAnimationEnd = null;
  55186. /**
  55187. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55188. */
  55189. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55190. /**
  55191. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55192. * to override the particles.
  55193. */
  55194. this.forceDepthWrite = false;
  55195. /**
  55196. * You can use gravity if you want to give an orientation to your particles.
  55197. */
  55198. this.gravity = BABYLON.Vector3.Zero();
  55199. this._colorGradients = null;
  55200. this._sizeGradients = null;
  55201. /**
  55202. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55203. */
  55204. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55205. /**
  55206. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55207. */
  55208. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55209. /**
  55210. * Color the particle will have at the end of its lifetime
  55211. */
  55212. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55213. /**
  55214. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55215. */
  55216. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55217. /**
  55218. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55219. */
  55220. this.spriteCellLoop = true;
  55221. /**
  55222. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55223. */
  55224. this.spriteCellChangeSpeed = 0;
  55225. /**
  55226. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55227. */
  55228. this.startSpriteCellID = 0;
  55229. /**
  55230. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55231. */
  55232. this.endSpriteCellID = 0;
  55233. /**
  55234. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55235. */
  55236. this.spriteCellWidth = 0;
  55237. /**
  55238. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55239. */
  55240. this.spriteCellHeight = 0;
  55241. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55242. this.preWarmCycles = 0;
  55243. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55244. this.preWarmStepOffset = 1;
  55245. /**
  55246. * An event triggered when the system is disposed
  55247. */
  55248. this.onDisposeObservable = new BABYLON.Observable();
  55249. this._particles = new Array();
  55250. this._stockParticles = new Array();
  55251. this._newPartsExcess = 0;
  55252. this._vertexBuffers = {};
  55253. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55254. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55255. this._scaledDirection = BABYLON.Vector3.Zero();
  55256. this._scaledGravity = BABYLON.Vector3.Zero();
  55257. this._currentRenderId = -1;
  55258. this._useInstancing = false;
  55259. this._started = false;
  55260. this._stopped = false;
  55261. this._actualFrame = 0;
  55262. this._isBillboardBased = true;
  55263. // start of sub system methods
  55264. /**
  55265. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55266. * Its lifetime will start back at 0.
  55267. */
  55268. this.recycleParticle = function (particle) {
  55269. var lastParticle = _this._particles.pop();
  55270. if (lastParticle !== particle) {
  55271. lastParticle.copyTo(particle);
  55272. }
  55273. _this._stockParticles.push(lastParticle);
  55274. };
  55275. this._createParticle = function () {
  55276. var particle;
  55277. if (_this._stockParticles.length !== 0) {
  55278. particle = _this._stockParticles.pop();
  55279. particle.age = 0;
  55280. particle._currentColorGradient = null;
  55281. particle.cellIndex = _this.startSpriteCellID;
  55282. }
  55283. else {
  55284. particle = new BABYLON.Particle(_this);
  55285. }
  55286. return particle;
  55287. };
  55288. this._emitFromParticle = function (particle) {
  55289. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55290. return;
  55291. }
  55292. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55293. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55294. subSystem._rootParticleSystem = _this;
  55295. _this.activeSubSystems.push(subSystem);
  55296. subSystem.start();
  55297. };
  55298. this.id = name;
  55299. this.name = name;
  55300. this._capacity = capacity;
  55301. this._epsilon = epsilon;
  55302. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55303. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55304. this._customEffect = customEffect;
  55305. scene.particleSystems.push(this);
  55306. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55307. this._createIndexBuffer();
  55308. this._createVertexBuffers();
  55309. // Default emitter type
  55310. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55311. this.updateFunction = function (particles) {
  55312. for (var index = 0; index < particles.length; index++) {
  55313. var particle = particles[index];
  55314. particle.age += _this._scaledUpdateSpeed;
  55315. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55316. _this._emitFromParticle(particle);
  55317. _this.recycleParticle(particle);
  55318. index--;
  55319. continue;
  55320. }
  55321. else {
  55322. var ratio = particle.age / particle.lifeTime;
  55323. // Color
  55324. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55325. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55326. if (currentGradient !== particle._currentColorGradient) {
  55327. particle._currentColor1.copyFrom(particle._currentColor2);
  55328. nextGradient.getColorToRef(particle._currentColor2);
  55329. particle._currentColorGradient = currentGradient;
  55330. }
  55331. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55332. });
  55333. }
  55334. else {
  55335. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55336. particle.color.addInPlace(_this._scaledColorStep);
  55337. if (particle.color.a < 0) {
  55338. particle.color.a = 0;
  55339. }
  55340. }
  55341. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55342. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55343. particle.position.addInPlace(_this._scaledDirection);
  55344. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55345. particle.direction.addInPlace(_this._scaledGravity);
  55346. // Gradient
  55347. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55348. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55349. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55350. });
  55351. }
  55352. if (_this._isAnimationSheetEnabled) {
  55353. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55354. }
  55355. }
  55356. }
  55357. };
  55358. }
  55359. /**
  55360. * Gets the current list of color gradients.
  55361. * You must use addColorGradient and removeColorGradient to udpate this list
  55362. * @returns the list of color gradients
  55363. */
  55364. ParticleSystem.prototype.getColorGradients = function () {
  55365. return this._colorGradients;
  55366. };
  55367. /**
  55368. * Gets the current list of size gradients.
  55369. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55370. * @returns the list of size gradients
  55371. */
  55372. ParticleSystem.prototype.getSizeGradients = function () {
  55373. return this._sizeGradients;
  55374. };
  55375. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55376. /**
  55377. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55378. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55379. */
  55380. get: function () {
  55381. if (this.particleEmitterType.direction1) {
  55382. return this.particleEmitterType.direction1;
  55383. }
  55384. return BABYLON.Vector3.Zero();
  55385. },
  55386. set: function (value) {
  55387. if (this.particleEmitterType.direction1) {
  55388. this.particleEmitterType.direction1 = value;
  55389. }
  55390. },
  55391. enumerable: true,
  55392. configurable: true
  55393. });
  55394. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55395. /**
  55396. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55397. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55398. */
  55399. get: function () {
  55400. if (this.particleEmitterType.direction2) {
  55401. return this.particleEmitterType.direction2;
  55402. }
  55403. return BABYLON.Vector3.Zero();
  55404. },
  55405. set: function (value) {
  55406. if (this.particleEmitterType.direction2) {
  55407. this.particleEmitterType.direction2 = value;
  55408. }
  55409. },
  55410. enumerable: true,
  55411. configurable: true
  55412. });
  55413. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55414. /**
  55415. * 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.
  55416. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55417. */
  55418. get: function () {
  55419. if (this.particleEmitterType.minEmitBox) {
  55420. return this.particleEmitterType.minEmitBox;
  55421. }
  55422. return BABYLON.Vector3.Zero();
  55423. },
  55424. set: function (value) {
  55425. if (this.particleEmitterType.minEmitBox) {
  55426. this.particleEmitterType.minEmitBox = value;
  55427. }
  55428. },
  55429. enumerable: true,
  55430. configurable: true
  55431. });
  55432. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55433. /**
  55434. * 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.
  55435. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55436. */
  55437. get: function () {
  55438. if (this.particleEmitterType.maxEmitBox) {
  55439. return this.particleEmitterType.maxEmitBox;
  55440. }
  55441. return BABYLON.Vector3.Zero();
  55442. },
  55443. set: function (value) {
  55444. if (this.particleEmitterType.maxEmitBox) {
  55445. this.particleEmitterType.maxEmitBox = value;
  55446. }
  55447. },
  55448. enumerable: true,
  55449. configurable: true
  55450. });
  55451. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55452. /**
  55453. * Sets a callback that will be triggered when the system is disposed
  55454. */
  55455. set: function (callback) {
  55456. if (this._onDisposeObserver) {
  55457. this.onDisposeObservable.remove(this._onDisposeObserver);
  55458. }
  55459. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55460. },
  55461. enumerable: true,
  55462. configurable: true
  55463. });
  55464. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55465. /**
  55466. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55467. */
  55468. get: function () {
  55469. return this._isAnimationSheetEnabled;
  55470. },
  55471. enumerable: true,
  55472. configurable: true
  55473. });
  55474. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55475. /**
  55476. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55477. */
  55478. get: function () {
  55479. return this._isBillboardBased;
  55480. },
  55481. set: function (value) {
  55482. if (this._isBillboardBased === value) {
  55483. return;
  55484. }
  55485. this._isBillboardBased = value;
  55486. this._resetEffect();
  55487. },
  55488. enumerable: true,
  55489. configurable: true
  55490. });
  55491. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55492. //end of Sub-emitter
  55493. /**
  55494. * Gets the current list of active particles
  55495. */
  55496. get: function () {
  55497. return this._particles;
  55498. },
  55499. enumerable: true,
  55500. configurable: true
  55501. });
  55502. /**
  55503. * Returns the string "ParticleSystem"
  55504. * @returns a string containing the class name
  55505. */
  55506. ParticleSystem.prototype.getClassName = function () {
  55507. return "ParticleSystem";
  55508. };
  55509. /**
  55510. * Adds a new size gradient
  55511. * @param gradient defines the gradient to use (between 0 and 1)
  55512. * @param factor defines the size factor to affect to the specified gradient
  55513. */
  55514. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55515. if (!this._sizeGradients) {
  55516. this._sizeGradients = [];
  55517. }
  55518. var sizeGradient = new BABYLON.FactorGradient();
  55519. sizeGradient.gradient = gradient;
  55520. sizeGradient.factor = factor;
  55521. this._sizeGradients.push(sizeGradient);
  55522. this._sizeGradients.sort(function (a, b) {
  55523. if (a.gradient < b.gradient) {
  55524. return -1;
  55525. }
  55526. else if (a.gradient > b.gradient) {
  55527. return 1;
  55528. }
  55529. return 0;
  55530. });
  55531. return this;
  55532. };
  55533. /**
  55534. * Remove a specific size gradient
  55535. * @param gradient defines the gradient to remove
  55536. */
  55537. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55538. if (!this._sizeGradients) {
  55539. return this;
  55540. }
  55541. var index = 0;
  55542. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55543. var sizeGradient = _a[_i];
  55544. if (sizeGradient.gradient === gradient) {
  55545. this._sizeGradients.splice(index, 1);
  55546. break;
  55547. }
  55548. index++;
  55549. }
  55550. return this;
  55551. };
  55552. /**
  55553. * Adds a new color gradient
  55554. * @param gradient defines the gradient to use (between 0 and 1)
  55555. * @param color defines the color to affect to the specified gradient
  55556. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55557. */
  55558. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55559. if (!this._colorGradients) {
  55560. this._colorGradients = [];
  55561. }
  55562. var colorGradient = new BABYLON.ColorGradient();
  55563. colorGradient.gradient = gradient;
  55564. colorGradient.color1 = color;
  55565. colorGradient.color2 = color2;
  55566. this._colorGradients.push(colorGradient);
  55567. this._colorGradients.sort(function (a, b) {
  55568. if (a.gradient < b.gradient) {
  55569. return -1;
  55570. }
  55571. else if (a.gradient > b.gradient) {
  55572. return 1;
  55573. }
  55574. return 0;
  55575. });
  55576. return this;
  55577. };
  55578. /**
  55579. * Remove a specific color gradient
  55580. * @param gradient defines the gradient to remove
  55581. */
  55582. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55583. if (!this._colorGradients) {
  55584. return this;
  55585. }
  55586. var index = 0;
  55587. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55588. var colorGradient = _a[_i];
  55589. if (colorGradient.gradient === gradient) {
  55590. this._colorGradients.splice(index, 1);
  55591. break;
  55592. }
  55593. index++;
  55594. }
  55595. return this;
  55596. };
  55597. ParticleSystem.prototype._resetEffect = function () {
  55598. if (this._vertexBuffer) {
  55599. this._vertexBuffer.dispose();
  55600. this._vertexBuffer = null;
  55601. }
  55602. if (this._spriteBuffer) {
  55603. this._spriteBuffer.dispose();
  55604. this._spriteBuffer = null;
  55605. }
  55606. this._createVertexBuffers();
  55607. };
  55608. ParticleSystem.prototype._createVertexBuffers = function () {
  55609. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55610. if (this._isAnimationSheetEnabled) {
  55611. this._vertexBufferSize += 1;
  55612. }
  55613. if (!this._isBillboardBased) {
  55614. this._vertexBufferSize += 3;
  55615. }
  55616. var engine = this._scene.getEngine();
  55617. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55618. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55619. var dataOffset = 0;
  55620. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55621. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55622. dataOffset += 3;
  55623. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55624. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55625. dataOffset += 4;
  55626. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55627. this._vertexBuffers["angle"] = options;
  55628. dataOffset += 1;
  55629. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55630. this._vertexBuffers["size"] = size;
  55631. dataOffset += 2;
  55632. if (this._isAnimationSheetEnabled) {
  55633. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55634. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55635. dataOffset += 1;
  55636. }
  55637. if (!this._isBillboardBased) {
  55638. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55639. this._vertexBuffers["direction"] = directionBuffer;
  55640. dataOffset += 3;
  55641. }
  55642. var offsets;
  55643. if (this._useInstancing) {
  55644. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55645. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55646. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55647. }
  55648. else {
  55649. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55650. dataOffset += 2;
  55651. }
  55652. this._vertexBuffers["offset"] = offsets;
  55653. };
  55654. ParticleSystem.prototype._createIndexBuffer = function () {
  55655. if (this._useInstancing) {
  55656. return;
  55657. }
  55658. var indices = [];
  55659. var index = 0;
  55660. for (var count = 0; count < this._capacity; count++) {
  55661. indices.push(index);
  55662. indices.push(index + 1);
  55663. indices.push(index + 2);
  55664. indices.push(index);
  55665. indices.push(index + 2);
  55666. indices.push(index + 3);
  55667. index += 4;
  55668. }
  55669. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55670. };
  55671. /**
  55672. * Gets the maximum number of particles active at the same time.
  55673. * @returns The max number of active particles.
  55674. */
  55675. ParticleSystem.prototype.getCapacity = function () {
  55676. return this._capacity;
  55677. };
  55678. /**
  55679. * Gets Wether there are still active particles in the system.
  55680. * @returns True if it is alive, otherwise false.
  55681. */
  55682. ParticleSystem.prototype.isAlive = function () {
  55683. return this._alive;
  55684. };
  55685. /**
  55686. * Gets Wether the system has been started.
  55687. * @returns True if it has been started, otherwise false.
  55688. */
  55689. ParticleSystem.prototype.isStarted = function () {
  55690. return this._started;
  55691. };
  55692. /**
  55693. * Starts the particle system and begins to emit.
  55694. */
  55695. ParticleSystem.prototype.start = function () {
  55696. this._started = true;
  55697. this._stopped = false;
  55698. this._actualFrame = 0;
  55699. if (this.subEmitters && this.subEmitters.length != 0) {
  55700. this.activeSubSystems = new Array();
  55701. }
  55702. if (this.preWarmCycles) {
  55703. for (var index = 0; index < this.preWarmCycles; index++) {
  55704. this.animate(true);
  55705. }
  55706. }
  55707. };
  55708. /**
  55709. * Stops the particle system.
  55710. * @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.
  55711. */
  55712. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55713. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55714. this._stopped = true;
  55715. if (stopSubEmitters) {
  55716. this._stopSubEmitters();
  55717. }
  55718. };
  55719. // animation sheet
  55720. /**
  55721. * Remove all active particles
  55722. */
  55723. ParticleSystem.prototype.reset = function () {
  55724. this._stockParticles = [];
  55725. this._particles = [];
  55726. };
  55727. /**
  55728. * @hidden (for internal use only)
  55729. */
  55730. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55731. var offset = index * this._vertexBufferSize;
  55732. this._vertexData[offset++] = particle.position.x;
  55733. this._vertexData[offset++] = particle.position.y;
  55734. this._vertexData[offset++] = particle.position.z;
  55735. this._vertexData[offset++] = particle.color.r;
  55736. this._vertexData[offset++] = particle.color.g;
  55737. this._vertexData[offset++] = particle.color.b;
  55738. this._vertexData[offset++] = particle.color.a;
  55739. this._vertexData[offset++] = particle.angle;
  55740. this._vertexData[offset++] = particle.scale.x * particle.size;
  55741. this._vertexData[offset++] = particle.scale.y * particle.size;
  55742. if (this._isAnimationSheetEnabled) {
  55743. this._vertexData[offset++] = particle.cellIndex;
  55744. }
  55745. if (!this._isBillboardBased) {
  55746. if (particle._initialDirection) {
  55747. this._vertexData[offset++] = particle._initialDirection.x;
  55748. this._vertexData[offset++] = particle._initialDirection.y;
  55749. this._vertexData[offset++] = particle._initialDirection.z;
  55750. }
  55751. else {
  55752. this._vertexData[offset++] = particle.direction.x;
  55753. this._vertexData[offset++] = particle.direction.y;
  55754. this._vertexData[offset++] = particle.direction.z;
  55755. }
  55756. }
  55757. if (!this._useInstancing) {
  55758. if (this._isAnimationSheetEnabled) {
  55759. if (offsetX === 0)
  55760. offsetX = this._epsilon;
  55761. else if (offsetX === 1)
  55762. offsetX = 1 - this._epsilon;
  55763. if (offsetY === 0)
  55764. offsetY = this._epsilon;
  55765. else if (offsetY === 1)
  55766. offsetY = 1 - this._epsilon;
  55767. }
  55768. this._vertexData[offset++] = offsetX;
  55769. this._vertexData[offset++] = offsetY;
  55770. }
  55771. };
  55772. ParticleSystem.prototype._stopSubEmitters = function () {
  55773. if (!this.activeSubSystems) {
  55774. return;
  55775. }
  55776. this.activeSubSystems.forEach(function (subSystem) {
  55777. subSystem.stop(true);
  55778. });
  55779. this.activeSubSystems = new Array();
  55780. };
  55781. ParticleSystem.prototype._removeFromRoot = function () {
  55782. if (!this._rootParticleSystem) {
  55783. return;
  55784. }
  55785. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55786. if (index !== -1) {
  55787. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55788. }
  55789. };
  55790. // end of sub system methods
  55791. ParticleSystem.prototype._update = function (newParticles) {
  55792. // Update current
  55793. this._alive = this._particles.length > 0;
  55794. this.updateFunction(this._particles);
  55795. // Add new ones
  55796. var worldMatrix;
  55797. if (this.emitter.position) {
  55798. var emitterMesh = this.emitter;
  55799. worldMatrix = emitterMesh.getWorldMatrix();
  55800. }
  55801. else {
  55802. var emitterPosition = this.emitter;
  55803. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55804. }
  55805. var particle;
  55806. for (var index = 0; index < newParticles; index++) {
  55807. if (this._particles.length === this._capacity) {
  55808. break;
  55809. }
  55810. particle = this._createParticle();
  55811. this._particles.push(particle);
  55812. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55813. if (this.startPositionFunction) {
  55814. this.startPositionFunction(worldMatrix, particle.position, particle);
  55815. }
  55816. else {
  55817. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55818. }
  55819. if (this.startDirectionFunction) {
  55820. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55821. }
  55822. else {
  55823. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55824. }
  55825. if (emitPower === 0) {
  55826. if (!particle._initialDirection) {
  55827. particle._initialDirection = particle.direction.clone();
  55828. }
  55829. else {
  55830. particle._initialDirection.copyFrom(particle.direction);
  55831. }
  55832. }
  55833. else {
  55834. particle._initialDirection = null;
  55835. }
  55836. particle.direction.scaleInPlace(emitPower);
  55837. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55838. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55839. particle._initialSize = particle.size;
  55840. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55841. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55842. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55843. if (!this._colorGradients || this._colorGradients.length === 0) {
  55844. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55845. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55846. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55847. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55848. }
  55849. else {
  55850. particle._currentColorGradient = this._colorGradients[0];
  55851. particle._currentColorGradient.getColorToRef(particle.color);
  55852. particle._currentColor1.copyFrom(particle.color);
  55853. if (this._colorGradients.length > 1) {
  55854. this._colorGradients[1].getColorToRef(particle._currentColor2);
  55855. }
  55856. else {
  55857. particle._currentColor2.copyFrom(particle.color);
  55858. }
  55859. }
  55860. }
  55861. };
  55862. /** @hidden */
  55863. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55864. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55865. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55866. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55867. if (isAnimationSheetEnabled) {
  55868. attributeNamesOrOptions.push("cellIndex");
  55869. }
  55870. if (!isBillboardBased) {
  55871. attributeNamesOrOptions.push("direction");
  55872. }
  55873. return attributeNamesOrOptions;
  55874. };
  55875. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55876. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55877. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55878. if (isAnimationSheetEnabled) {
  55879. effectCreationOption.push("particlesInfos");
  55880. }
  55881. return effectCreationOption;
  55882. };
  55883. ParticleSystem.prototype._getEffect = function () {
  55884. if (this._customEffect) {
  55885. return this._customEffect;
  55886. }
  55887. ;
  55888. var defines = [];
  55889. if (this._scene.clipPlane) {
  55890. defines.push("#define CLIPPLANE");
  55891. }
  55892. if (this._isAnimationSheetEnabled) {
  55893. defines.push("#define ANIMATESHEET");
  55894. }
  55895. if (this._isBillboardBased) {
  55896. defines.push("#define BILLBOARD");
  55897. }
  55898. // Effect
  55899. var join = defines.join("\n");
  55900. if (this._cachedDefines !== join) {
  55901. this._cachedDefines = join;
  55902. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55903. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55904. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55905. }
  55906. return this._effect;
  55907. };
  55908. /**
  55909. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55910. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55911. */
  55912. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55913. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55914. if (!this._started)
  55915. return;
  55916. if (!preWarmOnly) {
  55917. var effect = this._getEffect();
  55918. // Check
  55919. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55920. return;
  55921. if (this._currentRenderId === this._scene.getRenderId()) {
  55922. return;
  55923. }
  55924. this._currentRenderId = this._scene.getRenderId();
  55925. }
  55926. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55927. // determine the number of particles we need to create
  55928. var newParticles;
  55929. if (this.manualEmitCount > -1) {
  55930. newParticles = this.manualEmitCount;
  55931. this._newPartsExcess = 0;
  55932. this.manualEmitCount = 0;
  55933. }
  55934. else {
  55935. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55936. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55937. }
  55938. if (this._newPartsExcess > 1.0) {
  55939. newParticles += this._newPartsExcess >> 0;
  55940. this._newPartsExcess -= this._newPartsExcess >> 0;
  55941. }
  55942. this._alive = false;
  55943. if (!this._stopped) {
  55944. this._actualFrame += this._scaledUpdateSpeed;
  55945. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55946. this.stop();
  55947. }
  55948. else {
  55949. newParticles = 0;
  55950. }
  55951. this._update(newParticles);
  55952. // Stopped?
  55953. if (this._stopped) {
  55954. if (!this._alive) {
  55955. this._started = false;
  55956. if (this.onAnimationEnd) {
  55957. this.onAnimationEnd();
  55958. }
  55959. if (this.disposeOnStop) {
  55960. this._scene._toBeDisposed.push(this);
  55961. }
  55962. }
  55963. }
  55964. if (!preWarmOnly) {
  55965. // Update VBO
  55966. var offset = 0;
  55967. for (var index = 0; index < this._particles.length; index++) {
  55968. var particle = this._particles[index];
  55969. this._appendParticleVertices(offset, particle);
  55970. offset += this._useInstancing ? 1 : 4;
  55971. }
  55972. if (this._vertexBuffer) {
  55973. this._vertexBuffer.update(this._vertexData);
  55974. }
  55975. }
  55976. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55977. this.stop();
  55978. }
  55979. };
  55980. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55981. this._appendParticleVertex(offset++, particle, 0, 0);
  55982. if (!this._useInstancing) {
  55983. this._appendParticleVertex(offset++, particle, 1, 0);
  55984. this._appendParticleVertex(offset++, particle, 1, 1);
  55985. this._appendParticleVertex(offset++, particle, 0, 1);
  55986. }
  55987. };
  55988. /**
  55989. * Rebuilds the particle system.
  55990. */
  55991. ParticleSystem.prototype.rebuild = function () {
  55992. this._createIndexBuffer();
  55993. if (this._vertexBuffer) {
  55994. this._vertexBuffer._rebuild();
  55995. }
  55996. };
  55997. /**
  55998. * Is this system ready to be used/rendered
  55999. * @return true if the system is ready
  56000. */
  56001. ParticleSystem.prototype.isReady = function () {
  56002. var effect = this._getEffect();
  56003. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56004. return false;
  56005. }
  56006. return true;
  56007. };
  56008. /**
  56009. * Renders the particle system in its current state.
  56010. * @returns the current number of particles
  56011. */
  56012. ParticleSystem.prototype.render = function () {
  56013. var effect = this._getEffect();
  56014. // Check
  56015. if (!this.isReady() || !this._particles.length) {
  56016. return 0;
  56017. }
  56018. var engine = this._scene.getEngine();
  56019. // Render
  56020. engine.enableEffect(effect);
  56021. engine.setState(false);
  56022. var viewMatrix = this._scene.getViewMatrix();
  56023. effect.setTexture("diffuseSampler", this.particleTexture);
  56024. effect.setMatrix("view", viewMatrix);
  56025. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56026. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56027. var baseSize = this.particleTexture.getBaseSize();
  56028. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56029. }
  56030. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56031. if (this._scene.clipPlane) {
  56032. var clipPlane = this._scene.clipPlane;
  56033. var invView = viewMatrix.clone();
  56034. invView.invert();
  56035. effect.setMatrix("invView", invView);
  56036. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56037. }
  56038. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56039. // Draw order
  56040. switch (this.blendMode) {
  56041. case ParticleSystem.BLENDMODE_ADD:
  56042. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56043. break;
  56044. case ParticleSystem.BLENDMODE_ONEONE:
  56045. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56046. break;
  56047. case ParticleSystem.BLENDMODE_STANDARD:
  56048. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56049. break;
  56050. }
  56051. if (this.forceDepthWrite) {
  56052. engine.setDepthWrite(true);
  56053. }
  56054. if (this._useInstancing) {
  56055. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56056. engine.unbindInstanceAttributes();
  56057. }
  56058. else {
  56059. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56060. }
  56061. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56062. return this._particles.length;
  56063. };
  56064. /**
  56065. * Disposes the particle system and free the associated resources
  56066. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56067. */
  56068. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56069. if (disposeTexture === void 0) { disposeTexture = true; }
  56070. if (this._vertexBuffer) {
  56071. this._vertexBuffer.dispose();
  56072. this._vertexBuffer = null;
  56073. }
  56074. if (this._spriteBuffer) {
  56075. this._spriteBuffer.dispose();
  56076. this._spriteBuffer = null;
  56077. }
  56078. if (this._indexBuffer) {
  56079. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56080. this._indexBuffer = null;
  56081. }
  56082. if (disposeTexture && this.particleTexture) {
  56083. this.particleTexture.dispose();
  56084. this.particleTexture = null;
  56085. }
  56086. this._removeFromRoot();
  56087. // Remove from scene
  56088. var index = this._scene.particleSystems.indexOf(this);
  56089. if (index > -1) {
  56090. this._scene.particleSystems.splice(index, 1);
  56091. }
  56092. // Callback
  56093. this.onDisposeObservable.notifyObservers(this);
  56094. this.onDisposeObservable.clear();
  56095. };
  56096. /**
  56097. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56098. * @param radius The radius of the sphere to emit from
  56099. * @returns the emitter
  56100. */
  56101. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56102. if (radius === void 0) { radius = 1; }
  56103. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56104. this.particleEmitterType = particleEmitter;
  56105. return particleEmitter;
  56106. };
  56107. /**
  56108. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56109. * @param radius The radius of the sphere to emit from
  56110. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56111. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56112. * @returns the emitter
  56113. */
  56114. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56115. if (radius === void 0) { radius = 1; }
  56116. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56117. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56118. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56119. this.particleEmitterType = particleEmitter;
  56120. return particleEmitter;
  56121. };
  56122. /**
  56123. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56124. * @param radius The radius of the cone to emit from
  56125. * @param angle The base angle of the cone
  56126. * @returns the emitter
  56127. */
  56128. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56129. if (radius === void 0) { radius = 1; }
  56130. if (angle === void 0) { angle = Math.PI / 4; }
  56131. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56132. this.particleEmitterType = particleEmitter;
  56133. return particleEmitter;
  56134. };
  56135. // 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.
  56136. /**
  56137. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56138. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56139. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56140. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56141. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56142. * @returns the emitter
  56143. */
  56144. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56145. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56146. this.particleEmitterType = particleEmitter;
  56147. this.direction1 = direction1;
  56148. this.direction2 = direction2;
  56149. this.minEmitBox = minEmitBox;
  56150. this.maxEmitBox = maxEmitBox;
  56151. return particleEmitter;
  56152. };
  56153. // Clone
  56154. /**
  56155. * Clones the particle system.
  56156. * @param name The name of the cloned object
  56157. * @param newEmitter The new emitter to use
  56158. * @returns the cloned particle system
  56159. */
  56160. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56161. var custom = null;
  56162. var program = null;
  56163. if (this.customShader != null) {
  56164. program = this.customShader;
  56165. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56166. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56167. }
  56168. else if (this._customEffect) {
  56169. custom = this._customEffect;
  56170. }
  56171. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56172. result.customShader = program;
  56173. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56174. if (newEmitter === undefined) {
  56175. newEmitter = this.emitter;
  56176. }
  56177. result.emitter = newEmitter;
  56178. if (this.particleTexture) {
  56179. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56180. }
  56181. if (!this.preventAutoStart) {
  56182. result.start();
  56183. }
  56184. return result;
  56185. };
  56186. /**
  56187. * Serializes the particle system to a JSON object.
  56188. * @returns the JSON object
  56189. */
  56190. ParticleSystem.prototype.serialize = function () {
  56191. var serializationObject = {};
  56192. ParticleSystem._Serialize(serializationObject, this);
  56193. serializationObject.textureMask = this.textureMask.asArray();
  56194. serializationObject.customShader = this.customShader;
  56195. serializationObject.preventAutoStart = this.preventAutoStart;
  56196. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56197. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56198. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56199. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56200. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56201. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56202. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56203. return serializationObject;
  56204. };
  56205. /** @hidden */
  56206. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56207. serializationObject.name = particleSystem.name;
  56208. serializationObject.id = particleSystem.id;
  56209. serializationObject.capacity = particleSystem.getCapacity();
  56210. // Emitter
  56211. if (particleSystem.emitter.position) {
  56212. var emitterMesh = particleSystem.emitter;
  56213. serializationObject.emitterId = emitterMesh.id;
  56214. }
  56215. else {
  56216. var emitterPosition = particleSystem.emitter;
  56217. serializationObject.emitter = emitterPosition.asArray();
  56218. }
  56219. // Emitter
  56220. if (particleSystem.particleEmitterType) {
  56221. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56222. }
  56223. if (particleSystem.particleTexture) {
  56224. serializationObject.textureName = particleSystem.particleTexture.name;
  56225. }
  56226. // Animations
  56227. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56228. // Particle system
  56229. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56230. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56231. serializationObject.minSize = particleSystem.minSize;
  56232. serializationObject.maxSize = particleSystem.maxSize;
  56233. serializationObject.minScaleX = particleSystem.minScaleX;
  56234. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56235. serializationObject.minScaleY = particleSystem.minScaleY;
  56236. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56237. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56238. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56239. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56240. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56241. serializationObject.emitRate = particleSystem.emitRate;
  56242. serializationObject.gravity = particleSystem.gravity.asArray();
  56243. serializationObject.color1 = particleSystem.color1.asArray();
  56244. serializationObject.color2 = particleSystem.color2.asArray();
  56245. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56246. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56247. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56248. serializationObject.blendMode = particleSystem.blendMode;
  56249. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56250. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56251. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56252. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56253. var colorGradients = particleSystem.getColorGradients();
  56254. if (colorGradients) {
  56255. serializationObject.colorGradients = [];
  56256. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56257. var colorGradient = colorGradients_1[_i];
  56258. var serializedGradient = {
  56259. gradient: colorGradient.gradient,
  56260. color1: colorGradient.color1.asArray()
  56261. };
  56262. if (colorGradient.color2) {
  56263. serializedGradient.color2 = colorGradient.color2.asArray();
  56264. }
  56265. serializationObject.colorGradients.push(serializedGradient);
  56266. }
  56267. }
  56268. var sizeGradients = particleSystem.getSizeGradients();
  56269. if (sizeGradients) {
  56270. serializationObject.sizeGradients = [];
  56271. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56272. var sizeGradient = sizeGradients_1[_a];
  56273. serializationObject.sizeGradients.push({
  56274. gradient: sizeGradient.gradient,
  56275. factor: sizeGradient.factor
  56276. });
  56277. }
  56278. }
  56279. };
  56280. /** @hidden */
  56281. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56282. // Texture
  56283. if (parsedParticleSystem.textureName) {
  56284. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56285. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56286. }
  56287. // Emitter
  56288. if (parsedParticleSystem.emitterId) {
  56289. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56290. }
  56291. else {
  56292. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56293. }
  56294. // Animations
  56295. if (parsedParticleSystem.animations) {
  56296. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56297. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56298. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56299. }
  56300. }
  56301. if (parsedParticleSystem.autoAnimate) {
  56302. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56303. }
  56304. // Particle system
  56305. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56306. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56307. particleSystem.minSize = parsedParticleSystem.minSize;
  56308. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56309. if (parsedParticleSystem.minScaleX) {
  56310. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56311. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56312. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56313. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56314. }
  56315. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56316. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56317. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56318. }
  56319. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56320. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56321. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56322. }
  56323. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56324. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56325. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56326. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56327. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56328. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56329. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56330. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56331. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56332. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56333. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56334. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56335. if (parsedParticleSystem.colorGradients) {
  56336. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56337. var colorGradient = _a[_i];
  56338. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56339. }
  56340. }
  56341. if (parsedParticleSystem.sizeGradients) {
  56342. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56343. var sizeGradient = _c[_b];
  56344. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56345. }
  56346. }
  56347. // Emitter
  56348. var emitterType;
  56349. if (parsedParticleSystem.particleEmitterType) {
  56350. switch (parsedParticleSystem.particleEmitterType.type) {
  56351. case "SphereEmitter":
  56352. emitterType = new BABYLON.SphereParticleEmitter();
  56353. break;
  56354. case "SphereDirectedParticleEmitter":
  56355. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56356. break;
  56357. case "ConeEmitter":
  56358. emitterType = new BABYLON.ConeParticleEmitter();
  56359. break;
  56360. case "BoxEmitter":
  56361. default:
  56362. emitterType = new BABYLON.BoxParticleEmitter();
  56363. break;
  56364. }
  56365. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56366. }
  56367. else {
  56368. emitterType = new BABYLON.BoxParticleEmitter();
  56369. emitterType.parse(parsedParticleSystem);
  56370. }
  56371. particleSystem.particleEmitterType = emitterType;
  56372. };
  56373. /**
  56374. * Parses a JSON object to create a particle system.
  56375. * @param parsedParticleSystem The JSON object to parse
  56376. * @param scene The scene to create the particle system in
  56377. * @param rootUrl The root url to use to load external dependencies like texture
  56378. * @returns the Parsed particle system
  56379. */
  56380. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56381. var name = parsedParticleSystem.name;
  56382. var custom = null;
  56383. var program = null;
  56384. if (parsedParticleSystem.customShader) {
  56385. program = parsedParticleSystem.customShader;
  56386. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56387. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56388. }
  56389. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56390. particleSystem.customShader = program;
  56391. if (parsedParticleSystem.id) {
  56392. particleSystem.id = parsedParticleSystem.id;
  56393. }
  56394. // Auto start
  56395. if (parsedParticleSystem.preventAutoStart) {
  56396. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56397. }
  56398. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56399. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56400. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56401. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56402. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56403. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56404. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56405. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56406. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56407. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56408. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56409. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56410. if (!particleSystem.preventAutoStart) {
  56411. particleSystem.start();
  56412. }
  56413. return particleSystem;
  56414. };
  56415. /**
  56416. * Source color is added to the destination color without alpha affecting the result.
  56417. */
  56418. ParticleSystem.BLENDMODE_ONEONE = 0;
  56419. /**
  56420. * Blend current color and particle color using particle’s alpha.
  56421. */
  56422. ParticleSystem.BLENDMODE_STANDARD = 1;
  56423. /**
  56424. * Add current color and particle color multiplied by particle’s alpha.
  56425. */
  56426. ParticleSystem.BLENDMODE_ADD = 2;
  56427. return ParticleSystem;
  56428. }());
  56429. BABYLON.ParticleSystem = ParticleSystem;
  56430. })(BABYLON || (BABYLON = {}));
  56431. //# sourceMappingURL=babylon.particleSystem.js.map
  56432. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56433. var BABYLON;
  56434. (function (BABYLON) {
  56435. /**
  56436. * Particle emitter emitting particles from the inside of a box.
  56437. * It emits the particles randomly between 2 given directions.
  56438. */
  56439. var BoxParticleEmitter = /** @class */ (function () {
  56440. /**
  56441. * Creates a new instance BoxParticleEmitter
  56442. */
  56443. function BoxParticleEmitter() {
  56444. /**
  56445. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56446. */
  56447. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56448. /**
  56449. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56450. */
  56451. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56452. /**
  56453. * 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.
  56454. */
  56455. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56456. /**
  56457. * 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.
  56458. */
  56459. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56460. }
  56461. /**
  56462. * Called by the particle System when the direction is computed for the created particle.
  56463. * @param worldMatrix is the world matrix of the particle system
  56464. * @param directionToUpdate is the direction vector to update with the result
  56465. * @param particle is the particle we are computed the direction for
  56466. */
  56467. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56468. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56469. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56470. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56471. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56472. };
  56473. /**
  56474. * Called by the particle System when the position is computed for the created particle.
  56475. * @param worldMatrix is the world matrix of the particle system
  56476. * @param positionToUpdate is the position vector to update with the result
  56477. * @param particle is the particle we are computed the position for
  56478. */
  56479. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56480. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56481. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56482. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56483. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56484. };
  56485. /**
  56486. * Clones the current emitter and returns a copy of it
  56487. * @returns the new emitter
  56488. */
  56489. BoxParticleEmitter.prototype.clone = function () {
  56490. var newOne = new BoxParticleEmitter();
  56491. BABYLON.Tools.DeepCopy(this, newOne);
  56492. return newOne;
  56493. };
  56494. /**
  56495. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56496. * @param effect defines the update shader
  56497. */
  56498. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56499. effect.setVector3("direction1", this.direction1);
  56500. effect.setVector3("direction2", this.direction2);
  56501. effect.setVector3("minEmitBox", this.minEmitBox);
  56502. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56503. };
  56504. /**
  56505. * Returns a string to use to update the GPU particles update shader
  56506. * @returns a string containng the defines string
  56507. */
  56508. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56509. return "#define BOXEMITTER";
  56510. };
  56511. /**
  56512. * Returns the string "BoxEmitter"
  56513. * @returns a string containing the class name
  56514. */
  56515. BoxParticleEmitter.prototype.getClassName = function () {
  56516. return "BoxEmitter";
  56517. };
  56518. /**
  56519. * Serializes the particle system to a JSON object.
  56520. * @returns the JSON object
  56521. */
  56522. BoxParticleEmitter.prototype.serialize = function () {
  56523. var serializationObject = {};
  56524. serializationObject.type = this.getClassName();
  56525. serializationObject.direction1 = this.direction1.asArray();
  56526. serializationObject.direction2 = this.direction2.asArray();
  56527. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56528. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56529. return serializationObject;
  56530. };
  56531. /**
  56532. * Parse properties from a JSON object
  56533. * @param serializationObject defines the JSON object
  56534. */
  56535. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56536. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56537. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56538. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56539. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56540. };
  56541. return BoxParticleEmitter;
  56542. }());
  56543. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56544. })(BABYLON || (BABYLON = {}));
  56545. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56546. var BABYLON;
  56547. (function (BABYLON) {
  56548. /**
  56549. * Particle emitter emitting particles from the inside of a cone.
  56550. * It emits the particles alongside the cone volume from the base to the particle.
  56551. * The emission direction might be randomized.
  56552. */
  56553. var ConeParticleEmitter = /** @class */ (function () {
  56554. /**
  56555. * Creates a new instance ConeParticleEmitter
  56556. * @param radius the radius of the emission cone (1 by default)
  56557. * @param angles the cone base angle (PI by default)
  56558. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56559. */
  56560. function ConeParticleEmitter(radius, angle,
  56561. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56562. directionRandomizer) {
  56563. if (radius === void 0) { radius = 1; }
  56564. if (angle === void 0) { angle = Math.PI; }
  56565. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56566. this.directionRandomizer = directionRandomizer;
  56567. this.angle = angle;
  56568. this.radius = radius;
  56569. }
  56570. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56571. /**
  56572. * Gets or sets the radius of the emission cone
  56573. */
  56574. get: function () {
  56575. return this._radius;
  56576. },
  56577. set: function (value) {
  56578. this._radius = value;
  56579. this._buildHeight();
  56580. },
  56581. enumerable: true,
  56582. configurable: true
  56583. });
  56584. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56585. /**
  56586. * Gets or sets the angle of the emission cone
  56587. */
  56588. get: function () {
  56589. return this._angle;
  56590. },
  56591. set: function (value) {
  56592. this._angle = value;
  56593. this._buildHeight();
  56594. },
  56595. enumerable: true,
  56596. configurable: true
  56597. });
  56598. ConeParticleEmitter.prototype._buildHeight = function () {
  56599. if (this._angle !== 0) {
  56600. this._height = this._radius / Math.tan(this._angle / 2);
  56601. }
  56602. else {
  56603. this._height = 1;
  56604. }
  56605. };
  56606. /**
  56607. * Called by the particle System when the direction is computed for the created particle.
  56608. * @param worldMatrix is the world matrix of the particle system
  56609. * @param directionToUpdate is the direction vector to update with the result
  56610. * @param particle is the particle we are computed the direction for
  56611. */
  56612. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56613. if (this._angle === 0) {
  56614. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56615. }
  56616. else {
  56617. // measure the direction Vector from the emitter to the particle.
  56618. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56619. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56620. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56621. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56622. direction.x += randX;
  56623. direction.y += randY;
  56624. direction.z += randZ;
  56625. direction.normalize();
  56626. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56627. }
  56628. };
  56629. /**
  56630. * Called by the particle System when the position is computed for the created particle.
  56631. * @param worldMatrix is the world matrix of the particle system
  56632. * @param positionToUpdate is the position vector to update with the result
  56633. * @param particle is the particle we are computed the position for
  56634. */
  56635. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56636. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56637. var h = BABYLON.Scalar.RandomRange(0, 1);
  56638. // Better distribution in a cone at normal angles.
  56639. h = 1 - h * h;
  56640. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56641. radius = radius * h;
  56642. var randX = radius * Math.sin(s);
  56643. var randZ = radius * Math.cos(s);
  56644. var randY = h * this._height;
  56645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56646. };
  56647. /**
  56648. * Clones the current emitter and returns a copy of it
  56649. * @returns the new emitter
  56650. */
  56651. ConeParticleEmitter.prototype.clone = function () {
  56652. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56653. BABYLON.Tools.DeepCopy(this, newOne);
  56654. return newOne;
  56655. };
  56656. /**
  56657. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56658. * @param effect defines the update shader
  56659. */
  56660. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56661. effect.setFloat("radius", this._radius);
  56662. effect.setFloat("coneAngle", this._angle);
  56663. effect.setFloat("height", this._height);
  56664. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56665. };
  56666. /**
  56667. * Returns a string to use to update the GPU particles update shader
  56668. * @returns a string containng the defines string
  56669. */
  56670. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56671. return "#define CONEEMITTER";
  56672. };
  56673. /**
  56674. * Returns the string "BoxEmitter"
  56675. * @returns a string containing the class name
  56676. */
  56677. ConeParticleEmitter.prototype.getClassName = function () {
  56678. return "ConeEmitter";
  56679. };
  56680. /**
  56681. * Serializes the particle system to a JSON object.
  56682. * @returns the JSON object
  56683. */
  56684. ConeParticleEmitter.prototype.serialize = function () {
  56685. var serializationObject = {};
  56686. serializationObject.type = this.getClassName();
  56687. serializationObject.radius = this._radius;
  56688. serializationObject.angle = this._angle;
  56689. serializationObject.directionRandomizer = this.directionRandomizer;
  56690. return serializationObject;
  56691. };
  56692. /**
  56693. * Parse properties from a JSON object
  56694. * @param serializationObject defines the JSON object
  56695. */
  56696. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56697. this.radius = serializationObject.radius;
  56698. this.angle = serializationObject.angle;
  56699. this.directionRandomizer = serializationObject.directionRandomizer;
  56700. };
  56701. return ConeParticleEmitter;
  56702. }());
  56703. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56704. })(BABYLON || (BABYLON = {}));
  56705. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. /**
  56709. * Particle emitter emitting particles from the inside of a sphere.
  56710. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56711. */
  56712. var SphereParticleEmitter = /** @class */ (function () {
  56713. /**
  56714. * Creates a new instance SphereParticleEmitter
  56715. * @param radius the radius of the emission sphere (1 by default)
  56716. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56717. */
  56718. function SphereParticleEmitter(
  56719. /**
  56720. * The radius of the emission sphere.
  56721. */
  56722. radius,
  56723. /**
  56724. * How much to randomize the particle direction [0-1].
  56725. */
  56726. directionRandomizer) {
  56727. if (radius === void 0) { radius = 1; }
  56728. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56729. this.radius = radius;
  56730. this.directionRandomizer = directionRandomizer;
  56731. /**
  56732. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56733. */
  56734. this.radiusRange = 1;
  56735. }
  56736. /**
  56737. * Called by the particle System when the direction is computed for the created particle.
  56738. * @param worldMatrix is the world matrix of the particle system
  56739. * @param directionToUpdate is the direction vector to update with the result
  56740. * @param particle is the particle we are computed the direction for
  56741. */
  56742. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56743. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56744. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56745. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56746. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56747. direction.x += randX;
  56748. direction.y += randY;
  56749. direction.z += randZ;
  56750. direction.normalize();
  56751. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56752. };
  56753. /**
  56754. * Called by the particle System when the position is computed for the created particle.
  56755. * @param worldMatrix is the world matrix of the particle system
  56756. * @param positionToUpdate is the position vector to update with the result
  56757. * @param particle is the particle we are computed the position for
  56758. */
  56759. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56760. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56761. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56762. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56763. var theta = Math.acos(2 * v - 1);
  56764. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56765. var randY = randRadius * Math.cos(theta);
  56766. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56768. };
  56769. /**
  56770. * Clones the current emitter and returns a copy of it
  56771. * @returns the new emitter
  56772. */
  56773. SphereParticleEmitter.prototype.clone = function () {
  56774. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56775. BABYLON.Tools.DeepCopy(this, newOne);
  56776. return newOne;
  56777. };
  56778. /**
  56779. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56780. * @param effect defines the update shader
  56781. */
  56782. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56783. effect.setFloat("radius", this.radius);
  56784. effect.setFloat("radiusRange", this.radiusRange);
  56785. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56786. };
  56787. /**
  56788. * Returns a string to use to update the GPU particles update shader
  56789. * @returns a string containng the defines string
  56790. */
  56791. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56792. return "#define SPHEREEMITTER";
  56793. };
  56794. /**
  56795. * Returns the string "SphereParticleEmitter"
  56796. * @returns a string containing the class name
  56797. */
  56798. SphereParticleEmitter.prototype.getClassName = function () {
  56799. return "SphereParticleEmitter";
  56800. };
  56801. /**
  56802. * Serializes the particle system to a JSON object.
  56803. * @returns the JSON object
  56804. */
  56805. SphereParticleEmitter.prototype.serialize = function () {
  56806. var serializationObject = {};
  56807. serializationObject.type = this.getClassName();
  56808. serializationObject.radius = this.radius;
  56809. serializationObject.directionRandomizer = this.directionRandomizer;
  56810. return serializationObject;
  56811. };
  56812. /**
  56813. * Parse properties from a JSON object
  56814. * @param serializationObject defines the JSON object
  56815. */
  56816. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56817. this.radius = serializationObject.radius;
  56818. this.directionRandomizer = serializationObject.directionRandomizer;
  56819. };
  56820. return SphereParticleEmitter;
  56821. }());
  56822. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56823. /**
  56824. * Particle emitter emitting particles from the inside of a sphere.
  56825. * It emits the particles randomly between two vectors.
  56826. */
  56827. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56828. __extends(SphereDirectedParticleEmitter, _super);
  56829. /**
  56830. * Creates a new instance SphereDirectedParticleEmitter
  56831. * @param radius the radius of the emission sphere (1 by default)
  56832. * @param direction1 the min limit of the emission direction (up vector by default)
  56833. * @param direction2 the max limit of the emission direction (up vector by default)
  56834. */
  56835. function SphereDirectedParticleEmitter(radius,
  56836. /**
  56837. * The min limit of the emission direction.
  56838. */
  56839. direction1,
  56840. /**
  56841. * The max limit of the emission direction.
  56842. */
  56843. direction2) {
  56844. if (radius === void 0) { radius = 1; }
  56845. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56846. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56847. var _this = _super.call(this, radius) || this;
  56848. _this.direction1 = direction1;
  56849. _this.direction2 = direction2;
  56850. return _this;
  56851. }
  56852. /**
  56853. * Called by the particle System when the direction is computed for the created particle.
  56854. * @param worldMatrix is the world matrix of the particle system
  56855. * @param directionToUpdate is the direction vector to update with the result
  56856. * @param particle is the particle we are computed the direction for
  56857. */
  56858. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56859. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56860. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56861. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56862. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56863. };
  56864. /**
  56865. * Clones the current emitter and returns a copy of it
  56866. * @returns the new emitter
  56867. */
  56868. SphereDirectedParticleEmitter.prototype.clone = function () {
  56869. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56870. BABYLON.Tools.DeepCopy(this, newOne);
  56871. return newOne;
  56872. };
  56873. /**
  56874. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56875. * @param effect defines the update shader
  56876. */
  56877. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56878. effect.setFloat("radius", this.radius);
  56879. effect.setFloat("radiusRange", this.radiusRange);
  56880. effect.setVector3("direction1", this.direction1);
  56881. effect.setVector3("direction2", this.direction2);
  56882. };
  56883. /**
  56884. * Returns a string to use to update the GPU particles update shader
  56885. * @returns a string containng the defines string
  56886. */
  56887. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56888. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56889. };
  56890. /**
  56891. * Returns the string "SphereDirectedParticleEmitter"
  56892. * @returns a string containing the class name
  56893. */
  56894. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56895. return "SphereDirectedParticleEmitter";
  56896. };
  56897. /**
  56898. * Serializes the particle system to a JSON object.
  56899. * @returns the JSON object
  56900. */
  56901. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56902. var serializationObject = _super.prototype.serialize.call(this);
  56903. serializationObject.direction1 = this.direction1.asArray();
  56904. serializationObject.direction2 = this.direction2.asArray();
  56905. return serializationObject;
  56906. };
  56907. /**
  56908. * Parse properties from a JSON object
  56909. * @param serializationObject defines the JSON object
  56910. */
  56911. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56912. _super.prototype.parse.call(this, serializationObject);
  56913. this.direction1.copyFrom(serializationObject.direction1);
  56914. this.direction2.copyFrom(serializationObject.direction2);
  56915. };
  56916. return SphereDirectedParticleEmitter;
  56917. }(SphereParticleEmitter));
  56918. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56919. })(BABYLON || (BABYLON = {}));
  56920. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56921. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56922. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56923. s = arguments[i];
  56924. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56925. t[p] = s[p];
  56926. }
  56927. return t;
  56928. };
  56929. var BABYLON;
  56930. (function (BABYLON) {
  56931. /**
  56932. * This represents a GPU particle system in Babylon
  56933. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56934. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56935. */
  56936. var GPUParticleSystem = /** @class */ (function () {
  56937. /**
  56938. * Instantiates a GPU particle system.
  56939. * 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.
  56940. * @param name The name of the particle system
  56941. * @param capacity The max number of particles alive at the same time
  56942. * @param scene The scene the particle system belongs to
  56943. */
  56944. function GPUParticleSystem(name, options, scene) {
  56945. /**
  56946. * The emitter represents the Mesh or position we are attaching the particle system to.
  56947. */
  56948. this.emitter = null;
  56949. /**
  56950. * The rendering group used by the Particle system to chose when to render.
  56951. */
  56952. this.renderingGroupId = 0;
  56953. /**
  56954. * The layer mask we are rendering the particles through.
  56955. */
  56956. this.layerMask = 0x0FFFFFFF;
  56957. this._accumulatedCount = 0;
  56958. this._targetIndex = 0;
  56959. this._currentRenderId = -1;
  56960. this._started = false;
  56961. this._stopped = false;
  56962. this._timeDelta = 0;
  56963. this._attributesStrideSize = 21;
  56964. this._actualFrame = 0;
  56965. /**
  56966. * List of animations used by the particle system.
  56967. */
  56968. this.animations = [];
  56969. /**
  56970. * An event triggered when the system is disposed.
  56971. */
  56972. this.onDisposeObservable = new BABYLON.Observable();
  56973. /**
  56974. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56975. */
  56976. this.updateSpeed = 0.01;
  56977. /**
  56978. * The amount of time the particle system is running (depends of the overall update speed).
  56979. */
  56980. this.targetStopDuration = 0;
  56981. /**
  56982. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56983. */
  56984. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56985. /**
  56986. * Minimum life time of emitting particles.
  56987. */
  56988. this.minLifeTime = 1;
  56989. /**
  56990. * Maximum life time of emitting particles.
  56991. */
  56992. this.maxLifeTime = 1;
  56993. /**
  56994. * Minimum Size of emitting particles.
  56995. */
  56996. this.minSize = 1;
  56997. /**
  56998. * Maximum Size of emitting particles.
  56999. */
  57000. this.maxSize = 1;
  57001. /**
  57002. * Minimum scale of emitting particles on X axis.
  57003. */
  57004. this.minScaleX = 1;
  57005. /**
  57006. * Maximum scale of emitting particles on X axis.
  57007. */
  57008. this.maxScaleX = 1;
  57009. /**
  57010. * Minimum scale of emitting particles on Y axis.
  57011. */
  57012. this.minScaleY = 1;
  57013. /**
  57014. * Maximum scale of emitting particles on Y axis.
  57015. */
  57016. this.maxScaleY = 1;
  57017. /**
  57018. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57019. */
  57020. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57021. /**
  57022. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57023. */
  57024. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57025. /**
  57026. * Color the particle will have at the end of its lifetime.
  57027. */
  57028. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57029. /**
  57030. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57031. */
  57032. this.emitRate = 100;
  57033. /**
  57034. * You can use gravity if you want to give an orientation to your particles.
  57035. */
  57036. this.gravity = BABYLON.Vector3.Zero();
  57037. /**
  57038. * Minimum power of emitting particles.
  57039. */
  57040. this.minEmitPower = 1;
  57041. /**
  57042. * Maximum power of emitting particles.
  57043. */
  57044. this.maxEmitPower = 1;
  57045. /**
  57046. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57047. */
  57048. this.minAngularSpeed = 0;
  57049. /**
  57050. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57051. */
  57052. this.maxAngularSpeed = 0;
  57053. /**
  57054. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57055. * to override the particles.
  57056. */
  57057. this.forceDepthWrite = false;
  57058. this._preWarmDone = false;
  57059. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57060. this.preWarmCycles = 0;
  57061. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57062. this.preWarmStepOffset = 1;
  57063. /**
  57064. * Gets or sets the minimal initial rotation in radians.
  57065. */
  57066. this.minInitialRotation = 0;
  57067. /**
  57068. * Gets or sets the maximal initial rotation in radians.
  57069. */
  57070. this.maxInitialRotation = 0;
  57071. this._isBillboardBased = true;
  57072. this._colorGradients = null;
  57073. this._sizeGradients = null;
  57074. this.id = name;
  57075. this.name = name;
  57076. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57077. this._engine = this._scene.getEngine();
  57078. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57079. var optionsAsNumber = options;
  57080. if (isFinite(optionsAsNumber)) {
  57081. fullOptions.capacity = optionsAsNumber;
  57082. }
  57083. this._capacity = fullOptions.capacity;
  57084. this._activeCount = fullOptions.capacity;
  57085. this._currentActiveCount = 0;
  57086. this._scene.particleSystems.push(this);
  57087. this._updateEffectOptions = {
  57088. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  57089. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57090. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57091. "angleRange", "radiusRange"],
  57092. uniformBuffersNames: [],
  57093. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  57094. defines: "",
  57095. fallbacks: null,
  57096. onCompiled: null,
  57097. onError: null,
  57098. indexParameters: null,
  57099. maxSimultaneousLights: 0,
  57100. transformFeedbackVaryings: []
  57101. };
  57102. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57103. // Random data
  57104. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57105. var d = [];
  57106. for (var i = 0; i < maxTextureSize; ++i) {
  57107. d.push(Math.random());
  57108. d.push(Math.random());
  57109. d.push(Math.random());
  57110. d.push(Math.random());
  57111. }
  57112. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57113. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57114. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57115. d = [];
  57116. for (var i = 0; i < maxTextureSize; ++i) {
  57117. d.push(Math.random());
  57118. d.push(Math.random());
  57119. d.push(Math.random());
  57120. d.push(Math.random());
  57121. }
  57122. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57123. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57124. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57125. this._randomTextureSize = maxTextureSize;
  57126. }
  57127. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57128. /**
  57129. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57130. */
  57131. get: function () {
  57132. if (!BABYLON.Engine.LastCreatedEngine) {
  57133. return false;
  57134. }
  57135. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57136. },
  57137. enumerable: true,
  57138. configurable: true
  57139. });
  57140. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57141. /**
  57142. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57143. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57144. */
  57145. get: function () {
  57146. if (this.particleEmitterType.direction1) {
  57147. return this.particleEmitterType.direction1;
  57148. }
  57149. return BABYLON.Vector3.Zero();
  57150. },
  57151. set: function (value) {
  57152. if (this.particleEmitterType.direction1) {
  57153. this.particleEmitterType.direction1 = value;
  57154. }
  57155. },
  57156. enumerable: true,
  57157. configurable: true
  57158. });
  57159. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57160. /**
  57161. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57162. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57163. */
  57164. get: function () {
  57165. if (this.particleEmitterType.direction2) {
  57166. return this.particleEmitterType.direction2;
  57167. }
  57168. return BABYLON.Vector3.Zero();
  57169. },
  57170. set: function (value) {
  57171. if (this.particleEmitterType.direction2) {
  57172. this.particleEmitterType.direction2 = value;
  57173. }
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57179. /**
  57180. * 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.
  57181. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57182. */
  57183. get: function () {
  57184. if (this.particleEmitterType.minEmitBox) {
  57185. return this.particleEmitterType.minEmitBox;
  57186. }
  57187. return BABYLON.Vector3.Zero();
  57188. },
  57189. set: function (value) {
  57190. if (this.particleEmitterType.minEmitBox) {
  57191. this.particleEmitterType.minEmitBox = value;
  57192. }
  57193. },
  57194. enumerable: true,
  57195. configurable: true
  57196. });
  57197. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57198. /**
  57199. * 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.
  57200. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57201. */
  57202. get: function () {
  57203. if (this.particleEmitterType.maxEmitBox) {
  57204. return this.particleEmitterType.maxEmitBox;
  57205. }
  57206. return BABYLON.Vector3.Zero();
  57207. },
  57208. set: function (value) {
  57209. if (this.particleEmitterType.maxEmitBox) {
  57210. this.particleEmitterType.maxEmitBox = value;
  57211. }
  57212. },
  57213. enumerable: true,
  57214. configurable: true
  57215. });
  57216. /**
  57217. * Gets the maximum number of particles active at the same time.
  57218. * @returns The max number of active particles.
  57219. */
  57220. GPUParticleSystem.prototype.getCapacity = function () {
  57221. return this._capacity;
  57222. };
  57223. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57224. /**
  57225. * Gets or set the number of active particles
  57226. */
  57227. get: function () {
  57228. return this._activeCount;
  57229. },
  57230. set: function (value) {
  57231. this._activeCount = Math.min(value, this._capacity);
  57232. },
  57233. enumerable: true,
  57234. configurable: true
  57235. });
  57236. /**
  57237. * Is this system ready to be used/rendered
  57238. * @return true if the system is ready
  57239. */
  57240. GPUParticleSystem.prototype.isReady = function () {
  57241. if (!this._updateEffect) {
  57242. this._recreateUpdateEffect();
  57243. this._recreateRenderEffect();
  57244. return false;
  57245. }
  57246. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57247. return false;
  57248. }
  57249. return true;
  57250. };
  57251. /**
  57252. * Gets Wether the system has been started.
  57253. * @returns True if it has been started, otherwise false.
  57254. */
  57255. GPUParticleSystem.prototype.isStarted = function () {
  57256. return this._started;
  57257. };
  57258. /**
  57259. * Starts the particle system and begins to emit.
  57260. */
  57261. GPUParticleSystem.prototype.start = function () {
  57262. this._started = true;
  57263. this._stopped = false;
  57264. this._preWarmDone = false;
  57265. };
  57266. /**
  57267. * Stops the particle system.
  57268. */
  57269. GPUParticleSystem.prototype.stop = function () {
  57270. this._stopped = true;
  57271. };
  57272. /**
  57273. * Remove all active particles
  57274. */
  57275. GPUParticleSystem.prototype.reset = function () {
  57276. this._releaseBuffers();
  57277. this._releaseVAOs();
  57278. this._currentActiveCount = 0;
  57279. this._targetIndex = 0;
  57280. };
  57281. /**
  57282. * Returns the string "GPUParticleSystem"
  57283. * @returns a string containing the class name
  57284. */
  57285. GPUParticleSystem.prototype.getClassName = function () {
  57286. return "GPUParticleSystem";
  57287. };
  57288. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57289. /**
  57290. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57291. */
  57292. get: function () {
  57293. return this._isBillboardBased;
  57294. },
  57295. set: function (value) {
  57296. if (this._isBillboardBased === value) {
  57297. return;
  57298. }
  57299. this._isBillboardBased = value;
  57300. this._releaseBuffers();
  57301. },
  57302. enumerable: true,
  57303. configurable: true
  57304. });
  57305. /**
  57306. * Gets the current list of color gradients.
  57307. * You must use addColorGradient and removeColorGradient to udpate this list
  57308. * @returns the list of color gradients
  57309. */
  57310. GPUParticleSystem.prototype.getColorGradients = function () {
  57311. return this._colorGradients;
  57312. };
  57313. /**
  57314. * Gets the current list of size gradients.
  57315. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57316. * @returns the list of size gradients
  57317. */
  57318. GPUParticleSystem.prototype.getSizeGradients = function () {
  57319. return this._sizeGradients;
  57320. };
  57321. /**
  57322. * Adds a new color gradient
  57323. * @param gradient defines the gradient to use (between 0 and 1)
  57324. * @param color defines the color to affect to the specified gradient
  57325. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57326. */
  57327. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57328. if (!this._colorGradients) {
  57329. this._colorGradients = [];
  57330. }
  57331. var colorGradient = new BABYLON.ColorGradient();
  57332. colorGradient.gradient = gradient;
  57333. colorGradient.color1 = color1;
  57334. this._colorGradients.push(colorGradient);
  57335. this._colorGradients.sort(function (a, b) {
  57336. if (a.gradient < b.gradient) {
  57337. return -1;
  57338. }
  57339. else if (a.gradient > b.gradient) {
  57340. return 1;
  57341. }
  57342. return 0;
  57343. });
  57344. if (this._colorGradientsTexture) {
  57345. this._colorGradientsTexture.dispose();
  57346. this._colorGradientsTexture = null;
  57347. }
  57348. this._releaseBuffers();
  57349. return this;
  57350. };
  57351. /**
  57352. * Remove a specific color gradient
  57353. * @param gradient defines the gradient to remove
  57354. */
  57355. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57356. if (!this._colorGradients) {
  57357. return this;
  57358. }
  57359. var index = 0;
  57360. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57361. var colorGradient = _a[_i];
  57362. if (colorGradient.gradient === gradient) {
  57363. this._colorGradients.splice(index, 1);
  57364. break;
  57365. }
  57366. index++;
  57367. }
  57368. if (this._colorGradientsTexture) {
  57369. this._colorGradientsTexture.dispose();
  57370. this._colorGradientsTexture = null;
  57371. }
  57372. this._releaseBuffers();
  57373. return this;
  57374. };
  57375. /**
  57376. * Adds a new size gradient
  57377. * @param gradient defines the gradient to use (between 0 and 1)
  57378. * @param factor defines the size factor to affect to the specified gradient
  57379. */
  57380. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57381. if (!this._sizeGradients) {
  57382. this._sizeGradients = [];
  57383. }
  57384. var sizeGradient = new BABYLON.FactorGradient();
  57385. sizeGradient.gradient = gradient;
  57386. sizeGradient.factor = factor;
  57387. this._sizeGradients.push(sizeGradient);
  57388. this._sizeGradients.sort(function (a, b) {
  57389. if (a.gradient < b.gradient) {
  57390. return -1;
  57391. }
  57392. else if (a.gradient > b.gradient) {
  57393. return 1;
  57394. }
  57395. return 0;
  57396. });
  57397. if (this._sizeGradientsTexture) {
  57398. this._sizeGradientsTexture.dispose();
  57399. this._sizeGradientsTexture = null;
  57400. }
  57401. this._releaseBuffers();
  57402. return this;
  57403. };
  57404. /**
  57405. * Remove a specific size gradient
  57406. * @param gradient defines the gradient to remove
  57407. */
  57408. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57409. if (!this._sizeGradients) {
  57410. return this;
  57411. }
  57412. var index = 0;
  57413. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57414. var sizeGradient = _a[_i];
  57415. if (sizeGradient.gradient === gradient) {
  57416. this._sizeGradients.splice(index, 1);
  57417. break;
  57418. }
  57419. index++;
  57420. }
  57421. if (this._sizeGradientsTexture) {
  57422. this._sizeGradientsTexture.dispose();
  57423. this._sizeGradientsTexture = null;
  57424. }
  57425. this._releaseBuffers();
  57426. return this;
  57427. };
  57428. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57429. var updateVertexBuffers = {};
  57430. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57431. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57432. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57433. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57434. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57435. var offset = 12;
  57436. if (this._sizeGradientsTexture) {
  57437. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57438. offset += 3;
  57439. }
  57440. if (!this._colorGradientsTexture) {
  57441. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57442. offset += 4;
  57443. }
  57444. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57445. offset += 3;
  57446. if (!this._isBillboardBased) {
  57447. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57448. offset += 3;
  57449. }
  57450. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57451. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57452. this._engine.bindArrayBuffer(null);
  57453. return vao;
  57454. };
  57455. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57456. var renderVertexBuffers = {};
  57457. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57458. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57459. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57460. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57461. var offset = 12;
  57462. if (this._sizeGradientsTexture) {
  57463. offset += 3;
  57464. }
  57465. if (!this._colorGradientsTexture) {
  57466. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57467. offset += 4;
  57468. }
  57469. offset += 3; // Direction
  57470. if (!this._isBillboardBased) {
  57471. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57472. offset += 3;
  57473. }
  57474. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57475. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57476. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57477. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57478. this._engine.bindArrayBuffer(null);
  57479. return vao;
  57480. };
  57481. GPUParticleSystem.prototype._initialize = function (force) {
  57482. if (force === void 0) { force = false; }
  57483. if (this._buffer0 && !force) {
  57484. return;
  57485. }
  57486. var engine = this._scene.getEngine();
  57487. var data = new Array();
  57488. if (!this.isBillboardBased) {
  57489. this._attributesStrideSize += 3;
  57490. }
  57491. if (this._colorGradientsTexture) {
  57492. this._attributesStrideSize -= 4;
  57493. }
  57494. if (this._sizeGradientsTexture) {
  57495. this._attributesStrideSize += 3;
  57496. }
  57497. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57498. // position
  57499. data.push(0.0);
  57500. data.push(0.0);
  57501. data.push(0.0);
  57502. // Age and life
  57503. data.push(0.0); // create the particle as a dead one to create a new one at start
  57504. data.push(0.0);
  57505. // Seed
  57506. data.push(Math.random());
  57507. data.push(Math.random());
  57508. data.push(Math.random());
  57509. data.push(Math.random());
  57510. // Size
  57511. data.push(0.0);
  57512. data.push(0.0);
  57513. data.push(0.0);
  57514. if (this._sizeGradientsTexture) {
  57515. data.push(0.0);
  57516. data.push(0.0);
  57517. data.push(0.0);
  57518. }
  57519. if (!this._colorGradientsTexture) {
  57520. // color
  57521. data.push(0.0);
  57522. data.push(0.0);
  57523. data.push(0.0);
  57524. data.push(0.0);
  57525. }
  57526. // direction
  57527. data.push(0.0);
  57528. data.push(0.0);
  57529. data.push(0.0);
  57530. if (!this.isBillboardBased) {
  57531. // initialDirection
  57532. data.push(0.0);
  57533. data.push(0.0);
  57534. data.push(0.0);
  57535. }
  57536. // angle
  57537. data.push(0.0);
  57538. data.push(0.0);
  57539. }
  57540. // Sprite data
  57541. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57542. -0.5, 0.5, 0, 1,
  57543. -0.5, -0.5, 0, 0,
  57544. 0.5, -0.5, 1, 0]);
  57545. // Buffers
  57546. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57547. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57548. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57549. // Update VAO
  57550. this._updateVAO = [];
  57551. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57552. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57553. // Render VAO
  57554. this._renderVAO = [];
  57555. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57556. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57557. // Links
  57558. this._sourceBuffer = this._buffer0;
  57559. this._targetBuffer = this._buffer1;
  57560. };
  57561. /** @hidden */
  57562. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57563. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57564. if (this._isBillboardBased) {
  57565. defines += "\n#define BILLBOARD";
  57566. }
  57567. if (this._colorGradientsTexture) {
  57568. defines += "\n#define COLORGRADIENTS";
  57569. }
  57570. if (this._sizeGradientsTexture) {
  57571. defines += "\n#define SIZEGRADIENTS";
  57572. }
  57573. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57574. return;
  57575. }
  57576. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57577. if (this._sizeGradientsTexture) {
  57578. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57579. }
  57580. if (!this._colorGradientsTexture) {
  57581. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57582. }
  57583. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57584. if (!this._isBillboardBased) {
  57585. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57586. }
  57587. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57588. this._updateEffectOptions.defines = defines;
  57589. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57590. };
  57591. /** @hidden */
  57592. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57593. var defines = "";
  57594. if (this._scene.clipPlane) {
  57595. defines = "\n#define CLIPPLANE";
  57596. }
  57597. if (this._isBillboardBased) {
  57598. defines += "\n#define BILLBOARD";
  57599. }
  57600. if (this._colorGradientsTexture) {
  57601. defines += "\n#define COLORGRADIENTS";
  57602. }
  57603. if (this._renderEffect && this._renderEffect.defines === defines) {
  57604. return;
  57605. }
  57606. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57607. };
  57608. /**
  57609. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57610. * @param preWarm defines if we are in the pre-warmimg phase
  57611. */
  57612. GPUParticleSystem.prototype.animate = function (preWarm) {
  57613. if (preWarm === void 0) { preWarm = false; }
  57614. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57615. this._actualFrame += this._timeDelta;
  57616. if (!this._stopped) {
  57617. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57618. this.stop();
  57619. }
  57620. }
  57621. };
  57622. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57623. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57624. return;
  57625. }
  57626. var textureWidth = 256;
  57627. var data = new Float32Array(textureWidth);
  57628. for (var x = 0; x < textureWidth; x++) {
  57629. var ratio = x / textureWidth;
  57630. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57631. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57632. });
  57633. }
  57634. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57635. };
  57636. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57637. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57638. return;
  57639. }
  57640. var textureWidth = 256;
  57641. var data = new Uint8Array(textureWidth * 4);
  57642. var tmpColor = BABYLON.Tmp.Color4[0];
  57643. for (var x = 0; x < textureWidth; x++) {
  57644. var ratio = x / textureWidth;
  57645. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57646. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57647. data[x * 4] = tmpColor.r * 255;
  57648. data[x * 4 + 1] = tmpColor.g * 255;
  57649. data[x * 4 + 2] = tmpColor.b * 255;
  57650. data[x * 4 + 3] = tmpColor.a * 255;
  57651. });
  57652. }
  57653. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57654. };
  57655. /**
  57656. * Renders the particle system in its current state
  57657. * @param preWarm defines if the system should only update the particles but not render them
  57658. * @returns the current number of particles
  57659. */
  57660. GPUParticleSystem.prototype.render = function (preWarm) {
  57661. if (preWarm === void 0) { preWarm = false; }
  57662. if (!this._started) {
  57663. return 0;
  57664. }
  57665. this._createColorGradientTexture();
  57666. this._createSizeGradientTexture();
  57667. this._recreateUpdateEffect();
  57668. this._recreateRenderEffect();
  57669. if (!this.isReady()) {
  57670. return 0;
  57671. }
  57672. if (!preWarm) {
  57673. if (!this._preWarmDone && this.preWarmCycles) {
  57674. for (var index = 0; index < this.preWarmCycles; index++) {
  57675. this.animate(true);
  57676. this.render(true);
  57677. }
  57678. this._preWarmDone = true;
  57679. }
  57680. if (this._currentRenderId === this._scene.getRenderId()) {
  57681. return 0;
  57682. }
  57683. this._currentRenderId = this._scene.getRenderId();
  57684. }
  57685. // Get everything ready to render
  57686. this._initialize();
  57687. this._accumulatedCount += this.emitRate * this._timeDelta;
  57688. if (this._accumulatedCount > 1) {
  57689. var intPart = this._accumulatedCount | 0;
  57690. this._accumulatedCount -= intPart;
  57691. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57692. }
  57693. if (!this._currentActiveCount) {
  57694. return 0;
  57695. }
  57696. // Enable update effect
  57697. this._engine.enableEffect(this._updateEffect);
  57698. this._engine.setState(false);
  57699. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57700. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57701. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57702. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57703. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57704. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57705. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57706. if (!this._colorGradientsTexture) {
  57707. this._updateEffect.setDirectColor4("color1", this.color1);
  57708. this._updateEffect.setDirectColor4("color2", this.color2);
  57709. }
  57710. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57711. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57712. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57713. this._updateEffect.setVector3("gravity", this.gravity);
  57714. if (this._sizeGradientsTexture) {
  57715. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57716. }
  57717. if (this.particleEmitterType) {
  57718. this.particleEmitterType.applyToShader(this._updateEffect);
  57719. }
  57720. var emitterWM;
  57721. if (this.emitter.position) {
  57722. var emitterMesh = this.emitter;
  57723. emitterWM = emitterMesh.getWorldMatrix();
  57724. }
  57725. else {
  57726. var emitterPosition = this.emitter;
  57727. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57728. }
  57729. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57730. // Bind source VAO
  57731. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57732. // Update
  57733. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57734. this._engine.setRasterizerState(false);
  57735. this._engine.beginTransformFeedback();
  57736. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57737. this._engine.endTransformFeedback();
  57738. this._engine.setRasterizerState(true);
  57739. this._engine.bindTransformFeedbackBuffer(null);
  57740. if (!preWarm) {
  57741. // Enable render effect
  57742. this._engine.enableEffect(this._renderEffect);
  57743. var viewMatrix = this._scene.getViewMatrix();
  57744. this._renderEffect.setMatrix("view", viewMatrix);
  57745. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57746. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57747. if (this._colorGradientsTexture) {
  57748. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57749. }
  57750. else {
  57751. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57752. }
  57753. if (this._scene.clipPlane) {
  57754. var clipPlane = this._scene.clipPlane;
  57755. var invView = viewMatrix.clone();
  57756. invView.invert();
  57757. this._renderEffect.setMatrix("invView", invView);
  57758. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57759. }
  57760. // Draw order
  57761. switch (this.blendMode) {
  57762. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57763. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57764. break;
  57765. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57766. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57767. break;
  57768. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57769. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57770. break;
  57771. }
  57772. if (this.forceDepthWrite) {
  57773. this._engine.setDepthWrite(true);
  57774. }
  57775. // Bind source VAO
  57776. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57777. // Render
  57778. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57779. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57780. }
  57781. // Switch VAOs
  57782. this._targetIndex++;
  57783. if (this._targetIndex === 2) {
  57784. this._targetIndex = 0;
  57785. }
  57786. // Switch buffers
  57787. var tmpBuffer = this._sourceBuffer;
  57788. this._sourceBuffer = this._targetBuffer;
  57789. this._targetBuffer = tmpBuffer;
  57790. return this._currentActiveCount;
  57791. };
  57792. /**
  57793. * Rebuilds the particle system
  57794. */
  57795. GPUParticleSystem.prototype.rebuild = function () {
  57796. this._initialize(true);
  57797. };
  57798. GPUParticleSystem.prototype._releaseBuffers = function () {
  57799. if (this._buffer0) {
  57800. this._buffer0.dispose();
  57801. this._buffer0 = null;
  57802. }
  57803. if (this._buffer1) {
  57804. this._buffer1.dispose();
  57805. this._buffer1 = null;
  57806. }
  57807. if (this._spriteBuffer) {
  57808. this._spriteBuffer.dispose();
  57809. this._spriteBuffer = null;
  57810. }
  57811. };
  57812. GPUParticleSystem.prototype._releaseVAOs = function () {
  57813. if (!this._updateVAO) {
  57814. return;
  57815. }
  57816. for (var index = 0; index < this._updateVAO.length; index++) {
  57817. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57818. }
  57819. this._updateVAO = [];
  57820. for (var index = 0; index < this._renderVAO.length; index++) {
  57821. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57822. }
  57823. this._renderVAO = [];
  57824. };
  57825. /**
  57826. * Disposes the particle system and free the associated resources
  57827. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57828. */
  57829. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57830. if (disposeTexture === void 0) { disposeTexture = true; }
  57831. var index = this._scene.particleSystems.indexOf(this);
  57832. if (index > -1) {
  57833. this._scene.particleSystems.splice(index, 1);
  57834. }
  57835. this._releaseBuffers();
  57836. this._releaseVAOs();
  57837. if (this._colorGradientsTexture) {
  57838. this._colorGradientsTexture.dispose();
  57839. this._colorGradientsTexture = null;
  57840. }
  57841. if (this._sizeGradientsTexture) {
  57842. this._sizeGradientsTexture.dispose();
  57843. this._sizeGradientsTexture = null;
  57844. }
  57845. if (this._randomTexture) {
  57846. this._randomTexture.dispose();
  57847. this._randomTexture = null;
  57848. }
  57849. if (this._randomTexture2) {
  57850. this._randomTexture2.dispose();
  57851. this._randomTexture2 = null;
  57852. }
  57853. if (disposeTexture && this.particleTexture) {
  57854. this.particleTexture.dispose();
  57855. this.particleTexture = null;
  57856. }
  57857. // Callback
  57858. this.onDisposeObservable.notifyObservers(this);
  57859. this.onDisposeObservable.clear();
  57860. };
  57861. /**
  57862. * Clones the particle system.
  57863. * @param name The name of the cloned object
  57864. * @param newEmitter The new emitter to use
  57865. * @returns the cloned particle system
  57866. */
  57867. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57868. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57869. BABYLON.Tools.DeepCopy(this, result);
  57870. if (newEmitter === undefined) {
  57871. newEmitter = this.emitter;
  57872. }
  57873. result.emitter = newEmitter;
  57874. if (this.particleTexture) {
  57875. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57876. }
  57877. return result;
  57878. };
  57879. /**
  57880. * Serializes the particle system to a JSON object.
  57881. * @returns the JSON object
  57882. */
  57883. GPUParticleSystem.prototype.serialize = function () {
  57884. var serializationObject = {};
  57885. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57886. return serializationObject;
  57887. };
  57888. /**
  57889. * Parses a JSON object to create a GPU particle system.
  57890. * @param parsedParticleSystem The JSON object to parse
  57891. * @param scene The scene to create the particle system in
  57892. * @param rootUrl The root url to use to load external dependencies like texture
  57893. * @returns the parsed GPU particle system
  57894. */
  57895. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57896. var name = parsedParticleSystem.name;
  57897. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57898. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57899. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57900. return particleSystem;
  57901. };
  57902. return GPUParticleSystem;
  57903. }());
  57904. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57905. })(BABYLON || (BABYLON = {}));
  57906. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57907. var BABYLON;
  57908. (function (BABYLON) {
  57909. /**
  57910. * Represents one particle of a solid particle system.
  57911. */
  57912. var SolidParticle = /** @class */ (function () {
  57913. /**
  57914. * Creates a Solid Particle object.
  57915. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57916. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57917. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57918. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57919. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57920. * @param shapeId (integer) is the model shape identifier in the SPS.
  57921. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57922. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57923. */
  57924. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57925. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57926. /**
  57927. * particle global index
  57928. */
  57929. this.idx = 0;
  57930. /**
  57931. * The color of the particle
  57932. */
  57933. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57934. /**
  57935. * The world space position of the particle.
  57936. */
  57937. this.position = BABYLON.Vector3.Zero();
  57938. /**
  57939. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57940. */
  57941. this.rotation = BABYLON.Vector3.Zero();
  57942. /**
  57943. * The scaling of the particle.
  57944. */
  57945. this.scaling = BABYLON.Vector3.One();
  57946. /**
  57947. * The uvs of the particle.
  57948. */
  57949. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57950. /**
  57951. * The current speed of the particle.
  57952. */
  57953. this.velocity = BABYLON.Vector3.Zero();
  57954. /**
  57955. * The pivot point in the particle local space.
  57956. */
  57957. this.pivot = BABYLON.Vector3.Zero();
  57958. /**
  57959. * Must the particle be translated from its pivot point in its local space ?
  57960. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57961. * Default : false
  57962. */
  57963. this.translateFromPivot = false;
  57964. /**
  57965. * Is the particle active or not ?
  57966. */
  57967. this.alive = true;
  57968. /**
  57969. * Is the particle visible or not ?
  57970. */
  57971. this.isVisible = true;
  57972. /**
  57973. * Index of this particle in the global "positions" array (Internal use)
  57974. */
  57975. this._pos = 0;
  57976. /**
  57977. * Index of this particle in the global "indices" array (Internal use)
  57978. */
  57979. this._ind = 0;
  57980. /**
  57981. * ModelShape id of this particle
  57982. */
  57983. this.shapeId = 0;
  57984. /**
  57985. * Index of the particle in its shape id (Internal use)
  57986. */
  57987. this.idxInShape = 0;
  57988. /**
  57989. * Still set as invisible in order to skip useless computations (Internal use)
  57990. */
  57991. this._stillInvisible = false;
  57992. /**
  57993. * Last computed particle rotation matrix
  57994. */
  57995. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57996. /**
  57997. * Parent particle Id, if any.
  57998. * Default null.
  57999. */
  58000. this.parentId = null;
  58001. /**
  58002. * Internal global position in the SPS.
  58003. */
  58004. this._globalPosition = BABYLON.Vector3.Zero();
  58005. this.idx = particleIndex;
  58006. this._pos = positionIndex;
  58007. this._ind = indiceIndex;
  58008. this._model = model;
  58009. this.shapeId = shapeId;
  58010. this.idxInShape = idxInShape;
  58011. this._sps = sps;
  58012. if (modelBoundingInfo) {
  58013. this._modelBoundingInfo = modelBoundingInfo;
  58014. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58015. }
  58016. }
  58017. Object.defineProperty(SolidParticle.prototype, "scale", {
  58018. /**
  58019. * Legacy support, changed scale to scaling
  58020. */
  58021. get: function () {
  58022. return this.scaling;
  58023. },
  58024. /**
  58025. * Legacy support, changed scale to scaling
  58026. */
  58027. set: function (scale) {
  58028. this.scaling = scale;
  58029. },
  58030. enumerable: true,
  58031. configurable: true
  58032. });
  58033. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58034. /**
  58035. * Legacy support, changed quaternion to rotationQuaternion
  58036. */
  58037. get: function () {
  58038. return this.rotationQuaternion;
  58039. },
  58040. /**
  58041. * Legacy support, changed quaternion to rotationQuaternion
  58042. */
  58043. set: function (q) {
  58044. this.rotationQuaternion = q;
  58045. },
  58046. enumerable: true,
  58047. configurable: true
  58048. });
  58049. /**
  58050. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58051. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58052. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58053. * @returns true if it intersects
  58054. */
  58055. SolidParticle.prototype.intersectsMesh = function (target) {
  58056. if (!this._boundingInfo || !target._boundingInfo) {
  58057. return false;
  58058. }
  58059. if (this._sps._bSphereOnly) {
  58060. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58061. }
  58062. return this._boundingInfo.intersects(target._boundingInfo, false);
  58063. };
  58064. return SolidParticle;
  58065. }());
  58066. BABYLON.SolidParticle = SolidParticle;
  58067. /**
  58068. * Represents the shape of the model used by one particle of a solid particle system.
  58069. * SPS internal tool, don't use it manually.
  58070. */
  58071. var ModelShape = /** @class */ (function () {
  58072. /**
  58073. * 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.
  58074. * SPS internal tool, don't use it manually.
  58075. * @hidden
  58076. */
  58077. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58078. /**
  58079. * length of the shape in the model indices array (internal use)
  58080. */
  58081. this._indicesLength = 0;
  58082. this.shapeID = id;
  58083. this._shape = shape;
  58084. this._indicesLength = indicesLength;
  58085. this._shapeUV = shapeUV;
  58086. this._positionFunction = posFunction;
  58087. this._vertexFunction = vtxFunction;
  58088. }
  58089. return ModelShape;
  58090. }());
  58091. BABYLON.ModelShape = ModelShape;
  58092. /**
  58093. * Represents a Depth Sorted Particle in the solid particle system.
  58094. */
  58095. var DepthSortedParticle = /** @class */ (function () {
  58096. function DepthSortedParticle() {
  58097. /**
  58098. * Index of the particle in the "indices" array
  58099. */
  58100. this.ind = 0;
  58101. /**
  58102. * Length of the particle shape in the "indices" array
  58103. */
  58104. this.indicesLength = 0;
  58105. /**
  58106. * Squared distance from the particle to the camera
  58107. */
  58108. this.sqDistance = 0.0;
  58109. }
  58110. return DepthSortedParticle;
  58111. }());
  58112. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58113. })(BABYLON || (BABYLON = {}));
  58114. //# sourceMappingURL=babylon.solidParticle.js.map
  58115. var BABYLON;
  58116. (function (BABYLON) {
  58117. /**
  58118. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58119. *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.
  58120. * The SPS is also a particle system. It provides some methods to manage the particles.
  58121. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58122. *
  58123. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58124. */
  58125. var SolidParticleSystem = /** @class */ (function () {
  58126. /**
  58127. * Creates a SPS (Solid Particle System) object.
  58128. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58129. * @param scene (Scene) is the scene in which the SPS is added.
  58130. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58131. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58132. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58133. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58134. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58135. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58136. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58137. */
  58138. function SolidParticleSystem(name, scene, options) {
  58139. /**
  58140. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58141. * Example : var p = SPS.particles[i];
  58142. */
  58143. this.particles = new Array();
  58144. /**
  58145. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58146. */
  58147. this.nbParticles = 0;
  58148. /**
  58149. * If the particles must ever face the camera (default false). Useful for planar particles.
  58150. */
  58151. this.billboard = false;
  58152. /**
  58153. * Recompute normals when adding a shape
  58154. */
  58155. this.recomputeNormals = true;
  58156. /**
  58157. * This a counter ofr your own usage. It's not set by any SPS functions.
  58158. */
  58159. this.counter = 0;
  58160. /**
  58161. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58162. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58163. */
  58164. this.vars = {};
  58165. /**
  58166. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58167. */
  58168. this._bSphereOnly = false;
  58169. /**
  58170. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58171. */
  58172. this._bSphereRadiusFactor = 1.0;
  58173. this._positions = new Array();
  58174. this._indices = new Array();
  58175. this._normals = new Array();
  58176. this._colors = new Array();
  58177. this._uvs = new Array();
  58178. this._index = 0; // indices index
  58179. this._updatable = true;
  58180. this._pickable = false;
  58181. this._isVisibilityBoxLocked = false;
  58182. this._alwaysVisible = false;
  58183. this._depthSort = false;
  58184. this._shapeCounter = 0;
  58185. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58186. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58187. this._computeParticleColor = true;
  58188. this._computeParticleTexture = true;
  58189. this._computeParticleRotation = true;
  58190. this._computeParticleVertex = false;
  58191. this._computeBoundingBox = false;
  58192. this._depthSortParticles = true;
  58193. this._cam_axisZ = BABYLON.Vector3.Zero();
  58194. this._cam_axisY = BABYLON.Vector3.Zero();
  58195. this._cam_axisX = BABYLON.Vector3.Zero();
  58196. this._axisZ = BABYLON.Axis.Z;
  58197. this._camDir = BABYLON.Vector3.Zero();
  58198. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58199. this._rotMatrix = new BABYLON.Matrix();
  58200. this._invertMatrix = new BABYLON.Matrix();
  58201. this._rotated = BABYLON.Vector3.Zero();
  58202. this._quaternion = new BABYLON.Quaternion();
  58203. this._vertex = BABYLON.Vector3.Zero();
  58204. this._normal = BABYLON.Vector3.Zero();
  58205. this._yaw = 0.0;
  58206. this._pitch = 0.0;
  58207. this._roll = 0.0;
  58208. this._halfroll = 0.0;
  58209. this._halfpitch = 0.0;
  58210. this._halfyaw = 0.0;
  58211. this._sinRoll = 0.0;
  58212. this._cosRoll = 0.0;
  58213. this._sinPitch = 0.0;
  58214. this._cosPitch = 0.0;
  58215. this._sinYaw = 0.0;
  58216. this._cosYaw = 0.0;
  58217. this._mustUnrotateFixedNormals = false;
  58218. this._minimum = BABYLON.Vector3.Zero();
  58219. this._maximum = BABYLON.Vector3.Zero();
  58220. this._minBbox = BABYLON.Vector3.Zero();
  58221. this._maxBbox = BABYLON.Vector3.Zero();
  58222. this._particlesIntersect = false;
  58223. this._depthSortFunction = function (p1, p2) {
  58224. return (p2.sqDistance - p1.sqDistance);
  58225. };
  58226. this._needs32Bits = false;
  58227. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58228. this._scaledPivot = BABYLON.Vector3.Zero();
  58229. this._particleHasParent = false;
  58230. this.name = name;
  58231. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58232. this._camera = scene.activeCamera;
  58233. this._pickable = options ? options.isPickable : false;
  58234. this._depthSort = options ? options.enableDepthSort : false;
  58235. this._particlesIntersect = options ? options.particleIntersection : false;
  58236. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58237. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58238. if (options && options.updatable !== undefined) {
  58239. this._updatable = options.updatable;
  58240. }
  58241. else {
  58242. this._updatable = true;
  58243. }
  58244. if (this._pickable) {
  58245. this.pickedParticles = [];
  58246. }
  58247. if (this._depthSort) {
  58248. this.depthSortedParticles = [];
  58249. }
  58250. }
  58251. /**
  58252. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58253. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58254. * @returns the created mesh
  58255. */
  58256. SolidParticleSystem.prototype.buildMesh = function () {
  58257. if (this.nbParticles === 0) {
  58258. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58259. this.addShape(triangle, 1);
  58260. triangle.dispose();
  58261. }
  58262. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58263. this._positions32 = new Float32Array(this._positions);
  58264. this._uvs32 = new Float32Array(this._uvs);
  58265. this._colors32 = new Float32Array(this._colors);
  58266. if (this.recomputeNormals) {
  58267. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58268. }
  58269. this._normals32 = new Float32Array(this._normals);
  58270. this._fixedNormal32 = new Float32Array(this._normals);
  58271. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58272. this._unrotateFixedNormals();
  58273. }
  58274. var vertexData = new BABYLON.VertexData();
  58275. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58276. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58277. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58278. if (this._uvs32.length > 0) {
  58279. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58280. }
  58281. if (this._colors32.length > 0) {
  58282. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58283. }
  58284. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58285. vertexData.applyToMesh(mesh, this._updatable);
  58286. this.mesh = mesh;
  58287. this.mesh.isPickable = this._pickable;
  58288. // free memory
  58289. if (!this._depthSort) {
  58290. this._indices = null;
  58291. }
  58292. this._positions = null;
  58293. this._normals = null;
  58294. this._uvs = null;
  58295. this._colors = null;
  58296. if (!this._updatable) {
  58297. this.particles.length = 0;
  58298. }
  58299. return mesh;
  58300. };
  58301. /**
  58302. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58303. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58304. * Thus the particles generated from `digest()` have their property `position` set yet.
  58305. * @param mesh ( Mesh ) is the mesh to be digested
  58306. * @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
  58307. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58308. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58309. * @returns the current SPS
  58310. */
  58311. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58312. var size = (options && options.facetNb) || 1;
  58313. var number = (options && options.number) || 0;
  58314. var delta = (options && options.delta) || 0;
  58315. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58316. var meshInd = mesh.getIndices();
  58317. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58318. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58319. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58320. var f = 0; // facet counter
  58321. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58322. // compute size from number
  58323. if (number) {
  58324. number = (number > totalFacets) ? totalFacets : number;
  58325. size = Math.round(totalFacets / number);
  58326. delta = 0;
  58327. }
  58328. else {
  58329. size = (size > totalFacets) ? totalFacets : size;
  58330. }
  58331. var facetPos = []; // submesh positions
  58332. var facetInd = []; // submesh indices
  58333. var facetUV = []; // submesh UV
  58334. var facetCol = []; // submesh colors
  58335. var barycenter = BABYLON.Vector3.Zero();
  58336. var sizeO = size;
  58337. while (f < totalFacets) {
  58338. size = sizeO + Math.floor((1 + delta) * Math.random());
  58339. if (f > totalFacets - size) {
  58340. size = totalFacets - f;
  58341. }
  58342. // reset temp arrays
  58343. facetPos.length = 0;
  58344. facetInd.length = 0;
  58345. facetUV.length = 0;
  58346. facetCol.length = 0;
  58347. // iterate over "size" facets
  58348. var fi = 0;
  58349. for (var j = f * 3; j < (f + size) * 3; j++) {
  58350. facetInd.push(fi);
  58351. var i = meshInd[j];
  58352. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58353. if (meshUV) {
  58354. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58355. }
  58356. if (meshCol) {
  58357. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58358. }
  58359. fi++;
  58360. }
  58361. // create a model shape for each single particle
  58362. var idx = this.nbParticles;
  58363. var shape = this._posToShape(facetPos);
  58364. var shapeUV = this._uvsToShapeUV(facetUV);
  58365. // compute the barycenter of the shape
  58366. var v;
  58367. for (v = 0; v < shape.length; v++) {
  58368. barycenter.addInPlace(shape[v]);
  58369. }
  58370. barycenter.scaleInPlace(1 / shape.length);
  58371. // shift the shape from its barycenter to the origin
  58372. for (v = 0; v < shape.length; v++) {
  58373. shape[v].subtractInPlace(barycenter);
  58374. }
  58375. var bInfo;
  58376. if (this._particlesIntersect) {
  58377. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58378. }
  58379. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58380. // add the particle in the SPS
  58381. var currentPos = this._positions.length;
  58382. var currentInd = this._indices.length;
  58383. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58384. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58385. // initialize the particle position
  58386. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58387. this._index += shape.length;
  58388. idx++;
  58389. this.nbParticles++;
  58390. this._shapeCounter++;
  58391. f += size;
  58392. }
  58393. return this;
  58394. };
  58395. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58396. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58397. var index = 0;
  58398. var idx = 0;
  58399. for (var p = 0; p < this.particles.length; p++) {
  58400. this._particle = this.particles[p];
  58401. this._shape = this._particle._model._shape;
  58402. if (this._particle.rotationQuaternion) {
  58403. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58404. }
  58405. else {
  58406. this._yaw = this._particle.rotation.y;
  58407. this._pitch = this._particle.rotation.x;
  58408. this._roll = this._particle.rotation.z;
  58409. this._quaternionRotationYPR();
  58410. }
  58411. this._quaternionToRotationMatrix();
  58412. this._rotMatrix.invertToRef(this._invertMatrix);
  58413. for (var pt = 0; pt < this._shape.length; pt++) {
  58414. idx = index + pt * 3;
  58415. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58416. this._fixedNormal32[idx] = this._normal.x;
  58417. this._fixedNormal32[idx + 1] = this._normal.y;
  58418. this._fixedNormal32[idx + 2] = this._normal.z;
  58419. }
  58420. index = idx + 3;
  58421. }
  58422. };
  58423. //reset copy
  58424. SolidParticleSystem.prototype._resetCopy = function () {
  58425. this._copy.position.x = 0;
  58426. this._copy.position.y = 0;
  58427. this._copy.position.z = 0;
  58428. this._copy.rotation.x = 0;
  58429. this._copy.rotation.y = 0;
  58430. this._copy.rotation.z = 0;
  58431. this._copy.rotationQuaternion = null;
  58432. this._copy.scaling.x = 1.0;
  58433. this._copy.scaling.y = 1.0;
  58434. this._copy.scaling.z = 1.0;
  58435. this._copy.uvs.x = 0;
  58436. this._copy.uvs.y = 0;
  58437. this._copy.uvs.z = 1.0;
  58438. this._copy.uvs.w = 1.0;
  58439. this._copy.color = null;
  58440. this._copy.translateFromPivot = false;
  58441. };
  58442. // _meshBuilder : inserts the shape model in the global SPS mesh
  58443. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58444. var i;
  58445. var u = 0;
  58446. var c = 0;
  58447. var n = 0;
  58448. this._resetCopy();
  58449. if (options && options.positionFunction) { // call to custom positionFunction
  58450. options.positionFunction(this._copy, idx, idxInShape);
  58451. this._mustUnrotateFixedNormals = true;
  58452. }
  58453. if (this._copy.rotationQuaternion) {
  58454. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58455. }
  58456. else {
  58457. this._yaw = this._copy.rotation.y;
  58458. this._pitch = this._copy.rotation.x;
  58459. this._roll = this._copy.rotation.z;
  58460. this._quaternionRotationYPR();
  58461. }
  58462. this._quaternionToRotationMatrix();
  58463. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58464. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58465. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58466. if (this._copy.translateFromPivot) {
  58467. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58468. }
  58469. else {
  58470. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58471. }
  58472. for (i = 0; i < shape.length; i++) {
  58473. this._vertex.x = shape[i].x;
  58474. this._vertex.y = shape[i].y;
  58475. this._vertex.z = shape[i].z;
  58476. if (options && options.vertexFunction) {
  58477. options.vertexFunction(this._copy, this._vertex, i);
  58478. }
  58479. this._vertex.x *= this._copy.scaling.x;
  58480. this._vertex.y *= this._copy.scaling.y;
  58481. this._vertex.z *= this._copy.scaling.z;
  58482. this._vertex.x -= this._scaledPivot.x;
  58483. this._vertex.y -= this._scaledPivot.y;
  58484. this._vertex.z -= this._scaledPivot.z;
  58485. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58486. this._rotated.addInPlace(this._pivotBackTranslation);
  58487. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58488. if (meshUV) {
  58489. 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);
  58490. u += 2;
  58491. }
  58492. if (this._copy.color) {
  58493. this._color = this._copy.color;
  58494. }
  58495. else if (meshCol && meshCol[c] !== undefined) {
  58496. this._color.r = meshCol[c];
  58497. this._color.g = meshCol[c + 1];
  58498. this._color.b = meshCol[c + 2];
  58499. this._color.a = meshCol[c + 3];
  58500. }
  58501. else {
  58502. this._color.r = 1.0;
  58503. this._color.g = 1.0;
  58504. this._color.b = 1.0;
  58505. this._color.a = 1.0;
  58506. }
  58507. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58508. c += 4;
  58509. if (!this.recomputeNormals && meshNor) {
  58510. this._normal.x = meshNor[n];
  58511. this._normal.y = meshNor[n + 1];
  58512. this._normal.z = meshNor[n + 2];
  58513. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58514. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58515. n += 3;
  58516. }
  58517. }
  58518. for (i = 0; i < meshInd.length; i++) {
  58519. var current_ind = p + meshInd[i];
  58520. indices.push(current_ind);
  58521. if (current_ind > 65535) {
  58522. this._needs32Bits = true;
  58523. }
  58524. }
  58525. if (this._pickable) {
  58526. var nbfaces = meshInd.length / 3;
  58527. for (i = 0; i < nbfaces; i++) {
  58528. this.pickedParticles.push({ idx: idx, faceId: i });
  58529. }
  58530. }
  58531. if (this._depthSort) {
  58532. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58533. }
  58534. return this._copy;
  58535. };
  58536. // returns a shape array from positions array
  58537. SolidParticleSystem.prototype._posToShape = function (positions) {
  58538. var shape = [];
  58539. for (var i = 0; i < positions.length; i += 3) {
  58540. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58541. }
  58542. return shape;
  58543. };
  58544. // returns a shapeUV array from a Vector4 uvs
  58545. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58546. var shapeUV = [];
  58547. if (uvs) {
  58548. for (var i = 0; i < uvs.length; i++)
  58549. shapeUV.push(uvs[i]);
  58550. }
  58551. return shapeUV;
  58552. };
  58553. // adds a new particle object in the particles array
  58554. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58555. if (bInfo === void 0) { bInfo = null; }
  58556. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58557. this.particles.push(sp);
  58558. return sp;
  58559. };
  58560. /**
  58561. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58562. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58563. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58564. * @param nb (positive integer) the number of particles to be created from this model
  58565. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58566. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58567. * @returns the number of shapes in the system
  58568. */
  58569. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58570. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58571. var meshInd = mesh.getIndices();
  58572. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58573. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58574. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58575. var bbInfo;
  58576. if (this._particlesIntersect) {
  58577. bbInfo = mesh.getBoundingInfo();
  58578. }
  58579. var shape = this._posToShape(meshPos);
  58580. var shapeUV = this._uvsToShapeUV(meshUV);
  58581. var posfunc = options ? options.positionFunction : null;
  58582. var vtxfunc = options ? options.vertexFunction : null;
  58583. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58584. // particles
  58585. var sp;
  58586. var currentCopy;
  58587. var idx = this.nbParticles;
  58588. for (var i = 0; i < nb; i++) {
  58589. var currentPos = this._positions.length;
  58590. var currentInd = this._indices.length;
  58591. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58592. if (this._updatable) {
  58593. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58594. sp.position.copyFrom(currentCopy.position);
  58595. sp.rotation.copyFrom(currentCopy.rotation);
  58596. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58597. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58598. }
  58599. if (currentCopy.color && sp.color) {
  58600. sp.color.copyFrom(currentCopy.color);
  58601. }
  58602. sp.scaling.copyFrom(currentCopy.scaling);
  58603. sp.uvs.copyFrom(currentCopy.uvs);
  58604. }
  58605. this._index += shape.length;
  58606. idx++;
  58607. }
  58608. this.nbParticles += nb;
  58609. this._shapeCounter++;
  58610. return this._shapeCounter - 1;
  58611. };
  58612. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58613. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58614. this._resetCopy();
  58615. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58616. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58617. }
  58618. if (this._copy.rotationQuaternion) {
  58619. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58620. }
  58621. else {
  58622. this._yaw = this._copy.rotation.y;
  58623. this._pitch = this._copy.rotation.x;
  58624. this._roll = this._copy.rotation.z;
  58625. this._quaternionRotationYPR();
  58626. }
  58627. this._quaternionToRotationMatrix();
  58628. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58629. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58630. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58631. if (this._copy.translateFromPivot) {
  58632. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58633. }
  58634. else {
  58635. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58636. }
  58637. this._shape = particle._model._shape;
  58638. for (var pt = 0; pt < this._shape.length; pt++) {
  58639. this._vertex.x = this._shape[pt].x;
  58640. this._vertex.y = this._shape[pt].y;
  58641. this._vertex.z = this._shape[pt].z;
  58642. if (particle._model._vertexFunction) {
  58643. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58644. }
  58645. this._vertex.x *= this._copy.scaling.x;
  58646. this._vertex.y *= this._copy.scaling.y;
  58647. this._vertex.z *= this._copy.scaling.z;
  58648. this._vertex.x -= this._scaledPivot.x;
  58649. this._vertex.y -= this._scaledPivot.y;
  58650. this._vertex.z -= this._scaledPivot.z;
  58651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58652. this._rotated.addInPlace(this._pivotBackTranslation);
  58653. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58654. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58655. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58656. }
  58657. particle.position.x = 0.0;
  58658. particle.position.y = 0.0;
  58659. particle.position.z = 0.0;
  58660. particle.rotation.x = 0.0;
  58661. particle.rotation.y = 0.0;
  58662. particle.rotation.z = 0.0;
  58663. particle.rotationQuaternion = null;
  58664. particle.scaling.x = 1.0;
  58665. particle.scaling.y = 1.0;
  58666. particle.scaling.z = 1.0;
  58667. particle.uvs.x = 0.0;
  58668. particle.uvs.y = 0.0;
  58669. particle.uvs.z = 1.0;
  58670. particle.uvs.w = 1.0;
  58671. particle.pivot.x = 0.0;
  58672. particle.pivot.y = 0.0;
  58673. particle.pivot.z = 0.0;
  58674. particle.translateFromPivot = false;
  58675. particle.parentId = null;
  58676. };
  58677. /**
  58678. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58679. * @returns the SPS.
  58680. */
  58681. SolidParticleSystem.prototype.rebuildMesh = function () {
  58682. for (var p = 0; p < this.particles.length; p++) {
  58683. this._rebuildParticle(this.particles[p]);
  58684. }
  58685. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58686. return this;
  58687. };
  58688. /**
  58689. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58690. * This method calls `updateParticle()` for each particle of the SPS.
  58691. * For an animated SPS, it is usually called within the render loop.
  58692. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58693. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58694. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58695. * @returns the SPS.
  58696. */
  58697. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58698. if (start === void 0) { start = 0; }
  58699. if (end === void 0) { end = this.nbParticles - 1; }
  58700. if (update === void 0) { update = true; }
  58701. if (!this._updatable) {
  58702. return this;
  58703. }
  58704. // custom beforeUpdate
  58705. this.beforeUpdateParticles(start, end, update);
  58706. this._cam_axisX.x = 1.0;
  58707. this._cam_axisX.y = 0.0;
  58708. this._cam_axisX.z = 0.0;
  58709. this._cam_axisY.x = 0.0;
  58710. this._cam_axisY.y = 1.0;
  58711. this._cam_axisY.z = 0.0;
  58712. this._cam_axisZ.x = 0.0;
  58713. this._cam_axisZ.y = 0.0;
  58714. this._cam_axisZ.z = 1.0;
  58715. // cases when the World Matrix is to be computed first
  58716. if (this.billboard || this._depthSort) {
  58717. this.mesh.computeWorldMatrix(true);
  58718. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58719. }
  58720. // if the particles will always face the camera
  58721. if (this.billboard) {
  58722. // compute the camera position and un-rotate it by the current mesh rotation
  58723. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58724. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58725. this._cam_axisZ.normalize();
  58726. // same for camera up vector extracted from the cam view matrix
  58727. var view = this._camera.getViewMatrix(true);
  58728. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58729. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58730. this._cam_axisY.normalize();
  58731. this._cam_axisX.normalize();
  58732. }
  58733. // if depthSort, compute the camera global position in the mesh local system
  58734. if (this._depthSort) {
  58735. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58736. }
  58737. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58738. var idx = 0; // current position index in the global array positions32
  58739. var index = 0; // position start index in the global array positions32 of the current particle
  58740. var colidx = 0; // current color index in the global array colors32
  58741. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58742. var uvidx = 0; // current uv index in the global array uvs32
  58743. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58744. var pt = 0; // current index in the particle model shape
  58745. if (this.mesh.isFacetDataEnabled) {
  58746. this._computeBoundingBox = true;
  58747. }
  58748. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58749. if (this._computeBoundingBox) {
  58750. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58751. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58752. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58753. }
  58754. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58755. if (this.mesh._boundingInfo) {
  58756. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58757. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58758. }
  58759. }
  58760. }
  58761. // particle loop
  58762. index = this.particles[start]._pos;
  58763. var vpos = (index / 3) | 0;
  58764. colorIndex = vpos * 4;
  58765. uvIndex = vpos * 2;
  58766. for (var p = start; p <= end; p++) {
  58767. this._particle = this.particles[p];
  58768. this._shape = this._particle._model._shape;
  58769. this._shapeUV = this._particle._model._shapeUV;
  58770. // call to custom user function to update the particle properties
  58771. this.updateParticle(this._particle);
  58772. // camera-particle distance for depth sorting
  58773. if (this._depthSort && this._depthSortParticles) {
  58774. var dsp = this.depthSortedParticles[p];
  58775. dsp.ind = this._particle._ind;
  58776. dsp.indicesLength = this._particle._model._indicesLength;
  58777. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58778. }
  58779. // skip the computations for inactive or already invisible particles
  58780. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58781. // increment indexes for the next particle
  58782. pt = this._shape.length;
  58783. index += pt * 3;
  58784. colorIndex += pt * 4;
  58785. uvIndex += pt * 2;
  58786. continue;
  58787. }
  58788. if (this._particle.isVisible) {
  58789. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58790. this._particleHasParent = (this._particle.parentId !== null);
  58791. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58792. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58793. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58794. // particle rotation matrix
  58795. if (this.billboard) {
  58796. this._particle.rotation.x = 0.0;
  58797. this._particle.rotation.y = 0.0;
  58798. }
  58799. if (this._computeParticleRotation || this.billboard) {
  58800. if (this._particle.rotationQuaternion) {
  58801. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58802. }
  58803. else {
  58804. this._yaw = this._particle.rotation.y;
  58805. this._pitch = this._particle.rotation.x;
  58806. this._roll = this._particle.rotation.z;
  58807. this._quaternionRotationYPR();
  58808. }
  58809. this._quaternionToRotationMatrix();
  58810. }
  58811. if (this._particleHasParent) {
  58812. this._parent = this.particles[this._particle.parentId];
  58813. 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];
  58814. 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];
  58815. 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];
  58816. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58817. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58818. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58819. if (this._computeParticleRotation || this.billboard) {
  58820. 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];
  58821. 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];
  58822. 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];
  58823. 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];
  58824. 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];
  58825. 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];
  58826. 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];
  58827. 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];
  58828. 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];
  58829. }
  58830. }
  58831. else {
  58832. this._particle._globalPosition.x = this._particle.position.x;
  58833. this._particle._globalPosition.y = this._particle.position.y;
  58834. this._particle._globalPosition.z = this._particle.position.z;
  58835. if (this._computeParticleRotation || this.billboard) {
  58836. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58837. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58838. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58839. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58840. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58841. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58842. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58843. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58844. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58845. }
  58846. }
  58847. if (this._particle.translateFromPivot) {
  58848. this._pivotBackTranslation.x = 0.0;
  58849. this._pivotBackTranslation.y = 0.0;
  58850. this._pivotBackTranslation.z = 0.0;
  58851. }
  58852. else {
  58853. this._pivotBackTranslation.x = this._scaledPivot.x;
  58854. this._pivotBackTranslation.y = this._scaledPivot.y;
  58855. this._pivotBackTranslation.z = this._scaledPivot.z;
  58856. }
  58857. // particle vertex loop
  58858. for (pt = 0; pt < this._shape.length; pt++) {
  58859. idx = index + pt * 3;
  58860. colidx = colorIndex + pt * 4;
  58861. uvidx = uvIndex + pt * 2;
  58862. this._vertex.x = this._shape[pt].x;
  58863. this._vertex.y = this._shape[pt].y;
  58864. this._vertex.z = this._shape[pt].z;
  58865. if (this._computeParticleVertex) {
  58866. this.updateParticleVertex(this._particle, this._vertex, pt);
  58867. }
  58868. // positions
  58869. this._vertex.x *= this._particle.scaling.x;
  58870. this._vertex.y *= this._particle.scaling.y;
  58871. this._vertex.z *= this._particle.scaling.z;
  58872. this._vertex.x -= this._scaledPivot.x;
  58873. this._vertex.y -= this._scaledPivot.y;
  58874. this._vertex.z -= this._scaledPivot.z;
  58875. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58876. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58877. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58878. this._rotated.x += this._pivotBackTranslation.x;
  58879. this._rotated.y += this._pivotBackTranslation.y;
  58880. this._rotated.z += this._pivotBackTranslation.z;
  58881. 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;
  58882. 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;
  58883. 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;
  58884. if (this._computeBoundingBox) {
  58885. if (this._positions32[idx] < this._minimum.x) {
  58886. this._minimum.x = this._positions32[idx];
  58887. }
  58888. if (this._positions32[idx] > this._maximum.x) {
  58889. this._maximum.x = this._positions32[idx];
  58890. }
  58891. if (this._positions32[idx + 1] < this._minimum.y) {
  58892. this._minimum.y = this._positions32[idx + 1];
  58893. }
  58894. if (this._positions32[idx + 1] > this._maximum.y) {
  58895. this._maximum.y = this._positions32[idx + 1];
  58896. }
  58897. if (this._positions32[idx + 2] < this._minimum.z) {
  58898. this._minimum.z = this._positions32[idx + 2];
  58899. }
  58900. if (this._positions32[idx + 2] > this._maximum.z) {
  58901. this._maximum.z = this._positions32[idx + 2];
  58902. }
  58903. }
  58904. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58905. if (!this._computeParticleVertex) {
  58906. this._normal.x = this._fixedNormal32[idx];
  58907. this._normal.y = this._fixedNormal32[idx + 1];
  58908. this._normal.z = this._fixedNormal32[idx + 2];
  58909. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58910. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58911. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58912. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58913. 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;
  58914. 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;
  58915. }
  58916. if (this._computeParticleColor && this._particle.color) {
  58917. this._colors32[colidx] = this._particle.color.r;
  58918. this._colors32[colidx + 1] = this._particle.color.g;
  58919. this._colors32[colidx + 2] = this._particle.color.b;
  58920. this._colors32[colidx + 3] = this._particle.color.a;
  58921. }
  58922. if (this._computeParticleTexture) {
  58923. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58924. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58925. }
  58926. }
  58927. }
  58928. // particle just set invisible : scaled to zero and positioned at the origin
  58929. else {
  58930. this._particle._stillInvisible = true; // mark the particle as invisible
  58931. for (pt = 0; pt < this._shape.length; pt++) {
  58932. idx = index + pt * 3;
  58933. colidx = colorIndex + pt * 4;
  58934. uvidx = uvIndex + pt * 2;
  58935. this._positions32[idx] = 0.0;
  58936. this._positions32[idx + 1] = 0.0;
  58937. this._positions32[idx + 2] = 0.0;
  58938. this._normals32[idx] = 0.0;
  58939. this._normals32[idx + 1] = 0.0;
  58940. this._normals32[idx + 2] = 0.0;
  58941. if (this._computeParticleColor && this._particle.color) {
  58942. this._colors32[colidx] = this._particle.color.r;
  58943. this._colors32[colidx + 1] = this._particle.color.g;
  58944. this._colors32[colidx + 2] = this._particle.color.b;
  58945. this._colors32[colidx + 3] = this._particle.color.a;
  58946. }
  58947. if (this._computeParticleTexture) {
  58948. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58949. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58950. }
  58951. }
  58952. }
  58953. // if the particle intersections must be computed : update the bbInfo
  58954. if (this._particlesIntersect) {
  58955. var bInfo = this._particle._boundingInfo;
  58956. var bBox = bInfo.boundingBox;
  58957. var bSphere = bInfo.boundingSphere;
  58958. if (!this._bSphereOnly) {
  58959. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58960. for (var b = 0; b < bBox.vectors.length; b++) {
  58961. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58962. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58963. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58964. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58965. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58966. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58967. 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;
  58968. 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;
  58969. 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;
  58970. }
  58971. bBox._update(this.mesh._worldMatrix);
  58972. }
  58973. // place and scale the particle bouding sphere in the SPS local system, then update it
  58974. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58975. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58976. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58977. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58978. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58979. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58980. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58981. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58982. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58983. 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));
  58984. bSphere._update(this.mesh._worldMatrix);
  58985. }
  58986. // increment indexes for the next particle
  58987. index = idx + 3;
  58988. colorIndex = colidx + 4;
  58989. uvIndex = uvidx + 2;
  58990. }
  58991. // if the VBO must be updated
  58992. if (update) {
  58993. if (this._computeParticleColor) {
  58994. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58995. }
  58996. if (this._computeParticleTexture) {
  58997. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58998. }
  58999. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59000. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59001. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59002. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59003. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59004. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59005. for (var i = 0; i < this._normals32.length; i++) {
  59006. this._fixedNormal32[i] = this._normals32[i];
  59007. }
  59008. }
  59009. if (!this.mesh.areNormalsFrozen) {
  59010. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59011. }
  59012. }
  59013. if (this._depthSort && this._depthSortParticles) {
  59014. this.depthSortedParticles.sort(this._depthSortFunction);
  59015. var dspl = this.depthSortedParticles.length;
  59016. var sorted = 0;
  59017. var lind = 0;
  59018. var sind = 0;
  59019. var sid = 0;
  59020. for (sorted = 0; sorted < dspl; sorted++) {
  59021. lind = this.depthSortedParticles[sorted].indicesLength;
  59022. sind = this.depthSortedParticles[sorted].ind;
  59023. for (var i = 0; i < lind; i++) {
  59024. this._indices32[sid] = this._indices[sind + i];
  59025. sid++;
  59026. }
  59027. }
  59028. this.mesh.updateIndices(this._indices32);
  59029. }
  59030. }
  59031. if (this._computeBoundingBox) {
  59032. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59033. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59034. }
  59035. this.afterUpdateParticles(start, end, update);
  59036. return this;
  59037. };
  59038. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59039. this._halfroll = this._roll * 0.5;
  59040. this._halfpitch = this._pitch * 0.5;
  59041. this._halfyaw = this._yaw * 0.5;
  59042. this._sinRoll = Math.sin(this._halfroll);
  59043. this._cosRoll = Math.cos(this._halfroll);
  59044. this._sinPitch = Math.sin(this._halfpitch);
  59045. this._cosPitch = Math.cos(this._halfpitch);
  59046. this._sinYaw = Math.sin(this._halfyaw);
  59047. this._cosYaw = Math.cos(this._halfyaw);
  59048. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59049. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59050. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59051. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59052. };
  59053. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59054. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59055. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59056. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59057. this._rotMatrix.m[3] = 0;
  59058. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59059. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59060. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59061. this._rotMatrix.m[7] = 0;
  59062. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59063. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59064. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59065. this._rotMatrix.m[11] = 0;
  59066. this._rotMatrix.m[12] = 0;
  59067. this._rotMatrix.m[13] = 0;
  59068. this._rotMatrix.m[14] = 0;
  59069. this._rotMatrix.m[15] = 1.0;
  59070. };
  59071. /**
  59072. * Disposes the SPS.
  59073. */
  59074. SolidParticleSystem.prototype.dispose = function () {
  59075. this.mesh.dispose();
  59076. this.vars = null;
  59077. // drop references to internal big arrays for the GC
  59078. this._positions = null;
  59079. this._indices = null;
  59080. this._normals = null;
  59081. this._uvs = null;
  59082. this._colors = null;
  59083. this._indices32 = null;
  59084. this._positions32 = null;
  59085. this._normals32 = null;
  59086. this._fixedNormal32 = null;
  59087. this._uvs32 = null;
  59088. this._colors32 = null;
  59089. this.pickedParticles = null;
  59090. };
  59091. /**
  59092. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59093. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59094. * @returns the SPS.
  59095. */
  59096. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59097. if (!this._isVisibilityBoxLocked) {
  59098. this.mesh.refreshBoundingInfo();
  59099. }
  59100. return this;
  59101. };
  59102. /**
  59103. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59104. * @param size the size (float) of the visibility box
  59105. * note : this doesn't lock the SPS mesh bounding box.
  59106. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59107. */
  59108. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59109. var vis = size / 2;
  59110. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59111. };
  59112. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59113. /**
  59114. * Gets whether the SPS as always visible or not
  59115. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59116. */
  59117. get: function () {
  59118. return this._alwaysVisible;
  59119. },
  59120. /**
  59121. * Sets the SPS as always visible or not
  59122. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59123. */
  59124. set: function (val) {
  59125. this._alwaysVisible = val;
  59126. this.mesh.alwaysSelectAsActiveMesh = val;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59132. /**
  59133. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59135. */
  59136. get: function () {
  59137. return this._isVisibilityBoxLocked;
  59138. },
  59139. /**
  59140. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59141. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59142. */
  59143. set: function (val) {
  59144. this._isVisibilityBoxLocked = val;
  59145. var boundingInfo = this.mesh.getBoundingInfo();
  59146. boundingInfo.isLocked = val;
  59147. },
  59148. enumerable: true,
  59149. configurable: true
  59150. });
  59151. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59152. /**
  59153. * Gets if `setParticles()` computes the particle rotations or not.
  59154. * Default value : true. The SPS is faster when it's set to false.
  59155. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59156. */
  59157. get: function () {
  59158. return this._computeParticleRotation;
  59159. },
  59160. /**
  59161. * Tells to `setParticles()` to compute the particle rotations or not.
  59162. * Default value : true. The SPS is faster when it's set to false.
  59163. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59164. */
  59165. set: function (val) {
  59166. this._computeParticleRotation = val;
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59172. /**
  59173. * Gets if `setParticles()` computes the particle colors or not.
  59174. * Default value : true. The SPS is faster when it's set to false.
  59175. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59176. */
  59177. get: function () {
  59178. return this._computeParticleColor;
  59179. },
  59180. /**
  59181. * Tells to `setParticles()` to compute the particle colors or not.
  59182. * Default value : true. The SPS is faster when it's set to false.
  59183. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59184. */
  59185. set: function (val) {
  59186. this._computeParticleColor = val;
  59187. },
  59188. enumerable: true,
  59189. configurable: true
  59190. });
  59191. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59192. /**
  59193. * Gets if `setParticles()` computes the particle textures or not.
  59194. * Default value : true. The SPS is faster when it's set to false.
  59195. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59196. */
  59197. get: function () {
  59198. return this._computeParticleTexture;
  59199. },
  59200. set: function (val) {
  59201. this._computeParticleTexture = val;
  59202. },
  59203. enumerable: true,
  59204. configurable: true
  59205. });
  59206. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59207. /**
  59208. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59209. * Default value : false. The SPS is faster when it's set to false.
  59210. * Note : the particle custom vertex positions aren't stored values.
  59211. */
  59212. get: function () {
  59213. return this._computeParticleVertex;
  59214. },
  59215. /**
  59216. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59217. * Default value : false. The SPS is faster when it's set to false.
  59218. * Note : the particle custom vertex positions aren't stored values.
  59219. */
  59220. set: function (val) {
  59221. this._computeParticleVertex = val;
  59222. },
  59223. enumerable: true,
  59224. configurable: true
  59225. });
  59226. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59227. /**
  59228. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59229. */
  59230. get: function () {
  59231. return this._computeBoundingBox;
  59232. },
  59233. /**
  59234. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59235. */
  59236. set: function (val) {
  59237. this._computeBoundingBox = val;
  59238. },
  59239. enumerable: true,
  59240. configurable: true
  59241. });
  59242. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59243. /**
  59244. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59245. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59246. * Default : `true`
  59247. */
  59248. get: function () {
  59249. return this._depthSortParticles;
  59250. },
  59251. /**
  59252. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59253. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59254. * Default : `true`
  59255. */
  59256. set: function (val) {
  59257. this._depthSortParticles = val;
  59258. },
  59259. enumerable: true,
  59260. configurable: true
  59261. });
  59262. // =======================================================================
  59263. // Particle behavior logic
  59264. // these following methods may be overwritten by the user to fit his needs
  59265. /**
  59266. * This function does nothing. It may be overwritten to set all the particle first values.
  59267. * The SPS doesn't call this function, you may have to call it by your own.
  59268. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59269. */
  59270. SolidParticleSystem.prototype.initParticles = function () {
  59271. };
  59272. /**
  59273. * This function does nothing. It may be overwritten to recycle a particle.
  59274. * The SPS doesn't call this function, you may have to call it by your own.
  59275. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59276. * @param particle The particle to recycle
  59277. * @returns the recycled particle
  59278. */
  59279. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59280. return particle;
  59281. };
  59282. /**
  59283. * Updates a particle : this function should be overwritten by the user.
  59284. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59285. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59286. * @example : just set a particle position or velocity and recycle conditions
  59287. * @param particle The particle to update
  59288. * @returns the updated particle
  59289. */
  59290. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59291. return particle;
  59292. };
  59293. /**
  59294. * Updates a vertex of a particle : it can be overwritten by the user.
  59295. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59296. * @param particle the current particle
  59297. * @param vertex the current index of the current particle
  59298. * @param pt the index of the current vertex in the particle shape
  59299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59300. * @example : just set a vertex particle position
  59301. * @returns the updated vertex
  59302. */
  59303. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59304. return vertex;
  59305. };
  59306. /**
  59307. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59308. * This does nothing and may be overwritten by the user.
  59309. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59310. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59311. * @param update the boolean update value actually passed to setParticles()
  59312. */
  59313. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59314. };
  59315. /**
  59316. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59317. * This will be passed three parameters.
  59318. * This does nothing and may be overwritten by the user.
  59319. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59320. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59321. * @param update the boolean update value actually passed to setParticles()
  59322. */
  59323. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59324. };
  59325. return SolidParticleSystem;
  59326. }());
  59327. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59328. })(BABYLON || (BABYLON = {}));
  59329. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59330. var BABYLON;
  59331. (function (BABYLON) {
  59332. var ShaderMaterial = /** @class */ (function (_super) {
  59333. __extends(ShaderMaterial, _super);
  59334. function ShaderMaterial(name, scene, shaderPath, options) {
  59335. var _this = _super.call(this, name, scene) || this;
  59336. _this._textures = {};
  59337. _this._textureArrays = {};
  59338. _this._floats = {};
  59339. _this._ints = {};
  59340. _this._floatsArrays = {};
  59341. _this._colors3 = {};
  59342. _this._colors3Arrays = {};
  59343. _this._colors4 = {};
  59344. _this._vectors2 = {};
  59345. _this._vectors3 = {};
  59346. _this._vectors4 = {};
  59347. _this._matrices = {};
  59348. _this._matrices3x3 = {};
  59349. _this._matrices2x2 = {};
  59350. _this._vectors2Arrays = {};
  59351. _this._vectors3Arrays = {};
  59352. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59353. _this._shaderPath = shaderPath;
  59354. options.needAlphaBlending = options.needAlphaBlending || false;
  59355. options.needAlphaTesting = options.needAlphaTesting || false;
  59356. options.attributes = options.attributes || ["position", "normal", "uv"];
  59357. options.uniforms = options.uniforms || ["worldViewProjection"];
  59358. options.uniformBuffers = options.uniformBuffers || [];
  59359. options.samplers = options.samplers || [];
  59360. options.defines = options.defines || [];
  59361. _this._options = options;
  59362. return _this;
  59363. }
  59364. ShaderMaterial.prototype.getClassName = function () {
  59365. return "ShaderMaterial";
  59366. };
  59367. ShaderMaterial.prototype.needAlphaBlending = function () {
  59368. return this._options.needAlphaBlending;
  59369. };
  59370. ShaderMaterial.prototype.needAlphaTesting = function () {
  59371. return this._options.needAlphaTesting;
  59372. };
  59373. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59374. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59375. this._options.uniforms.push(uniformName);
  59376. }
  59377. };
  59378. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59379. if (this._options.samplers.indexOf(name) === -1) {
  59380. this._options.samplers.push(name);
  59381. }
  59382. this._textures[name] = texture;
  59383. return this;
  59384. };
  59385. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59386. if (this._options.samplers.indexOf(name) === -1) {
  59387. this._options.samplers.push(name);
  59388. }
  59389. this._checkUniform(name);
  59390. this._textureArrays[name] = textures;
  59391. return this;
  59392. };
  59393. ShaderMaterial.prototype.setFloat = function (name, value) {
  59394. this._checkUniform(name);
  59395. this._floats[name] = value;
  59396. return this;
  59397. };
  59398. ShaderMaterial.prototype.setInt = function (name, value) {
  59399. this._checkUniform(name);
  59400. this._ints[name] = value;
  59401. return this;
  59402. };
  59403. ShaderMaterial.prototype.setFloats = function (name, value) {
  59404. this._checkUniform(name);
  59405. this._floatsArrays[name] = value;
  59406. return this;
  59407. };
  59408. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59409. this._checkUniform(name);
  59410. this._colors3[name] = value;
  59411. return this;
  59412. };
  59413. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59414. this._checkUniform(name);
  59415. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59416. color.toArray(arr, arr.length);
  59417. return arr;
  59418. }, []);
  59419. return this;
  59420. };
  59421. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59422. this._checkUniform(name);
  59423. this._colors4[name] = value;
  59424. return this;
  59425. };
  59426. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59427. this._checkUniform(name);
  59428. this._vectors2[name] = value;
  59429. return this;
  59430. };
  59431. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59432. this._checkUniform(name);
  59433. this._vectors3[name] = value;
  59434. return this;
  59435. };
  59436. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59437. this._checkUniform(name);
  59438. this._vectors4[name] = value;
  59439. return this;
  59440. };
  59441. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59442. this._checkUniform(name);
  59443. this._matrices[name] = value;
  59444. return this;
  59445. };
  59446. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59447. this._checkUniform(name);
  59448. this._matrices3x3[name] = value;
  59449. return this;
  59450. };
  59451. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59452. this._checkUniform(name);
  59453. this._matrices2x2[name] = value;
  59454. return this;
  59455. };
  59456. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59457. this._checkUniform(name);
  59458. this._vectors2Arrays[name] = value;
  59459. return this;
  59460. };
  59461. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59462. this._checkUniform(name);
  59463. this._vectors3Arrays[name] = value;
  59464. return this;
  59465. };
  59466. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59467. if (!mesh) {
  59468. return true;
  59469. }
  59470. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59471. return false;
  59472. }
  59473. return false;
  59474. };
  59475. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59476. var scene = this.getScene();
  59477. var engine = scene.getEngine();
  59478. if (!this.checkReadyOnEveryCall) {
  59479. if (this._renderId === scene.getRenderId()) {
  59480. if (this._checkCache(scene, mesh, useInstances)) {
  59481. return true;
  59482. }
  59483. }
  59484. }
  59485. // Instances
  59486. var defines = [];
  59487. var attribs = [];
  59488. var fallbacks = new BABYLON.EffectFallbacks();
  59489. if (useInstances) {
  59490. defines.push("#define INSTANCES");
  59491. }
  59492. for (var index = 0; index < this._options.defines.length; index++) {
  59493. defines.push(this._options.defines[index]);
  59494. }
  59495. for (var index = 0; index < this._options.attributes.length; index++) {
  59496. attribs.push(this._options.attributes[index]);
  59497. }
  59498. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59499. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59500. defines.push("#define VERTEXCOLOR");
  59501. }
  59502. // Bones
  59503. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59506. if (mesh.numBoneInfluencers > 4) {
  59507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59509. }
  59510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59512. fallbacks.addCPUSkinningFallback(0, mesh);
  59513. if (this._options.uniforms.indexOf("mBones") === -1) {
  59514. this._options.uniforms.push("mBones");
  59515. }
  59516. }
  59517. else {
  59518. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59519. }
  59520. // Textures
  59521. for (var name in this._textures) {
  59522. if (!this._textures[name].isReady()) {
  59523. return false;
  59524. }
  59525. }
  59526. // Alpha test
  59527. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59528. defines.push("#define ALPHATEST");
  59529. }
  59530. var previousEffect = this._effect;
  59531. var join = defines.join("\n");
  59532. this._effect = engine.createEffect(this._shaderPath, {
  59533. attributes: attribs,
  59534. uniformsNames: this._options.uniforms,
  59535. uniformBuffersNames: this._options.uniformBuffers,
  59536. samplers: this._options.samplers,
  59537. defines: join,
  59538. fallbacks: fallbacks,
  59539. onCompiled: this.onCompiled,
  59540. onError: this.onError
  59541. }, engine);
  59542. if (!this._effect.isReady()) {
  59543. return false;
  59544. }
  59545. if (previousEffect !== this._effect) {
  59546. scene.resetCachedMaterial();
  59547. }
  59548. this._renderId = scene.getRenderId();
  59549. return true;
  59550. };
  59551. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59552. var scene = this.getScene();
  59553. if (!this._effect) {
  59554. return;
  59555. }
  59556. if (this._options.uniforms.indexOf("world") !== -1) {
  59557. this._effect.setMatrix("world", world);
  59558. }
  59559. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59560. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59561. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59562. }
  59563. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59564. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59565. }
  59566. };
  59567. ShaderMaterial.prototype.bind = function (world, mesh) {
  59568. // Std values
  59569. this.bindOnlyWorldMatrix(world);
  59570. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59571. if (this._options.uniforms.indexOf("view") !== -1) {
  59572. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59573. }
  59574. if (this._options.uniforms.indexOf("projection") !== -1) {
  59575. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59576. }
  59577. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59578. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59579. }
  59580. // Bones
  59581. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59582. var name;
  59583. // Texture
  59584. for (name in this._textures) {
  59585. this._effect.setTexture(name, this._textures[name]);
  59586. }
  59587. // Texture arrays
  59588. for (name in this._textureArrays) {
  59589. this._effect.setTextureArray(name, this._textureArrays[name]);
  59590. }
  59591. // Int
  59592. for (name in this._ints) {
  59593. this._effect.setInt(name, this._ints[name]);
  59594. }
  59595. // Float
  59596. for (name in this._floats) {
  59597. this._effect.setFloat(name, this._floats[name]);
  59598. }
  59599. // Floats
  59600. for (name in this._floatsArrays) {
  59601. this._effect.setArray(name, this._floatsArrays[name]);
  59602. }
  59603. // Color3
  59604. for (name in this._colors3) {
  59605. this._effect.setColor3(name, this._colors3[name]);
  59606. }
  59607. for (name in this._colors3Arrays) {
  59608. this._effect.setArray3(name, this._colors3Arrays[name]);
  59609. }
  59610. // Color4
  59611. for (name in this._colors4) {
  59612. var color = this._colors4[name];
  59613. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59614. }
  59615. // Vector2
  59616. for (name in this._vectors2) {
  59617. this._effect.setVector2(name, this._vectors2[name]);
  59618. }
  59619. // Vector3
  59620. for (name in this._vectors3) {
  59621. this._effect.setVector3(name, this._vectors3[name]);
  59622. }
  59623. // Vector4
  59624. for (name in this._vectors4) {
  59625. this._effect.setVector4(name, this._vectors4[name]);
  59626. }
  59627. // Matrix
  59628. for (name in this._matrices) {
  59629. this._effect.setMatrix(name, this._matrices[name]);
  59630. }
  59631. // Matrix 3x3
  59632. for (name in this._matrices3x3) {
  59633. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59634. }
  59635. // Matrix 2x2
  59636. for (name in this._matrices2x2) {
  59637. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59638. }
  59639. // Vector2Array
  59640. for (name in this._vectors2Arrays) {
  59641. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59642. }
  59643. // Vector3Array
  59644. for (name in this._vectors3Arrays) {
  59645. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59646. }
  59647. }
  59648. this._afterBind(mesh);
  59649. };
  59650. ShaderMaterial.prototype.getActiveTextures = function () {
  59651. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59652. for (var name in this._textures) {
  59653. activeTextures.push(this._textures[name]);
  59654. }
  59655. for (var name in this._textureArrays) {
  59656. var array = this._textureArrays[name];
  59657. for (var index = 0; index < array.length; index++) {
  59658. activeTextures.push(array[index]);
  59659. }
  59660. }
  59661. return activeTextures;
  59662. };
  59663. ShaderMaterial.prototype.hasTexture = function (texture) {
  59664. if (_super.prototype.hasTexture.call(this, texture)) {
  59665. return true;
  59666. }
  59667. for (var name in this._textures) {
  59668. if (this._textures[name] === texture) {
  59669. return true;
  59670. }
  59671. }
  59672. for (var name in this._textureArrays) {
  59673. var array = this._textureArrays[name];
  59674. for (var index = 0; index < array.length; index++) {
  59675. if (array[index] === texture) {
  59676. return true;
  59677. }
  59678. }
  59679. }
  59680. return false;
  59681. };
  59682. ShaderMaterial.prototype.clone = function (name) {
  59683. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59684. return newShaderMaterial;
  59685. };
  59686. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59687. if (forceDisposeTextures) {
  59688. var name;
  59689. for (name in this._textures) {
  59690. this._textures[name].dispose();
  59691. }
  59692. for (name in this._textureArrays) {
  59693. var array = this._textureArrays[name];
  59694. for (var index = 0; index < array.length; index++) {
  59695. array[index].dispose();
  59696. }
  59697. }
  59698. }
  59699. this._textures = {};
  59700. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59701. };
  59702. ShaderMaterial.prototype.serialize = function () {
  59703. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59704. serializationObject.customType = "BABYLON.ShaderMaterial";
  59705. serializationObject.options = this._options;
  59706. serializationObject.shaderPath = this._shaderPath;
  59707. var name;
  59708. // Texture
  59709. serializationObject.textures = {};
  59710. for (name in this._textures) {
  59711. serializationObject.textures[name] = this._textures[name].serialize();
  59712. }
  59713. // Texture arrays
  59714. serializationObject.textureArrays = {};
  59715. for (name in this._textureArrays) {
  59716. serializationObject.textureArrays[name] = [];
  59717. var array = this._textureArrays[name];
  59718. for (var index = 0; index < array.length; index++) {
  59719. serializationObject.textureArrays[name].push(array[index].serialize());
  59720. }
  59721. }
  59722. // Float
  59723. serializationObject.floats = {};
  59724. for (name in this._floats) {
  59725. serializationObject.floats[name] = this._floats[name];
  59726. }
  59727. // Float s
  59728. serializationObject.FloatArrays = {};
  59729. for (name in this._floatsArrays) {
  59730. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59731. }
  59732. // Color3
  59733. serializationObject.colors3 = {};
  59734. for (name in this._colors3) {
  59735. serializationObject.colors3[name] = this._colors3[name].asArray();
  59736. }
  59737. // Color3 array
  59738. serializationObject.colors3Arrays = {};
  59739. for (name in this._colors3Arrays) {
  59740. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59741. }
  59742. // Color4
  59743. serializationObject.colors4 = {};
  59744. for (name in this._colors4) {
  59745. serializationObject.colors4[name] = this._colors4[name].asArray();
  59746. }
  59747. // Vector2
  59748. serializationObject.vectors2 = {};
  59749. for (name in this._vectors2) {
  59750. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59751. }
  59752. // Vector3
  59753. serializationObject.vectors3 = {};
  59754. for (name in this._vectors3) {
  59755. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59756. }
  59757. // Vector4
  59758. serializationObject.vectors4 = {};
  59759. for (name in this._vectors4) {
  59760. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59761. }
  59762. // Matrix
  59763. serializationObject.matrices = {};
  59764. for (name in this._matrices) {
  59765. serializationObject.matrices[name] = this._matrices[name].asArray();
  59766. }
  59767. // Matrix 3x3
  59768. serializationObject.matrices3x3 = {};
  59769. for (name in this._matrices3x3) {
  59770. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59771. }
  59772. // Matrix 2x2
  59773. serializationObject.matrices2x2 = {};
  59774. for (name in this._matrices2x2) {
  59775. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59776. }
  59777. // Vector2Array
  59778. serializationObject.vectors2Arrays = {};
  59779. for (name in this._vectors2Arrays) {
  59780. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59781. }
  59782. // Vector3Array
  59783. serializationObject.vectors3Arrays = {};
  59784. for (name in this._vectors3Arrays) {
  59785. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59786. }
  59787. return serializationObject;
  59788. };
  59789. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59790. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59791. var name;
  59792. // Texture
  59793. for (name in source.textures) {
  59794. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59795. }
  59796. // Texture arrays
  59797. for (name in source.textureArrays) {
  59798. var array = source.textureArrays[name];
  59799. var textureArray = new Array();
  59800. for (var index = 0; index < array.length; index++) {
  59801. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59802. }
  59803. material.setTextureArray(name, textureArray);
  59804. }
  59805. // Float
  59806. for (name in source.floats) {
  59807. material.setFloat(name, source.floats[name]);
  59808. }
  59809. // Float s
  59810. for (name in source.floatsArrays) {
  59811. material.setFloats(name, source.floatsArrays[name]);
  59812. }
  59813. // Color3
  59814. for (name in source.colors3) {
  59815. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59816. }
  59817. // Color3 arrays
  59818. for (name in source.colors3Arrays) {
  59819. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59820. if (i % 3 === 0) {
  59821. arr.push([num]);
  59822. }
  59823. else {
  59824. arr[arr.length - 1].push(num);
  59825. }
  59826. return arr;
  59827. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59828. material.setColor3Array(name, colors);
  59829. }
  59830. // Color4
  59831. for (name in source.colors4) {
  59832. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59833. }
  59834. // Vector2
  59835. for (name in source.vectors2) {
  59836. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59837. }
  59838. // Vector3
  59839. for (name in source.vectors3) {
  59840. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59841. }
  59842. // Vector4
  59843. for (name in source.vectors4) {
  59844. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59845. }
  59846. // Matrix
  59847. for (name in source.matrices) {
  59848. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59849. }
  59850. // Matrix 3x3
  59851. for (name in source.matrices3x3) {
  59852. material.setMatrix3x3(name, source.matrices3x3[name]);
  59853. }
  59854. // Matrix 2x2
  59855. for (name in source.matrices2x2) {
  59856. material.setMatrix2x2(name, source.matrices2x2[name]);
  59857. }
  59858. // Vector2Array
  59859. for (name in source.vectors2Arrays) {
  59860. material.setArray2(name, source.vectors2Arrays[name]);
  59861. }
  59862. // Vector3Array
  59863. for (name in source.vectors3Arrays) {
  59864. material.setArray3(name, source.vectors3Arrays[name]);
  59865. }
  59866. return material;
  59867. };
  59868. return ShaderMaterial;
  59869. }(BABYLON.Material));
  59870. BABYLON.ShaderMaterial = ShaderMaterial;
  59871. })(BABYLON || (BABYLON = {}));
  59872. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59873. var BABYLON;
  59874. (function (BABYLON) {
  59875. var GroundMesh = /** @class */ (function (_super) {
  59876. __extends(GroundMesh, _super);
  59877. function GroundMesh(name, scene) {
  59878. var _this = _super.call(this, name, scene) || this;
  59879. _this.generateOctree = false;
  59880. return _this;
  59881. }
  59882. GroundMesh.prototype.getClassName = function () {
  59883. return "GroundMesh";
  59884. };
  59885. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59886. get: function () {
  59887. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59888. },
  59889. enumerable: true,
  59890. configurable: true
  59891. });
  59892. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59893. get: function () {
  59894. return this._subdivisionsX;
  59895. },
  59896. enumerable: true,
  59897. configurable: true
  59898. });
  59899. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59900. get: function () {
  59901. return this._subdivisionsY;
  59902. },
  59903. enumerable: true,
  59904. configurable: true
  59905. });
  59906. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59907. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59908. this._subdivisionsX = chunksCount;
  59909. this._subdivisionsY = chunksCount;
  59910. this.subdivide(chunksCount);
  59911. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59912. };
  59913. /**
  59914. * Returns a height (y) value in the Worl system :
  59915. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59916. * Returns the ground y position if (x, z) are outside the ground surface.
  59917. */
  59918. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59919. var world = this.getWorldMatrix();
  59920. var invMat = BABYLON.Tmp.Matrix[5];
  59921. world.invertToRef(invMat);
  59922. var tmpVect = BABYLON.Tmp.Vector3[8];
  59923. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59924. x = tmpVect.x;
  59925. z = tmpVect.z;
  59926. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59927. return this.position.y;
  59928. }
  59929. if (!this._heightQuads || this._heightQuads.length == 0) {
  59930. this._initHeightQuads();
  59931. this._computeHeightQuads();
  59932. }
  59933. var facet = this._getFacetAt(x, z);
  59934. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59935. // return y in the World system
  59936. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59937. return tmpVect.y;
  59938. };
  59939. /**
  59940. * Returns a normalized vector (Vector3) orthogonal to the ground
  59941. * at the ground coordinates (x, z) expressed in the World system.
  59942. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59943. */
  59944. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59945. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59946. this.getNormalAtCoordinatesToRef(x, z, normal);
  59947. return normal;
  59948. };
  59949. /**
  59950. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59951. * at the ground coordinates (x, z) expressed in the World system.
  59952. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59953. * Returns the GroundMesh.
  59954. */
  59955. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59956. var world = this.getWorldMatrix();
  59957. var tmpMat = BABYLON.Tmp.Matrix[5];
  59958. world.invertToRef(tmpMat);
  59959. var tmpVect = BABYLON.Tmp.Vector3[8];
  59960. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59961. x = tmpVect.x;
  59962. z = tmpVect.z;
  59963. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59964. return this;
  59965. }
  59966. if (!this._heightQuads || this._heightQuads.length == 0) {
  59967. this._initHeightQuads();
  59968. this._computeHeightQuads();
  59969. }
  59970. var facet = this._getFacetAt(x, z);
  59971. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59972. return this;
  59973. };
  59974. /**
  59975. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59976. * if the ground has been updated.
  59977. * This can be used in the render loop.
  59978. * Returns the GroundMesh.
  59979. */
  59980. GroundMesh.prototype.updateCoordinateHeights = function () {
  59981. if (!this._heightQuads || this._heightQuads.length == 0) {
  59982. this._initHeightQuads();
  59983. }
  59984. this._computeHeightQuads();
  59985. return this;
  59986. };
  59987. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59988. GroundMesh.prototype._getFacetAt = function (x, z) {
  59989. // retrieve col and row from x, z coordinates in the ground local system
  59990. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59991. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59992. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59993. var facet;
  59994. if (z < quad.slope.x * x + quad.slope.y) {
  59995. facet = quad.facet1;
  59996. }
  59997. else {
  59998. facet = quad.facet2;
  59999. }
  60000. return facet;
  60001. };
  60002. // Creates and populates the heightMap array with "facet" elements :
  60003. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60004. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60005. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60006. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60007. // Returns the GroundMesh.
  60008. GroundMesh.prototype._initHeightQuads = function () {
  60009. var subdivisionsX = this._subdivisionsX;
  60010. var subdivisionsY = this._subdivisionsY;
  60011. this._heightQuads = new Array();
  60012. for (var row = 0; row < subdivisionsY; row++) {
  60013. for (var col = 0; col < subdivisionsX; col++) {
  60014. 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) };
  60015. this._heightQuads[row * subdivisionsX + col] = quad;
  60016. }
  60017. }
  60018. return this;
  60019. };
  60020. // Compute each quad element values and update the the heightMap array :
  60021. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60022. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60023. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60024. // Returns the GroundMesh.
  60025. GroundMesh.prototype._computeHeightQuads = function () {
  60026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60027. if (!positions) {
  60028. return this;
  60029. }
  60030. var v1 = BABYLON.Tmp.Vector3[3];
  60031. var v2 = BABYLON.Tmp.Vector3[2];
  60032. var v3 = BABYLON.Tmp.Vector3[1];
  60033. var v4 = BABYLON.Tmp.Vector3[0];
  60034. var v1v2 = BABYLON.Tmp.Vector3[4];
  60035. var v1v3 = BABYLON.Tmp.Vector3[5];
  60036. var v1v4 = BABYLON.Tmp.Vector3[6];
  60037. var norm1 = BABYLON.Tmp.Vector3[7];
  60038. var norm2 = BABYLON.Tmp.Vector3[8];
  60039. var i = 0;
  60040. var j = 0;
  60041. var k = 0;
  60042. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60043. var h = 0;
  60044. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60045. var d2 = 0;
  60046. var subdivisionsX = this._subdivisionsX;
  60047. var subdivisionsY = this._subdivisionsY;
  60048. for (var row = 0; row < subdivisionsY; row++) {
  60049. for (var col = 0; col < subdivisionsX; col++) {
  60050. i = col * 3;
  60051. j = row * (subdivisionsX + 1) * 3;
  60052. k = (row + 1) * (subdivisionsX + 1) * 3;
  60053. v1.x = positions[j + i];
  60054. v1.y = positions[j + i + 1];
  60055. v1.z = positions[j + i + 2];
  60056. v2.x = positions[j + i + 3];
  60057. v2.y = positions[j + i + 4];
  60058. v2.z = positions[j + i + 5];
  60059. v3.x = positions[k + i];
  60060. v3.y = positions[k + i + 1];
  60061. v3.z = positions[k + i + 2];
  60062. v4.x = positions[k + i + 3];
  60063. v4.y = positions[k + i + 4];
  60064. v4.z = positions[k + i + 5];
  60065. // 2D slope V1V4
  60066. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60067. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60068. // facet equations :
  60069. // we compute each facet normal vector
  60070. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60071. // we compute the value d by applying the equation to v1 which belongs to the plane
  60072. // then we store the facet equation in a Vector4
  60073. v2.subtractToRef(v1, v1v2);
  60074. v3.subtractToRef(v1, v1v3);
  60075. v4.subtractToRef(v1, v1v4);
  60076. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60077. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60078. norm1.normalize();
  60079. norm2.normalize();
  60080. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60081. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60082. var quad = this._heightQuads[row * subdivisionsX + col];
  60083. quad.slope.copyFromFloats(cd, h);
  60084. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60085. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60086. }
  60087. }
  60088. return this;
  60089. };
  60090. GroundMesh.prototype.serialize = function (serializationObject) {
  60091. _super.prototype.serialize.call(this, serializationObject);
  60092. serializationObject.subdivisionsX = this._subdivisionsX;
  60093. serializationObject.subdivisionsY = this._subdivisionsY;
  60094. serializationObject.minX = this._minX;
  60095. serializationObject.maxX = this._maxX;
  60096. serializationObject.minZ = this._minZ;
  60097. serializationObject.maxZ = this._maxZ;
  60098. serializationObject.width = this._width;
  60099. serializationObject.height = this._height;
  60100. };
  60101. GroundMesh.Parse = function (parsedMesh, scene) {
  60102. var result = new GroundMesh(parsedMesh.name, scene);
  60103. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60104. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60105. result._minX = parsedMesh.minX;
  60106. result._maxX = parsedMesh.maxX;
  60107. result._minZ = parsedMesh.minZ;
  60108. result._maxZ = parsedMesh.maxZ;
  60109. result._width = parsedMesh.width;
  60110. result._height = parsedMesh.height;
  60111. return result;
  60112. };
  60113. return GroundMesh;
  60114. }(BABYLON.Mesh));
  60115. BABYLON.GroundMesh = GroundMesh;
  60116. })(BABYLON || (BABYLON = {}));
  60117. //# sourceMappingURL=babylon.groundMesh.js.map
  60118. var BABYLON;
  60119. (function (BABYLON) {
  60120. /**
  60121. * Creates an instance based on a source mesh.
  60122. */
  60123. var InstancedMesh = /** @class */ (function (_super) {
  60124. __extends(InstancedMesh, _super);
  60125. function InstancedMesh(name, source) {
  60126. var _this = _super.call(this, name, source.getScene()) || this;
  60127. source.instances.push(_this);
  60128. _this._sourceMesh = source;
  60129. _this.position.copyFrom(source.position);
  60130. _this.rotation.copyFrom(source.rotation);
  60131. _this.scaling.copyFrom(source.scaling);
  60132. if (source.rotationQuaternion) {
  60133. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60134. }
  60135. _this.infiniteDistance = source.infiniteDistance;
  60136. _this.setPivotMatrix(source.getPivotMatrix());
  60137. _this.refreshBoundingInfo();
  60138. _this._syncSubMeshes();
  60139. return _this;
  60140. }
  60141. /**
  60142. * Returns the string "InstancedMesh".
  60143. */
  60144. InstancedMesh.prototype.getClassName = function () {
  60145. return "InstancedMesh";
  60146. };
  60147. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60148. // Methods
  60149. get: function () {
  60150. return this._sourceMesh.receiveShadows;
  60151. },
  60152. enumerable: true,
  60153. configurable: true
  60154. });
  60155. Object.defineProperty(InstancedMesh.prototype, "material", {
  60156. get: function () {
  60157. return this._sourceMesh.material;
  60158. },
  60159. enumerable: true,
  60160. configurable: true
  60161. });
  60162. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60163. get: function () {
  60164. return this._sourceMesh.visibility;
  60165. },
  60166. enumerable: true,
  60167. configurable: true
  60168. });
  60169. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60170. get: function () {
  60171. return this._sourceMesh.skeleton;
  60172. },
  60173. enumerable: true,
  60174. configurable: true
  60175. });
  60176. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60177. get: function () {
  60178. return this._sourceMesh.renderingGroupId;
  60179. },
  60180. set: function (value) {
  60181. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60182. return;
  60183. }
  60184. //no-op with warning
  60185. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. /**
  60191. * Returns the total number of vertices (integer).
  60192. */
  60193. InstancedMesh.prototype.getTotalVertices = function () {
  60194. return this._sourceMesh.getTotalVertices();
  60195. };
  60196. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60197. get: function () {
  60198. return this._sourceMesh;
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. /**
  60204. * Is this node ready to be used/rendered
  60205. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60206. * @return {boolean} is it ready
  60207. */
  60208. InstancedMesh.prototype.isReady = function (completeCheck) {
  60209. if (completeCheck === void 0) { completeCheck = false; }
  60210. return this._sourceMesh.isReady(completeCheck, true);
  60211. };
  60212. /**
  60213. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60214. */
  60215. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60216. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60217. };
  60218. /**
  60219. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60220. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60221. * The `data` are either a numeric array either a Float32Array.
  60222. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60223. * 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).
  60224. * Note that a new underlying VertexBuffer object is created each call.
  60225. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60226. *
  60227. * Possible `kind` values :
  60228. * - BABYLON.VertexBuffer.PositionKind
  60229. * - BABYLON.VertexBuffer.UVKind
  60230. * - BABYLON.VertexBuffer.UV2Kind
  60231. * - BABYLON.VertexBuffer.UV3Kind
  60232. * - BABYLON.VertexBuffer.UV4Kind
  60233. * - BABYLON.VertexBuffer.UV5Kind
  60234. * - BABYLON.VertexBuffer.UV6Kind
  60235. * - BABYLON.VertexBuffer.ColorKind
  60236. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60237. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60238. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60239. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60240. *
  60241. * Returns the Mesh.
  60242. */
  60243. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60244. if (this.sourceMesh) {
  60245. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60246. }
  60247. return this.sourceMesh;
  60248. };
  60249. /**
  60250. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60251. * If the mesh has no geometry, it is simply returned as it is.
  60252. * The `data` are either a numeric array either a Float32Array.
  60253. * No new underlying VertexBuffer object is created.
  60254. * 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.
  60255. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60256. *
  60257. * Possible `kind` values :
  60258. * - BABYLON.VertexBuffer.PositionKind
  60259. * - BABYLON.VertexBuffer.UVKind
  60260. * - BABYLON.VertexBuffer.UV2Kind
  60261. * - BABYLON.VertexBuffer.UV3Kind
  60262. * - BABYLON.VertexBuffer.UV4Kind
  60263. * - BABYLON.VertexBuffer.UV5Kind
  60264. * - BABYLON.VertexBuffer.UV6Kind
  60265. * - BABYLON.VertexBuffer.ColorKind
  60266. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60267. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60268. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60269. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60270. *
  60271. * Returns the Mesh.
  60272. */
  60273. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60274. if (this.sourceMesh) {
  60275. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60276. }
  60277. return this.sourceMesh;
  60278. };
  60279. /**
  60280. * Sets the mesh indices.
  60281. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60282. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60283. * This method creates a new index buffer each call.
  60284. * Returns the Mesh.
  60285. */
  60286. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60287. if (totalVertices === void 0) { totalVertices = null; }
  60288. if (this.sourceMesh) {
  60289. this.sourceMesh.setIndices(indices, totalVertices);
  60290. }
  60291. return this.sourceMesh;
  60292. };
  60293. /**
  60294. * Boolean : True if the mesh owns the requested kind of data.
  60295. */
  60296. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60297. return this._sourceMesh.isVerticesDataPresent(kind);
  60298. };
  60299. /**
  60300. * Returns an array of indices (IndicesArray).
  60301. */
  60302. InstancedMesh.prototype.getIndices = function () {
  60303. return this._sourceMesh.getIndices();
  60304. };
  60305. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60306. get: function () {
  60307. return this._sourceMesh._positions;
  60308. },
  60309. enumerable: true,
  60310. configurable: true
  60311. });
  60312. /**
  60313. * Sets a new updated BoundingInfo to the mesh.
  60314. * Returns the mesh.
  60315. */
  60316. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60317. var meshBB = this._sourceMesh.getBoundingInfo();
  60318. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60319. this._updateBoundingInfo();
  60320. return this;
  60321. };
  60322. InstancedMesh.prototype._preActivate = function () {
  60323. if (this._currentLOD) {
  60324. this._currentLOD._preActivate();
  60325. }
  60326. return this;
  60327. };
  60328. InstancedMesh.prototype._activate = function (renderId) {
  60329. if (this._currentLOD) {
  60330. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60331. }
  60332. return this;
  60333. };
  60334. /**
  60335. * Returns the current associated LOD AbstractMesh.
  60336. */
  60337. InstancedMesh.prototype.getLOD = function (camera) {
  60338. if (!camera) {
  60339. return this;
  60340. }
  60341. var boundingInfo = this.getBoundingInfo();
  60342. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60343. if (this._currentLOD === this.sourceMesh) {
  60344. return this;
  60345. }
  60346. return this._currentLOD;
  60347. };
  60348. InstancedMesh.prototype._syncSubMeshes = function () {
  60349. this.releaseSubMeshes();
  60350. if (this._sourceMesh.subMeshes) {
  60351. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60352. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60353. }
  60354. }
  60355. return this;
  60356. };
  60357. InstancedMesh.prototype._generatePointsArray = function () {
  60358. return this._sourceMesh._generatePointsArray();
  60359. };
  60360. /**
  60361. * Creates a new InstancedMesh from the current mesh.
  60362. * - name (string) : the cloned mesh name
  60363. * - newParent (optional Node) : the optional Node to parent the clone to.
  60364. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60365. *
  60366. * Returns the clone.
  60367. */
  60368. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60369. var result = this._sourceMesh.createInstance(name);
  60370. // Deep copy
  60371. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60372. // Bounding info
  60373. this.refreshBoundingInfo();
  60374. // Parent
  60375. if (newParent) {
  60376. result.parent = newParent;
  60377. }
  60378. if (!doNotCloneChildren) {
  60379. // Children
  60380. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60381. var mesh = this.getScene().meshes[index];
  60382. if (mesh.parent === this) {
  60383. mesh.clone(mesh.name, result);
  60384. }
  60385. }
  60386. }
  60387. result.computeWorldMatrix(true);
  60388. return result;
  60389. };
  60390. /**
  60391. * Disposes the InstancedMesh.
  60392. * Returns nothing.
  60393. */
  60394. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60395. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60396. // Remove from mesh
  60397. var index = this._sourceMesh.instances.indexOf(this);
  60398. this._sourceMesh.instances.splice(index, 1);
  60399. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60400. };
  60401. return InstancedMesh;
  60402. }(BABYLON.AbstractMesh));
  60403. BABYLON.InstancedMesh = InstancedMesh;
  60404. })(BABYLON || (BABYLON = {}));
  60405. //# sourceMappingURL=babylon.instancedMesh.js.map
  60406. var BABYLON;
  60407. (function (BABYLON) {
  60408. var LinesMesh = /** @class */ (function (_super) {
  60409. __extends(LinesMesh, _super);
  60410. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60411. if (scene === void 0) { scene = null; }
  60412. if (parent === void 0) { parent = null; }
  60413. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60414. _this.useVertexColor = useVertexColor;
  60415. _this.useVertexAlpha = useVertexAlpha;
  60416. _this.color = new BABYLON.Color3(1, 1, 1);
  60417. _this.alpha = 1;
  60418. if (source) {
  60419. _this.color = source.color.clone();
  60420. _this.alpha = source.alpha;
  60421. _this.useVertexColor = source.useVertexColor;
  60422. _this.useVertexAlpha = source.useVertexAlpha;
  60423. }
  60424. _this._intersectionThreshold = 0.1;
  60425. var defines = [];
  60426. var options = {
  60427. attributes: [BABYLON.VertexBuffer.PositionKind],
  60428. uniforms: ["world", "viewProjection"],
  60429. needAlphaBlending: true,
  60430. defines: defines
  60431. };
  60432. if (useVertexAlpha === false) {
  60433. options.needAlphaBlending = false;
  60434. }
  60435. if (!useVertexColor) {
  60436. options.uniforms.push("color");
  60437. }
  60438. else {
  60439. options.defines.push("#define VERTEXCOLOR");
  60440. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60441. }
  60442. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60443. return _this;
  60444. }
  60445. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60446. /**
  60447. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60448. * This margin is expressed in world space coordinates, so its value may vary.
  60449. * Default value is 0.1
  60450. * @returns the intersection Threshold value.
  60451. */
  60452. get: function () {
  60453. return this._intersectionThreshold;
  60454. },
  60455. /**
  60456. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60457. * This margin is expressed in world space coordinates, so its value may vary.
  60458. * @param value the new threshold to apply
  60459. */
  60460. set: function (value) {
  60461. if (this._intersectionThreshold === value) {
  60462. return;
  60463. }
  60464. this._intersectionThreshold = value;
  60465. if (this.geometry) {
  60466. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60467. }
  60468. },
  60469. enumerable: true,
  60470. configurable: true
  60471. });
  60472. /**
  60473. * Returns the string "LineMesh"
  60474. */
  60475. LinesMesh.prototype.getClassName = function () {
  60476. return "LinesMesh";
  60477. };
  60478. Object.defineProperty(LinesMesh.prototype, "material", {
  60479. get: function () {
  60480. return this._colorShader;
  60481. },
  60482. set: function (value) {
  60483. // Do nothing
  60484. },
  60485. enumerable: true,
  60486. configurable: true
  60487. });
  60488. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60489. get: function () {
  60490. return false;
  60491. },
  60492. enumerable: true,
  60493. configurable: true
  60494. });
  60495. LinesMesh.prototype.createInstance = function (name) {
  60496. throw new Error("LinesMeshes do not support createInstance.");
  60497. };
  60498. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60499. if (!this._geometry) {
  60500. return this;
  60501. }
  60502. // VBOs
  60503. this._geometry._bind(this._colorShader.getEffect());
  60504. // Color
  60505. if (!this.useVertexColor) {
  60506. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60507. }
  60508. return this;
  60509. };
  60510. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60511. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60512. return this;
  60513. }
  60514. var engine = this.getScene().getEngine();
  60515. // Draw order
  60516. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60517. return this;
  60518. };
  60519. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60520. this._colorShader.dispose();
  60521. _super.prototype.dispose.call(this, doNotRecurse);
  60522. };
  60523. /**
  60524. * Returns a new LineMesh object cloned from the current one.
  60525. */
  60526. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60527. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60528. };
  60529. return LinesMesh;
  60530. }(BABYLON.Mesh));
  60531. BABYLON.LinesMesh = LinesMesh;
  60532. })(BABYLON || (BABYLON = {}));
  60533. //# sourceMappingURL=babylon.linesMesh.js.map
  60534. var BABYLON;
  60535. (function (BABYLON) {
  60536. /**
  60537. * Class containing static functions to help procedurally build meshes
  60538. */
  60539. var MeshBuilder = /** @class */ (function () {
  60540. function MeshBuilder() {
  60541. }
  60542. MeshBuilder.updateSideOrientation = function (orientation) {
  60543. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60544. return BABYLON.Mesh.DOUBLESIDE;
  60545. }
  60546. if (orientation === undefined || orientation === null) {
  60547. return BABYLON.Mesh.FRONTSIDE;
  60548. }
  60549. return orientation;
  60550. };
  60551. /**
  60552. * Creates a box mesh
  60553. * * The parameter `size` sets the size (float) of each box side (default 1)
  60554. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60555. * * 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)
  60556. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60557. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60558. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60559. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60560. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60561. * @param name defines the name of the mesh
  60562. * @param options defines the options used to create the mesh
  60563. * @param scene defines the hosting scene
  60564. * @returns the box mesh
  60565. */
  60566. MeshBuilder.CreateBox = function (name, options, scene) {
  60567. if (scene === void 0) { scene = null; }
  60568. var box = new BABYLON.Mesh(name, scene);
  60569. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60570. box._originalBuilderSideOrientation = options.sideOrientation;
  60571. var vertexData = BABYLON.VertexData.CreateBox(options);
  60572. vertexData.applyToMesh(box, options.updatable);
  60573. return box;
  60574. };
  60575. /**
  60576. * Creates a sphere mesh
  60577. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60578. * * 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`)
  60579. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60580. * * 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
  60581. * * 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)
  60582. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60583. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60584. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60585. * @param name defines the name of the mesh
  60586. * @param options defines the options used to create the mesh
  60587. * @param scene defines the hosting scene
  60588. * @returns the sphere mesh
  60589. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60590. */
  60591. MeshBuilder.CreateSphere = function (name, options, scene) {
  60592. var sphere = new BABYLON.Mesh(name, scene);
  60593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60594. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60595. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60596. vertexData.applyToMesh(sphere, options.updatable);
  60597. return sphere;
  60598. };
  60599. /**
  60600. * Creates a plane polygonal mesh. By default, this is a disc
  60601. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60602. * * 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
  60603. * * 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
  60604. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60605. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60606. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60607. * @param name defines the name of the mesh
  60608. * @param options defines the options used to create the mesh
  60609. * @param scene defines the hosting scene
  60610. * @returns the plane polygonal mesh
  60611. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60612. */
  60613. MeshBuilder.CreateDisc = function (name, options, scene) {
  60614. if (scene === void 0) { scene = null; }
  60615. var disc = new BABYLON.Mesh(name, scene);
  60616. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60617. disc._originalBuilderSideOrientation = options.sideOrientation;
  60618. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60619. vertexData.applyToMesh(disc, options.updatable);
  60620. return disc;
  60621. };
  60622. /**
  60623. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60624. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60625. * * 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`)
  60626. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60627. * * 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
  60628. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60629. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60630. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60631. * @param name defines the name of the mesh
  60632. * @param options defines the options used to create the mesh
  60633. * @param scene defines the hosting scene
  60634. * @returns the icosahedron mesh
  60635. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60636. */
  60637. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60638. var sphere = new BABYLON.Mesh(name, scene);
  60639. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60640. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60641. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60642. vertexData.applyToMesh(sphere, options.updatable);
  60643. return sphere;
  60644. };
  60645. ;
  60646. /**
  60647. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60648. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60649. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60650. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60651. * * 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
  60652. * * 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
  60653. * * 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
  60654. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60655. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60656. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60657. * * 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
  60658. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60659. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60660. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60661. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60662. * @param name defines the name of the mesh
  60663. * @param options defines the options used to create the mesh
  60664. * @param scene defines the hosting scene
  60665. * @returns the ribbon mesh
  60666. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60667. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60668. */
  60669. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60670. if (scene === void 0) { scene = null; }
  60671. var pathArray = options.pathArray;
  60672. var closeArray = options.closeArray;
  60673. var closePath = options.closePath;
  60674. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60675. var instance = options.instance;
  60676. var updatable = options.updatable;
  60677. if (instance) { // existing ribbon instance update
  60678. // positionFunction : ribbon case
  60679. // only pathArray and sideOrientation parameters are taken into account for positions update
  60680. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60681. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60682. var positionFunction = function (positions) {
  60683. var minlg = pathArray[0].length;
  60684. var i = 0;
  60685. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60686. for (var si = 1; si <= ns; si++) {
  60687. for (var p = 0; p < pathArray.length; p++) {
  60688. var path = pathArray[p];
  60689. var l = path.length;
  60690. minlg = (minlg < l) ? minlg : l;
  60691. var j = 0;
  60692. while (j < minlg) {
  60693. positions[i] = path[j].x;
  60694. positions[i + 1] = path[j].y;
  60695. positions[i + 2] = path[j].z;
  60696. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60697. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60698. }
  60699. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60700. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60701. }
  60702. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60703. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60704. }
  60705. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60706. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60707. }
  60708. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60709. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60710. }
  60711. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60712. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60713. }
  60714. j++;
  60715. i += 3;
  60716. }
  60717. if (instance._closePath) {
  60718. positions[i] = path[0].x;
  60719. positions[i + 1] = path[0].y;
  60720. positions[i + 2] = path[0].z;
  60721. i += 3;
  60722. }
  60723. }
  60724. }
  60725. };
  60726. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60727. positionFunction(positions);
  60728. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60729. instance._boundingInfo.update(instance._worldMatrix);
  60730. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60731. if (options.colors) {
  60732. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60733. for (var c = 0; c < options.colors.length; c++) {
  60734. colors[c * 4] = options.colors[c].r;
  60735. colors[c * 4 + 1] = options.colors[c].g;
  60736. colors[c * 4 + 2] = options.colors[c].b;
  60737. colors[c * 4 + 3] = options.colors[c].a;
  60738. }
  60739. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60740. }
  60741. if (options.uvs) {
  60742. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60743. for (var i = 0; i < options.uvs.length; i++) {
  60744. uvs[i * 2] = options.uvs[i].x;
  60745. uvs[i * 2 + 1] = options.uvs[i].y;
  60746. }
  60747. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60748. }
  60749. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60750. var indices = instance.getIndices();
  60751. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60752. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60753. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60754. if (instance._closePath) {
  60755. var indexFirst = 0;
  60756. var indexLast = 0;
  60757. for (var p = 0; p < pathArray.length; p++) {
  60758. indexFirst = instance._idx[p] * 3;
  60759. if (p + 1 < pathArray.length) {
  60760. indexLast = (instance._idx[p + 1] - 1) * 3;
  60761. }
  60762. else {
  60763. indexLast = normals.length - 3;
  60764. }
  60765. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60766. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60767. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60768. normals[indexLast] = normals[indexFirst];
  60769. normals[indexLast + 1] = normals[indexFirst + 1];
  60770. normals[indexLast + 2] = normals[indexFirst + 2];
  60771. }
  60772. }
  60773. if (!(instance.areNormalsFrozen)) {
  60774. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60775. }
  60776. }
  60777. return instance;
  60778. }
  60779. else { // new ribbon creation
  60780. var ribbon = new BABYLON.Mesh(name, scene);
  60781. ribbon._originalBuilderSideOrientation = sideOrientation;
  60782. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60783. if (closePath) {
  60784. ribbon._idx = vertexData._idx;
  60785. }
  60786. ribbon._closePath = closePath;
  60787. ribbon._closeArray = closeArray;
  60788. vertexData.applyToMesh(ribbon, updatable);
  60789. return ribbon;
  60790. }
  60791. };
  60792. /**
  60793. * Creates a cylinder or a cone mesh
  60794. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60795. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60796. * * 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.
  60797. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60798. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60799. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60800. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60801. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60802. * * 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).
  60803. * * 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
  60804. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60805. * * 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
  60806. * * 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.
  60807. * * If `enclose` is false, a ring surface is one element.
  60808. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60809. * * 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
  60810. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60811. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60812. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60813. * @param name defines the name of the mesh
  60814. * @param options defines the options used to create the mesh
  60815. * @param scene defines the hosting scene
  60816. * @returns the cylinder mesh
  60817. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60818. */
  60819. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60820. var cylinder = new BABYLON.Mesh(name, scene);
  60821. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60822. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60823. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60824. vertexData.applyToMesh(cylinder, options.updatable);
  60825. return cylinder;
  60826. };
  60827. /**
  60828. * Creates a torus mesh
  60829. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60830. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60831. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60832. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60833. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60834. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60835. * @param name defines the name of the mesh
  60836. * @param options defines the options used to create the mesh
  60837. * @param scene defines the hosting scene
  60838. * @returns the torus mesh
  60839. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60840. */
  60841. MeshBuilder.CreateTorus = function (name, options, scene) {
  60842. var torus = new BABYLON.Mesh(name, scene);
  60843. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60844. torus._originalBuilderSideOrientation = options.sideOrientation;
  60845. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60846. vertexData.applyToMesh(torus, options.updatable);
  60847. return torus;
  60848. };
  60849. /**
  60850. * Creates a torus knot mesh
  60851. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60852. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60853. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60854. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60855. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60856. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60857. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60858. * @param name defines the name of the mesh
  60859. * @param options defines the options used to create the mesh
  60860. * @param scene defines the hosting scene
  60861. * @returns the torus knot mesh
  60862. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60863. */
  60864. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60865. var torusKnot = new BABYLON.Mesh(name, scene);
  60866. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60867. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60868. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60869. vertexData.applyToMesh(torusKnot, options.updatable);
  60870. return torusKnot;
  60871. };
  60872. /**
  60873. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60874. * * 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
  60875. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60876. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60877. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60878. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60879. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60880. * * 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
  60881. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60882. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60883. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60884. * @param name defines the name of the new line system
  60885. * @param options defines the options used to create the line system
  60886. * @param scene defines the hosting scene
  60887. * @returns a new line system mesh
  60888. */
  60889. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60890. var instance = options.instance;
  60891. var lines = options.lines;
  60892. var colors = options.colors;
  60893. if (instance) { // lines update
  60894. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60895. var vertexColor;
  60896. var lineColors;
  60897. if (colors) {
  60898. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60899. }
  60900. var i = 0;
  60901. var c = 0;
  60902. for (var l = 0; l < lines.length; l++) {
  60903. var points = lines[l];
  60904. for (var p = 0; p < points.length; p++) {
  60905. positions[i] = points[p].x;
  60906. positions[i + 1] = points[p].y;
  60907. positions[i + 2] = points[p].z;
  60908. if (colors && vertexColor) {
  60909. lineColors = colors[l];
  60910. vertexColor[c] = lineColors[p].r;
  60911. vertexColor[c + 1] = lineColors[p].g;
  60912. vertexColor[c + 2] = lineColors[p].b;
  60913. vertexColor[c + 3] = lineColors[p].a;
  60914. c += 4;
  60915. }
  60916. i += 3;
  60917. }
  60918. }
  60919. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60920. if (colors && vertexColor) {
  60921. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60922. }
  60923. return instance;
  60924. }
  60925. // line system creation
  60926. var useVertexColor = (colors) ? true : false;
  60927. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60928. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60929. vertexData.applyToMesh(lineSystem, options.updatable);
  60930. return lineSystem;
  60931. };
  60932. /**
  60933. * Creates a line mesh
  60934. * 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
  60935. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60936. * * The parameter `points` is an array successive Vector3
  60937. * * 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
  60938. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60939. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60940. * * When updating an instance, remember that only point positions can change, not the number of points
  60941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60942. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60943. * @param name defines the name of the new line system
  60944. * @param options defines the options used to create the line system
  60945. * @param scene defines the hosting scene
  60946. * @returns a new line mesh
  60947. */
  60948. MeshBuilder.CreateLines = function (name, options, scene) {
  60949. if (scene === void 0) { scene = null; }
  60950. var colors = (options.colors) ? [options.colors] : null;
  60951. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60952. return lines;
  60953. };
  60954. /**
  60955. * Creates a dashed line mesh
  60956. * * 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
  60957. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60958. * * The parameter `points` is an array successive Vector3
  60959. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60960. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60961. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60962. * * 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
  60963. * * When updating an instance, remember that only point positions can change, not the number of points
  60964. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60965. * @param name defines the name of the mesh
  60966. * @param options defines the options used to create the mesh
  60967. * @param scene defines the hosting scene
  60968. * @returns the dashed line mesh
  60969. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60970. */
  60971. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60972. if (scene === void 0) { scene = null; }
  60973. var points = options.points;
  60974. var instance = options.instance;
  60975. var gapSize = options.gapSize || 1;
  60976. var dashSize = options.dashSize || 3;
  60977. if (instance) { // dashed lines update
  60978. var positionFunction = function (positions) {
  60979. var curvect = BABYLON.Vector3.Zero();
  60980. var nbSeg = positions.length / 6;
  60981. var lg = 0;
  60982. var nb = 0;
  60983. var shft = 0;
  60984. var dashshft = 0;
  60985. var curshft = 0;
  60986. var p = 0;
  60987. var i = 0;
  60988. var j = 0;
  60989. for (i = 0; i < points.length - 1; i++) {
  60990. points[i + 1].subtractToRef(points[i], curvect);
  60991. lg += curvect.length();
  60992. }
  60993. shft = lg / nbSeg;
  60994. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60995. for (i = 0; i < points.length - 1; i++) {
  60996. points[i + 1].subtractToRef(points[i], curvect);
  60997. nb = Math.floor(curvect.length() / shft);
  60998. curvect.normalize();
  60999. j = 0;
  61000. while (j < nb && p < positions.length) {
  61001. curshft = shft * j;
  61002. positions[p] = points[i].x + curshft * curvect.x;
  61003. positions[p + 1] = points[i].y + curshft * curvect.y;
  61004. positions[p + 2] = points[i].z + curshft * curvect.z;
  61005. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61006. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61007. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61008. p += 6;
  61009. j++;
  61010. }
  61011. }
  61012. while (p < positions.length) {
  61013. positions[p] = points[i].x;
  61014. positions[p + 1] = points[i].y;
  61015. positions[p + 2] = points[i].z;
  61016. p += 3;
  61017. }
  61018. };
  61019. instance.updateMeshPositions(positionFunction, false);
  61020. return instance;
  61021. }
  61022. // dashed lines creation
  61023. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61024. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61025. vertexData.applyToMesh(dashedLines, options.updatable);
  61026. dashedLines.dashSize = dashSize;
  61027. dashedLines.gapSize = gapSize;
  61028. return dashedLines;
  61029. };
  61030. /**
  61031. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61032. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61033. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61034. * * 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.
  61035. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61036. * * 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
  61037. * * 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
  61038. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61039. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61040. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61041. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61042. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61043. * @param name defines the name of the mesh
  61044. * @param options defines the options used to create the mesh
  61045. * @param scene defines the hosting scene
  61046. * @returns the extruded shape mesh
  61047. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61048. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61049. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61050. */
  61051. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61052. if (scene === void 0) { scene = null; }
  61053. var path = options.path;
  61054. var shape = options.shape;
  61055. var scale = options.scale || 1;
  61056. var rotation = options.rotation || 0;
  61057. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61058. var updatable = options.updatable;
  61059. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61060. var instance = options.instance || null;
  61061. var invertUV = options.invertUV || false;
  61062. 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);
  61063. };
  61064. /**
  61065. * Creates an custom extruded shape mesh.
  61066. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61067. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61068. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61069. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61070. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61071. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61072. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61073. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61074. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61075. * * 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
  61076. * * 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
  61077. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61078. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61079. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61080. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61081. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61082. * @param name defines the name of the mesh
  61083. * @param options defines the options used to create the mesh
  61084. * @param scene defines the hosting scene
  61085. * @returns the custom extruded shape mesh
  61086. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61087. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61088. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61089. */
  61090. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61091. var path = options.path;
  61092. var shape = options.shape;
  61093. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61094. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61095. var ribbonCloseArray = options.ribbonCloseArray || false;
  61096. var ribbonClosePath = options.ribbonClosePath || false;
  61097. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61098. var updatable = options.updatable;
  61099. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61100. var instance = options.instance;
  61101. var invertUV = options.invertUV || false;
  61102. 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);
  61103. };
  61104. /**
  61105. * Creates lathe mesh.
  61106. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61107. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61108. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61109. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61110. * * 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
  61111. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61112. * * 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
  61113. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61114. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61115. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61116. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61117. * @param name defines the name of the mesh
  61118. * @param options defines the options used to create the mesh
  61119. * @param scene defines the hosting scene
  61120. * @returns the lathe mesh
  61121. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61122. */
  61123. MeshBuilder.CreateLathe = function (name, options, scene) {
  61124. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61125. var closed = (options.closed === undefined) ? true : options.closed;
  61126. var shape = options.shape;
  61127. var radius = options.radius || 1;
  61128. var tessellation = options.tessellation || 64;
  61129. var updatable = options.updatable;
  61130. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61131. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61132. var pi2 = Math.PI * 2;
  61133. var paths = new Array();
  61134. var invertUV = options.invertUV || false;
  61135. var i = 0;
  61136. var p = 0;
  61137. var step = pi2 / tessellation * arc;
  61138. var rotated;
  61139. var path = new Array();
  61140. for (i = 0; i <= tessellation; i++) {
  61141. var path = [];
  61142. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61143. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61144. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61145. }
  61146. for (p = 0; p < shape.length; p++) {
  61147. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61148. path.push(rotated);
  61149. }
  61150. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61151. 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));
  61152. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61153. }
  61154. paths.push(path);
  61155. }
  61156. // lathe ribbon
  61157. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61158. return lathe;
  61159. };
  61160. /**
  61161. * Creates a plane mesh
  61162. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61163. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61164. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61165. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61166. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61167. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61168. * @param name defines the name of the mesh
  61169. * @param options defines the options used to create the mesh
  61170. * @param scene defines the hosting scene
  61171. * @returns the plane mesh
  61172. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61173. */
  61174. MeshBuilder.CreatePlane = function (name, options, scene) {
  61175. var plane = new BABYLON.Mesh(name, scene);
  61176. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61177. plane._originalBuilderSideOrientation = options.sideOrientation;
  61178. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61179. vertexData.applyToMesh(plane, options.updatable);
  61180. if (options.sourcePlane) {
  61181. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61182. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61183. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61184. plane.rotate(vectorProduct, product);
  61185. }
  61186. return plane;
  61187. };
  61188. /**
  61189. * Creates a ground mesh
  61190. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61191. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61193. * @param name defines the name of the mesh
  61194. * @param options defines the options used to create the mesh
  61195. * @param scene defines the hosting scene
  61196. * @returns the ground mesh
  61197. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61198. */
  61199. MeshBuilder.CreateGround = function (name, options, scene) {
  61200. var ground = new BABYLON.GroundMesh(name, scene);
  61201. ground._setReady(false);
  61202. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61203. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61204. ground._width = options.width || 1;
  61205. ground._height = options.height || 1;
  61206. ground._maxX = ground._width / 2;
  61207. ground._maxZ = ground._height / 2;
  61208. ground._minX = -ground._maxX;
  61209. ground._minZ = -ground._maxZ;
  61210. var vertexData = BABYLON.VertexData.CreateGround(options);
  61211. vertexData.applyToMesh(ground, options.updatable);
  61212. ground._setReady(true);
  61213. return ground;
  61214. };
  61215. /**
  61216. * Creates a tiled ground mesh
  61217. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61218. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61219. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61220. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61221. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61222. * @param name defines the name of the mesh
  61223. * @param options defines the options used to create the mesh
  61224. * @param scene defines the hosting scene
  61225. * @returns the tiled ground mesh
  61226. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61227. */
  61228. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61229. var tiledGround = new BABYLON.Mesh(name, scene);
  61230. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61231. vertexData.applyToMesh(tiledGround, options.updatable);
  61232. return tiledGround;
  61233. };
  61234. /**
  61235. * Creates a ground mesh from a height map
  61236. * * The parameter `url` sets the URL of the height map image resource.
  61237. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61238. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61239. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61240. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61241. * * 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.
  61242. * * 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).
  61243. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61244. * @param name defines the name of the mesh
  61245. * @param url defines the url to the height map
  61246. * @param options defines the options used to create the mesh
  61247. * @param scene defines the hosting scene
  61248. * @returns the ground mesh
  61249. * @see http://doc.babylonjs.com/babylon101/height_map
  61250. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61251. */
  61252. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61253. var width = options.width || 10.0;
  61254. var height = options.height || 10.0;
  61255. var subdivisions = options.subdivisions || 1 | 0;
  61256. var minHeight = options.minHeight || 0.0;
  61257. var maxHeight = options.maxHeight || 1.0;
  61258. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61259. var updatable = options.updatable;
  61260. var onReady = options.onReady;
  61261. var ground = new BABYLON.GroundMesh(name, scene);
  61262. ground._subdivisionsX = subdivisions;
  61263. ground._subdivisionsY = subdivisions;
  61264. ground._width = width;
  61265. ground._height = height;
  61266. ground._maxX = ground._width / 2.0;
  61267. ground._maxZ = ground._height / 2.0;
  61268. ground._minX = -ground._maxX;
  61269. ground._minZ = -ground._maxZ;
  61270. ground._setReady(false);
  61271. var onload = function (img) {
  61272. // Getting height map data
  61273. var canvas = document.createElement("canvas");
  61274. var context = canvas.getContext("2d");
  61275. if (!context) {
  61276. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61277. }
  61278. if (scene.isDisposed) {
  61279. return;
  61280. }
  61281. var bufferWidth = img.width;
  61282. var bufferHeight = img.height;
  61283. canvas.width = bufferWidth;
  61284. canvas.height = bufferHeight;
  61285. context.drawImage(img, 0, 0);
  61286. // Create VertexData from map data
  61287. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61288. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61289. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61290. width: width, height: height,
  61291. subdivisions: subdivisions,
  61292. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61293. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61294. });
  61295. vertexData.applyToMesh(ground, updatable);
  61296. //execute ready callback, if set
  61297. if (onReady) {
  61298. onReady(ground);
  61299. }
  61300. ground._setReady(true);
  61301. };
  61302. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61303. return ground;
  61304. };
  61305. /**
  61306. * Creates a polygon mesh
  61307. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61308. * * 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
  61309. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61310. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61311. * * 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)
  61312. * * Remember you can only change the shape positions, not their number when updating a polygon
  61313. * @param name defines the name of the mesh
  61314. * @param options defines the options used to create the mesh
  61315. * @param scene defines the hosting scene
  61316. * @returns the polygon mesh
  61317. */
  61318. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61319. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61320. var shape = options.shape;
  61321. var holes = options.holes || [];
  61322. var depth = options.depth || 0;
  61323. var contours = [];
  61324. var hole = [];
  61325. for (var i = 0; i < shape.length; i++) {
  61326. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61327. }
  61328. var epsilon = 0.00000001;
  61329. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61330. contours.pop();
  61331. }
  61332. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61333. for (var hNb = 0; hNb < holes.length; hNb++) {
  61334. hole = [];
  61335. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61336. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61337. }
  61338. polygonTriangulation.addHole(hole);
  61339. }
  61340. var polygon = polygonTriangulation.build(options.updatable, depth);
  61341. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61342. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61343. vertexData.applyToMesh(polygon, options.updatable);
  61344. return polygon;
  61345. };
  61346. ;
  61347. /**
  61348. * Creates an extruded polygon mesh, with depth in the Y direction.
  61349. * * 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)
  61350. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61351. * @param name defines the name of the mesh
  61352. * @param options defines the options used to create the mesh
  61353. * @param scene defines the hosting scene
  61354. * @returns the polygon mesh
  61355. */
  61356. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61357. return MeshBuilder.CreatePolygon(name, options, scene);
  61358. };
  61359. ;
  61360. /**
  61361. * Creates a tube mesh.
  61362. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61363. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61364. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61365. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61366. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61367. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61368. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61369. * * 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
  61370. * * 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
  61371. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61372. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61373. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61374. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61375. * @param name defines the name of the mesh
  61376. * @param options defines the options used to create the mesh
  61377. * @param scene defines the hosting scene
  61378. * @returns the tube mesh
  61379. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61380. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61381. */
  61382. MeshBuilder.CreateTube = function (name, options, scene) {
  61383. var path = options.path;
  61384. var instance = options.instance;
  61385. var radius = 1.0;
  61386. if (instance) {
  61387. radius = instance.radius;
  61388. }
  61389. if (options.radius !== undefined) {
  61390. radius = options.radius;
  61391. }
  61392. ;
  61393. var tessellation = options.tessellation || 64 | 0;
  61394. var radiusFunction = options.radiusFunction || null;
  61395. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61396. var invertUV = options.invertUV || false;
  61397. var updatable = options.updatable;
  61398. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61399. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61400. // tube geometry
  61401. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61402. var tangents = path3D.getTangents();
  61403. var normals = path3D.getNormals();
  61404. var distances = path3D.getDistances();
  61405. var pi2 = Math.PI * 2;
  61406. var step = pi2 / tessellation * arc;
  61407. var returnRadius = function () { return radius; };
  61408. var radiusFunctionFinal = radiusFunction || returnRadius;
  61409. var circlePath;
  61410. var rad;
  61411. var normal;
  61412. var rotated;
  61413. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61414. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61415. for (var i = 0; i < path.length; i++) {
  61416. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61417. circlePath = Array(); // current circle array
  61418. normal = normals[i]; // current normal
  61419. for (var t = 0; t < tessellation; t++) {
  61420. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61421. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61422. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61423. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61424. circlePath[t] = rotated;
  61425. }
  61426. circlePaths[index] = circlePath;
  61427. index++;
  61428. }
  61429. // cap
  61430. var capPath = function (nbPoints, pathIndex) {
  61431. var pointCap = Array();
  61432. for (var i = 0; i < nbPoints; i++) {
  61433. pointCap.push(path[pathIndex]);
  61434. }
  61435. return pointCap;
  61436. };
  61437. switch (cap) {
  61438. case BABYLON.Mesh.NO_CAP:
  61439. break;
  61440. case BABYLON.Mesh.CAP_START:
  61441. circlePaths[0] = capPath(tessellation, 0);
  61442. circlePaths[1] = circlePaths[2].slice(0);
  61443. break;
  61444. case BABYLON.Mesh.CAP_END:
  61445. circlePaths[index] = circlePaths[index - 1].slice(0);
  61446. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61447. break;
  61448. case BABYLON.Mesh.CAP_ALL:
  61449. circlePaths[0] = capPath(tessellation, 0);
  61450. circlePaths[1] = circlePaths[2].slice(0);
  61451. circlePaths[index] = circlePaths[index - 1].slice(0);
  61452. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61453. break;
  61454. default:
  61455. break;
  61456. }
  61457. return circlePaths;
  61458. };
  61459. var path3D;
  61460. var pathArray;
  61461. if (instance) { // tube update
  61462. var arc = options.arc || instance.arc;
  61463. path3D = (instance.path3D).update(path);
  61464. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61465. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61466. instance.path3D = path3D;
  61467. instance.pathArray = pathArray;
  61468. instance.arc = arc;
  61469. instance.radius = radius;
  61470. return instance;
  61471. }
  61472. // tube creation
  61473. path3D = new BABYLON.Path3D(path);
  61474. var newPathArray = new Array();
  61475. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61476. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61477. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61478. tube.pathArray = pathArray;
  61479. tube.path3D = path3D;
  61480. tube.tessellation = tessellation;
  61481. tube.cap = cap;
  61482. tube.arc = options.arc;
  61483. tube.radius = radius;
  61484. return tube;
  61485. };
  61486. /**
  61487. * Creates a polyhedron mesh
  61488. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61489. * * The parameter `size` (positive float, default 1) sets the polygon size
  61490. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61491. * * 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`
  61492. * * 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
  61493. * * 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)`)
  61494. * * 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
  61495. * * 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
  61496. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61497. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61498. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61499. * @param name defines the name of the mesh
  61500. * @param options defines the options used to create the mesh
  61501. * @param scene defines the hosting scene
  61502. * @returns the polyhedron mesh
  61503. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61504. */
  61505. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61506. var polyhedron = new BABYLON.Mesh(name, scene);
  61507. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61508. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61509. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61510. vertexData.applyToMesh(polyhedron, options.updatable);
  61511. return polyhedron;
  61512. };
  61513. /**
  61514. * Creates a decal mesh.
  61515. * 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
  61516. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61517. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61518. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61519. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61520. * @param name defines the name of the mesh
  61521. * @param sourceMesh defines the mesh where the decal must be applied
  61522. * @param options defines the options used to create the mesh
  61523. * @param scene defines the hosting scene
  61524. * @returns the decal mesh
  61525. * @see http://doc.babylonjs.com/how_to/decals
  61526. */
  61527. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61528. var indices = sourceMesh.getIndices();
  61529. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61530. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61531. var position = options.position || BABYLON.Vector3.Zero();
  61532. var normal = options.normal || BABYLON.Vector3.Up();
  61533. var size = options.size || BABYLON.Vector3.One();
  61534. var angle = options.angle || 0;
  61535. // Getting correct rotation
  61536. if (!normal) {
  61537. var target = new BABYLON.Vector3(0, 0, 1);
  61538. var camera = sourceMesh.getScene().activeCamera;
  61539. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61540. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61541. }
  61542. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61543. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61544. var pitch = Math.atan2(normal.y, len);
  61545. // Matrix
  61546. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61547. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61548. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61549. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61550. var vertexData = new BABYLON.VertexData();
  61551. vertexData.indices = [];
  61552. vertexData.positions = [];
  61553. vertexData.normals = [];
  61554. vertexData.uvs = [];
  61555. var currentVertexDataIndex = 0;
  61556. var extractDecalVector3 = function (indexId) {
  61557. var result = new BABYLON.PositionNormalVertex();
  61558. if (!indices || !positions || !normals) {
  61559. return result;
  61560. }
  61561. var vertexId = indices[indexId];
  61562. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61563. // Send vector to decal local world
  61564. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61565. // Get normal
  61566. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61567. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61568. return result;
  61569. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61570. var clip = function (vertices, axis) {
  61571. if (vertices.length === 0) {
  61572. return vertices;
  61573. }
  61574. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61575. var clipVertices = function (v0, v1) {
  61576. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61577. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61578. };
  61579. var result = new Array();
  61580. for (var index = 0; index < vertices.length; index += 3) {
  61581. var v1Out;
  61582. var v2Out;
  61583. var v3Out;
  61584. var total = 0;
  61585. var nV1 = null;
  61586. var nV2 = null;
  61587. var nV3 = null;
  61588. var nV4 = null;
  61589. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61590. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61591. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61592. v1Out = d1 > 0;
  61593. v2Out = d2 > 0;
  61594. v3Out = d3 > 0;
  61595. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61596. switch (total) {
  61597. case 0:
  61598. result.push(vertices[index]);
  61599. result.push(vertices[index + 1]);
  61600. result.push(vertices[index + 2]);
  61601. break;
  61602. case 1:
  61603. if (v1Out) {
  61604. nV1 = vertices[index + 1];
  61605. nV2 = vertices[index + 2];
  61606. nV3 = clipVertices(vertices[index], nV1);
  61607. nV4 = clipVertices(vertices[index], nV2);
  61608. }
  61609. if (v2Out) {
  61610. nV1 = vertices[index];
  61611. nV2 = vertices[index + 2];
  61612. nV3 = clipVertices(vertices[index + 1], nV1);
  61613. nV4 = clipVertices(vertices[index + 1], nV2);
  61614. result.push(nV3);
  61615. result.push(nV2.clone());
  61616. result.push(nV1.clone());
  61617. result.push(nV2.clone());
  61618. result.push(nV3.clone());
  61619. result.push(nV4);
  61620. break;
  61621. }
  61622. if (v3Out) {
  61623. nV1 = vertices[index];
  61624. nV2 = vertices[index + 1];
  61625. nV3 = clipVertices(vertices[index + 2], nV1);
  61626. nV4 = clipVertices(vertices[index + 2], nV2);
  61627. }
  61628. if (nV1 && nV2 && nV3 && nV4) {
  61629. result.push(nV1.clone());
  61630. result.push(nV2.clone());
  61631. result.push(nV3);
  61632. result.push(nV4);
  61633. result.push(nV3.clone());
  61634. result.push(nV2.clone());
  61635. }
  61636. break;
  61637. case 2:
  61638. if (!v1Out) {
  61639. nV1 = vertices[index].clone();
  61640. nV2 = clipVertices(nV1, vertices[index + 1]);
  61641. nV3 = clipVertices(nV1, vertices[index + 2]);
  61642. result.push(nV1);
  61643. result.push(nV2);
  61644. result.push(nV3);
  61645. }
  61646. if (!v2Out) {
  61647. nV1 = vertices[index + 1].clone();
  61648. nV2 = clipVertices(nV1, vertices[index + 2]);
  61649. nV3 = clipVertices(nV1, vertices[index]);
  61650. result.push(nV1);
  61651. result.push(nV2);
  61652. result.push(nV3);
  61653. }
  61654. if (!v3Out) {
  61655. nV1 = vertices[index + 2].clone();
  61656. nV2 = clipVertices(nV1, vertices[index]);
  61657. nV3 = clipVertices(nV1, vertices[index + 1]);
  61658. result.push(nV1);
  61659. result.push(nV2);
  61660. result.push(nV3);
  61661. }
  61662. break;
  61663. case 3:
  61664. break;
  61665. }
  61666. }
  61667. return result;
  61668. };
  61669. for (var index = 0; index < indices.length; index += 3) {
  61670. var faceVertices = new Array();
  61671. faceVertices.push(extractDecalVector3(index));
  61672. faceVertices.push(extractDecalVector3(index + 1));
  61673. faceVertices.push(extractDecalVector3(index + 2));
  61674. // Clip
  61675. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61676. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61678. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61679. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61680. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61681. if (faceVertices.length === 0) {
  61682. continue;
  61683. }
  61684. // Add UVs and get back to world
  61685. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61686. var vertex = faceVertices[vIndex];
  61687. //TODO check for Int32Array | Uint32Array | Uint16Array
  61688. vertexData.indices.push(currentVertexDataIndex);
  61689. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61690. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61691. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61692. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61693. currentVertexDataIndex++;
  61694. }
  61695. }
  61696. // Return mesh
  61697. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61698. vertexData.applyToMesh(decal);
  61699. decal.position = position.clone();
  61700. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61701. return decal;
  61702. };
  61703. // Privates
  61704. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61705. // extrusion geometry
  61706. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61707. var tangents = path3D.getTangents();
  61708. var normals = path3D.getNormals();
  61709. var binormals = path3D.getBinormals();
  61710. var distances = path3D.getDistances();
  61711. var angle = 0;
  61712. var returnScale = function () { return scale !== null ? scale : 1; };
  61713. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61714. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61715. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61716. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61717. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61718. for (var i = 0; i < curve.length; i++) {
  61719. var shapePath = new Array();
  61720. var angleStep = rotate(i, distances[i]);
  61721. var scaleRatio = scl(i, distances[i]);
  61722. for (var p = 0; p < shape.length; p++) {
  61723. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61724. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61725. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61726. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61727. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61728. shapePath[p] = rotated;
  61729. }
  61730. shapePaths[index] = shapePath;
  61731. angle += angleStep;
  61732. index++;
  61733. }
  61734. // cap
  61735. var capPath = function (shapePath) {
  61736. var pointCap = Array();
  61737. var barycenter = BABYLON.Vector3.Zero();
  61738. var i;
  61739. for (i = 0; i < shapePath.length; i++) {
  61740. barycenter.addInPlace(shapePath[i]);
  61741. }
  61742. barycenter.scaleInPlace(1.0 / shapePath.length);
  61743. for (i = 0; i < shapePath.length; i++) {
  61744. pointCap.push(barycenter);
  61745. }
  61746. return pointCap;
  61747. };
  61748. switch (cap) {
  61749. case BABYLON.Mesh.NO_CAP:
  61750. break;
  61751. case BABYLON.Mesh.CAP_START:
  61752. shapePaths[0] = capPath(shapePaths[2]);
  61753. shapePaths[1] = shapePaths[2];
  61754. break;
  61755. case BABYLON.Mesh.CAP_END:
  61756. shapePaths[index] = shapePaths[index - 1];
  61757. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61758. break;
  61759. case BABYLON.Mesh.CAP_ALL:
  61760. shapePaths[0] = capPath(shapePaths[2]);
  61761. shapePaths[1] = shapePaths[2];
  61762. shapePaths[index] = shapePaths[index - 1];
  61763. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61764. break;
  61765. default:
  61766. break;
  61767. }
  61768. return shapePaths;
  61769. };
  61770. var path3D;
  61771. var pathArray;
  61772. if (instance) { // instance update
  61773. path3D = (instance.path3D).update(curve);
  61774. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61775. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61776. return instance;
  61777. }
  61778. // extruded shape creation
  61779. path3D = new BABYLON.Path3D(curve);
  61780. var newShapePaths = new Array();
  61781. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61782. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61783. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61784. extrudedGeneric.pathArray = pathArray;
  61785. extrudedGeneric.path3D = path3D;
  61786. extrudedGeneric.cap = cap;
  61787. return extrudedGeneric;
  61788. };
  61789. return MeshBuilder;
  61790. }());
  61791. BABYLON.MeshBuilder = MeshBuilder;
  61792. })(BABYLON || (BABYLON = {}));
  61793. //# sourceMappingURL=babylon.meshBuilder.js.map
  61794. var BABYLON;
  61795. (function (BABYLON) {
  61796. /**
  61797. * Draco compression (https://google.github.io/draco/)
  61798. *
  61799. * This class wraps the Draco module.
  61800. *
  61801. * **Encoder**
  61802. *
  61803. * The encoder is not currently implemented.
  61804. *
  61805. * **Decoder**
  61806. *
  61807. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61808. *
  61809. * To update the configuration, use the following code:
  61810. * ```javascript
  61811. * BABYLON.DracoCompression.Configuration = {
  61812. * decoder: {
  61813. * wasmUrl: "<url to the WebAssembly library>",
  61814. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61815. * fallbackUrl: "<url to the fallback JavaScript library>",
  61816. * }
  61817. * };
  61818. * ```
  61819. *
  61820. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  61821. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61822. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61823. *
  61824. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61825. * ```javascript
  61826. * var dracoCompression = new BABYLON.DracoCompression();
  61827. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61828. * [BABYLON.VertexBuffer.PositionKind]: 0
  61829. * });
  61830. * ```
  61831. *
  61832. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61833. */
  61834. var DracoCompression = /** @class */ (function () {
  61835. /**
  61836. * Constructor
  61837. */
  61838. function DracoCompression() {
  61839. }
  61840. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61841. /**
  61842. * Returns true if the decoder is available.
  61843. */
  61844. get: function () {
  61845. if (typeof DracoDecoderModule !== "undefined") {
  61846. return true;
  61847. }
  61848. var decoder = DracoCompression.Configuration.decoder;
  61849. if (decoder) {
  61850. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61851. return true;
  61852. }
  61853. if (decoder.fallbackUrl) {
  61854. return true;
  61855. }
  61856. }
  61857. return false;
  61858. },
  61859. enumerable: true,
  61860. configurable: true
  61861. });
  61862. /**
  61863. * Stop all async operations and release resources.
  61864. */
  61865. DracoCompression.prototype.dispose = function () {
  61866. };
  61867. /**
  61868. * Decode Draco compressed mesh data to vertex data.
  61869. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61870. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61871. * @returns A promise that resolves with the decoded vertex data
  61872. */
  61873. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61874. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61875. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61876. var module = wrappedModule.module;
  61877. var vertexData = new BABYLON.VertexData();
  61878. var buffer = new module.DecoderBuffer();
  61879. buffer.Init(dataView, dataView.byteLength);
  61880. var decoder = new module.Decoder();
  61881. var geometry;
  61882. var status;
  61883. try {
  61884. var type = decoder.GetEncodedGeometryType(buffer);
  61885. switch (type) {
  61886. case module.TRIANGULAR_MESH:
  61887. geometry = new module.Mesh();
  61888. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61889. break;
  61890. case module.POINT_CLOUD:
  61891. geometry = new module.PointCloud();
  61892. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61893. break;
  61894. default:
  61895. throw new Error("Invalid geometry type " + type);
  61896. }
  61897. if (!status.ok() || !geometry.ptr) {
  61898. throw new Error(status.error_msg());
  61899. }
  61900. var numPoints = geometry.num_points();
  61901. if (type === module.TRIANGULAR_MESH) {
  61902. var numFaces = geometry.num_faces();
  61903. var faceIndices = new module.DracoInt32Array();
  61904. try {
  61905. var indices = new Uint32Array(numFaces * 3);
  61906. for (var i = 0; i < numFaces; i++) {
  61907. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61908. var offset = i * 3;
  61909. indices[offset + 0] = faceIndices.GetValue(0);
  61910. indices[offset + 1] = faceIndices.GetValue(1);
  61911. indices[offset + 2] = faceIndices.GetValue(2);
  61912. }
  61913. vertexData.indices = indices;
  61914. }
  61915. finally {
  61916. module.destroy(faceIndices);
  61917. }
  61918. }
  61919. for (var kind in attributes) {
  61920. var uniqueId = attributes[kind];
  61921. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61922. var dracoData = new module.DracoFloat32Array();
  61923. try {
  61924. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61925. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61926. for (var i = 0; i < babylonData.length; i++) {
  61927. babylonData[i] = dracoData.GetValue(i);
  61928. }
  61929. vertexData.set(babylonData, kind);
  61930. }
  61931. finally {
  61932. module.destroy(dracoData);
  61933. }
  61934. }
  61935. }
  61936. finally {
  61937. if (geometry) {
  61938. module.destroy(geometry);
  61939. }
  61940. module.destroy(decoder);
  61941. module.destroy(buffer);
  61942. }
  61943. return vertexData;
  61944. });
  61945. };
  61946. DracoCompression._GetDecoderModule = function () {
  61947. if (!DracoCompression._DecoderModulePromise) {
  61948. var promise = null;
  61949. var config_1 = {};
  61950. if (typeof DracoDecoderModule !== "undefined") {
  61951. promise = Promise.resolve();
  61952. }
  61953. else {
  61954. var decoder = DracoCompression.Configuration.decoder;
  61955. if (decoder) {
  61956. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61957. promise = Promise.all([
  61958. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61959. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61960. config_1.wasmBinary = data;
  61961. })
  61962. ]);
  61963. }
  61964. else if (decoder.fallbackUrl) {
  61965. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61966. }
  61967. }
  61968. }
  61969. if (!promise) {
  61970. throw new Error("Draco decoder module is not available");
  61971. }
  61972. DracoCompression._DecoderModulePromise = promise.then(function () {
  61973. return new Promise(function (resolve) {
  61974. config_1.onModuleLoaded = function (decoderModule) {
  61975. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61976. resolve({ module: decoderModule });
  61977. };
  61978. DracoDecoderModule(config_1);
  61979. });
  61980. });
  61981. }
  61982. return DracoCompression._DecoderModulePromise;
  61983. };
  61984. DracoCompression._LoadScriptAsync = function (url) {
  61985. return new Promise(function (resolve, reject) {
  61986. BABYLON.Tools.LoadScript(url, function () {
  61987. resolve();
  61988. }, function (message) {
  61989. reject(new Error(message));
  61990. });
  61991. });
  61992. };
  61993. DracoCompression._LoadFileAsync = function (url) {
  61994. return new Promise(function (resolve, reject) {
  61995. BABYLON.Tools.LoadFile(url, function (data) {
  61996. resolve(data);
  61997. }, undefined, undefined, true, function (request, exception) {
  61998. reject(exception);
  61999. });
  62000. });
  62001. };
  62002. /**
  62003. * The configuration. Defaults to the following urls:
  62004. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62005. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62006. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62007. */
  62008. DracoCompression.Configuration = {
  62009. decoder: {
  62010. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62011. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62012. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62013. }
  62014. };
  62015. return DracoCompression;
  62016. }());
  62017. BABYLON.DracoCompression = DracoCompression;
  62018. })(BABYLON || (BABYLON = {}));
  62019. //# sourceMappingURL=babylon.dracoCompression.js.map
  62020. var BABYLON;
  62021. (function (BABYLON) {
  62022. var AudioEngine = /** @class */ (function () {
  62023. function AudioEngine() {
  62024. this._audioContext = null;
  62025. this._audioContextInitialized = false;
  62026. this.canUseWebAudio = false;
  62027. this.WarnedWebAudioUnsupported = false;
  62028. this.unlocked = false;
  62029. this.isMP3supported = false;
  62030. this.isOGGsupported = false;
  62031. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62032. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62033. this.canUseWebAudio = true;
  62034. }
  62035. var audioElem = document.createElement('audio');
  62036. try {
  62037. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62038. this.isMP3supported = true;
  62039. }
  62040. }
  62041. catch (e) {
  62042. // protect error during capability check.
  62043. }
  62044. try {
  62045. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62046. this.isOGGsupported = true;
  62047. }
  62048. }
  62049. catch (e) {
  62050. // protect error during capability check.
  62051. }
  62052. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62053. this._unlockiOSaudio();
  62054. }
  62055. else {
  62056. this.unlocked = true;
  62057. }
  62058. }
  62059. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62060. get: function () {
  62061. if (!this._audioContextInitialized) {
  62062. this._initializeAudioContext();
  62063. }
  62064. return this._audioContext;
  62065. },
  62066. enumerable: true,
  62067. configurable: true
  62068. });
  62069. AudioEngine.prototype._unlockiOSaudio = function () {
  62070. var _this = this;
  62071. var unlockaudio = function () {
  62072. if (!_this.audioContext) {
  62073. return;
  62074. }
  62075. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62076. var source = _this.audioContext.createBufferSource();
  62077. source.buffer = buffer;
  62078. source.connect(_this.audioContext.destination);
  62079. source.start(0);
  62080. setTimeout(function () {
  62081. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62082. _this.unlocked = true;
  62083. window.removeEventListener('touchend', unlockaudio, false);
  62084. if (_this.onAudioUnlocked) {
  62085. _this.onAudioUnlocked();
  62086. }
  62087. }
  62088. }, 0);
  62089. };
  62090. window.addEventListener('touchend', unlockaudio, false);
  62091. };
  62092. AudioEngine.prototype._initializeAudioContext = function () {
  62093. try {
  62094. if (this.canUseWebAudio) {
  62095. this._audioContext = new AudioContext();
  62096. // create a global volume gain node
  62097. this.masterGain = this._audioContext.createGain();
  62098. this.masterGain.gain.value = 1;
  62099. this.masterGain.connect(this._audioContext.destination);
  62100. this._audioContextInitialized = true;
  62101. }
  62102. }
  62103. catch (e) {
  62104. this.canUseWebAudio = false;
  62105. BABYLON.Tools.Error("Web Audio: " + e.message);
  62106. }
  62107. };
  62108. AudioEngine.prototype.dispose = function () {
  62109. if (this.canUseWebAudio && this._audioContextInitialized) {
  62110. if (this._connectedAnalyser && this._audioContext) {
  62111. this._connectedAnalyser.stopDebugCanvas();
  62112. this._connectedAnalyser.dispose();
  62113. this.masterGain.disconnect();
  62114. this.masterGain.connect(this._audioContext.destination);
  62115. this._connectedAnalyser = null;
  62116. }
  62117. this.masterGain.gain.value = 1;
  62118. }
  62119. this.WarnedWebAudioUnsupported = false;
  62120. };
  62121. AudioEngine.prototype.getGlobalVolume = function () {
  62122. if (this.canUseWebAudio && this._audioContextInitialized) {
  62123. return this.masterGain.gain.value;
  62124. }
  62125. else {
  62126. return -1;
  62127. }
  62128. };
  62129. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62130. if (this.canUseWebAudio && this._audioContextInitialized) {
  62131. this.masterGain.gain.value = newVolume;
  62132. }
  62133. };
  62134. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62135. if (this._connectedAnalyser) {
  62136. this._connectedAnalyser.stopDebugCanvas();
  62137. }
  62138. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62139. this._connectedAnalyser = analyser;
  62140. this.masterGain.disconnect();
  62141. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62142. }
  62143. };
  62144. return AudioEngine;
  62145. }());
  62146. BABYLON.AudioEngine = AudioEngine;
  62147. })(BABYLON || (BABYLON = {}));
  62148. //# sourceMappingURL=babylon.audioEngine.js.map
  62149. var BABYLON;
  62150. (function (BABYLON) {
  62151. var Sound = /** @class */ (function () {
  62152. /**
  62153. * Create a sound and attach it to a scene
  62154. * @param name Name of your sound
  62155. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62156. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62157. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62158. */
  62159. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62160. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62161. var _this = this;
  62162. this.autoplay = false;
  62163. this.loop = false;
  62164. this.useCustomAttenuation = false;
  62165. this.spatialSound = false;
  62166. this.refDistance = 1;
  62167. this.rolloffFactor = 1;
  62168. this.maxDistance = 100;
  62169. this.distanceModel = "linear";
  62170. this._panningModel = "equalpower";
  62171. this._playbackRate = 1;
  62172. this._streaming = false;
  62173. this._startTime = 0;
  62174. this._startOffset = 0;
  62175. this._position = BABYLON.Vector3.Zero();
  62176. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62177. this._volume = 1;
  62178. this._isReadyToPlay = false;
  62179. this.isPlaying = false;
  62180. this.isPaused = false;
  62181. this._isDirectional = false;
  62182. // Used if you'd like to create a directional sound.
  62183. // If not set, the sound will be omnidirectional
  62184. this._coneInnerAngle = 360;
  62185. this._coneOuterAngle = 360;
  62186. this._coneOuterGain = 0;
  62187. this._isOutputConnected = false;
  62188. this._urlType = "Unknown";
  62189. this.name = name;
  62190. this._scene = scene;
  62191. this._readyToPlayCallback = readyToPlayCallback;
  62192. // Default custom attenuation function is a linear attenuation
  62193. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62194. if (currentDistance < maxDistance) {
  62195. return currentVolume * (1 - currentDistance / maxDistance);
  62196. }
  62197. else {
  62198. return 0;
  62199. }
  62200. };
  62201. if (options) {
  62202. this.autoplay = options.autoplay || false;
  62203. this.loop = options.loop || false;
  62204. // if volume === 0, we need another way to check this option
  62205. if (options.volume !== undefined) {
  62206. this._volume = options.volume;
  62207. }
  62208. this.spatialSound = options.spatialSound || false;
  62209. this.maxDistance = options.maxDistance || 100;
  62210. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62211. this.rolloffFactor = options.rolloffFactor || 1;
  62212. this.refDistance = options.refDistance || 1;
  62213. this.distanceModel = options.distanceModel || "linear";
  62214. this._playbackRate = options.playbackRate || 1;
  62215. this._streaming = options.streaming || false;
  62216. }
  62217. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62218. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62219. this._soundGain.gain.value = this._volume;
  62220. this._inputAudioNode = this._soundGain;
  62221. this._ouputAudioNode = this._soundGain;
  62222. if (this.spatialSound) {
  62223. this._createSpatialParameters();
  62224. }
  62225. this._scene.mainSoundTrack.AddSound(this);
  62226. var validParameter = true;
  62227. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62228. if (urlOrArrayBuffer) {
  62229. try {
  62230. if (typeof (urlOrArrayBuffer) === "string") {
  62231. this._urlType = "String";
  62232. }
  62233. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62234. this._urlType = "ArrayBuffer";
  62235. }
  62236. else if (urlOrArrayBuffer instanceof MediaStream) {
  62237. this._urlType = "MediaStream";
  62238. }
  62239. else if (Array.isArray(urlOrArrayBuffer)) {
  62240. this._urlType = "Array";
  62241. }
  62242. var urls = [];
  62243. var codecSupportedFound = false;
  62244. switch (this._urlType) {
  62245. case "MediaStream":
  62246. this._streaming = true;
  62247. this._isReadyToPlay = true;
  62248. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62249. if (this.autoplay) {
  62250. this.play();
  62251. }
  62252. if (this._readyToPlayCallback) {
  62253. this._readyToPlayCallback();
  62254. }
  62255. break;
  62256. case "ArrayBuffer":
  62257. if (urlOrArrayBuffer.byteLength > 0) {
  62258. codecSupportedFound = true;
  62259. this._soundLoaded(urlOrArrayBuffer);
  62260. }
  62261. break;
  62262. case "String":
  62263. urls.push(urlOrArrayBuffer);
  62264. case "Array":
  62265. if (urls.length === 0)
  62266. urls = urlOrArrayBuffer;
  62267. // If we found a supported format, we load it immediately and stop the loop
  62268. for (var i = 0; i < urls.length; i++) {
  62269. var url = urls[i];
  62270. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62271. codecSupportedFound = true;
  62272. }
  62273. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62274. codecSupportedFound = true;
  62275. }
  62276. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62277. codecSupportedFound = true;
  62278. }
  62279. if (url.indexOf("blob:") !== -1) {
  62280. codecSupportedFound = true;
  62281. }
  62282. if (codecSupportedFound) {
  62283. // Loading sound using XHR2
  62284. if (!this._streaming) {
  62285. this._scene._loadFile(url, function (data) {
  62286. _this._soundLoaded(data);
  62287. }, undefined, true, true, function (exception) {
  62288. if (exception) {
  62289. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62290. }
  62291. BABYLON.Tools.Error("Sound creation aborted.");
  62292. _this._scene.mainSoundTrack.RemoveSound(_this);
  62293. });
  62294. }
  62295. // Streaming sound using HTML5 Audio tag
  62296. else {
  62297. this._htmlAudioElement = new Audio(url);
  62298. this._htmlAudioElement.controls = false;
  62299. this._htmlAudioElement.loop = this.loop;
  62300. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62301. this._htmlAudioElement.preload = "auto";
  62302. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62303. _this._isReadyToPlay = true;
  62304. if (_this.autoplay) {
  62305. _this.play();
  62306. }
  62307. if (_this._readyToPlayCallback) {
  62308. _this._readyToPlayCallback();
  62309. }
  62310. });
  62311. document.body.appendChild(this._htmlAudioElement);
  62312. }
  62313. break;
  62314. }
  62315. }
  62316. break;
  62317. default:
  62318. validParameter = false;
  62319. break;
  62320. }
  62321. if (!validParameter) {
  62322. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62323. }
  62324. else {
  62325. if (!codecSupportedFound) {
  62326. this._isReadyToPlay = true;
  62327. // Simulating a ready to play event to avoid breaking code path
  62328. if (this._readyToPlayCallback) {
  62329. window.setTimeout(function () {
  62330. if (_this._readyToPlayCallback) {
  62331. _this._readyToPlayCallback();
  62332. }
  62333. }, 1000);
  62334. }
  62335. }
  62336. }
  62337. }
  62338. catch (ex) {
  62339. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62340. this._scene.mainSoundTrack.RemoveSound(this);
  62341. }
  62342. }
  62343. }
  62344. else {
  62345. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62346. this._scene.mainSoundTrack.AddSound(this);
  62347. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62348. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62349. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62350. }
  62351. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62352. if (this._readyToPlayCallback) {
  62353. window.setTimeout(function () {
  62354. if (_this._readyToPlayCallback) {
  62355. _this._readyToPlayCallback();
  62356. }
  62357. }, 1000);
  62358. }
  62359. }
  62360. }
  62361. Sound.prototype.dispose = function () {
  62362. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62363. if (this.isPlaying) {
  62364. this.stop();
  62365. }
  62366. this._isReadyToPlay = false;
  62367. if (this.soundTrackId === -1) {
  62368. this._scene.mainSoundTrack.RemoveSound(this);
  62369. }
  62370. else {
  62371. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62372. }
  62373. if (this._soundGain) {
  62374. this._soundGain.disconnect();
  62375. this._soundGain = null;
  62376. }
  62377. if (this._soundPanner) {
  62378. this._soundPanner.disconnect();
  62379. this._soundPanner = null;
  62380. }
  62381. if (this._soundSource) {
  62382. this._soundSource.disconnect();
  62383. this._soundSource = null;
  62384. }
  62385. this._audioBuffer = null;
  62386. if (this._htmlAudioElement) {
  62387. this._htmlAudioElement.pause();
  62388. this._htmlAudioElement.src = "";
  62389. document.body.removeChild(this._htmlAudioElement);
  62390. }
  62391. if (this._streamingSource) {
  62392. this._streamingSource.disconnect();
  62393. }
  62394. if (this._connectedMesh && this._registerFunc) {
  62395. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62396. this._connectedMesh = null;
  62397. }
  62398. }
  62399. };
  62400. Sound.prototype.isReady = function () {
  62401. return this._isReadyToPlay;
  62402. };
  62403. Sound.prototype._soundLoaded = function (audioData) {
  62404. var _this = this;
  62405. if (!BABYLON.Engine.audioEngine.audioContext) {
  62406. return;
  62407. }
  62408. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62409. _this._audioBuffer = buffer;
  62410. _this._isReadyToPlay = true;
  62411. if (_this.autoplay) {
  62412. _this.play();
  62413. }
  62414. if (_this._readyToPlayCallback) {
  62415. _this._readyToPlayCallback();
  62416. }
  62417. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62418. };
  62419. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62421. this._audioBuffer = audioBuffer;
  62422. this._isReadyToPlay = true;
  62423. }
  62424. };
  62425. Sound.prototype.updateOptions = function (options) {
  62426. if (options) {
  62427. this.loop = options.loop || this.loop;
  62428. this.maxDistance = options.maxDistance || this.maxDistance;
  62429. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62430. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62431. this.refDistance = options.refDistance || this.refDistance;
  62432. this.distanceModel = options.distanceModel || this.distanceModel;
  62433. this._playbackRate = options.playbackRate || this._playbackRate;
  62434. this._updateSpatialParameters();
  62435. if (this.isPlaying) {
  62436. if (this._streaming && this._htmlAudioElement) {
  62437. this._htmlAudioElement.playbackRate = this._playbackRate;
  62438. }
  62439. else {
  62440. if (this._soundSource) {
  62441. this._soundSource.playbackRate.value = this._playbackRate;
  62442. }
  62443. }
  62444. }
  62445. }
  62446. };
  62447. Sound.prototype._createSpatialParameters = function () {
  62448. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62449. if (this._scene.headphone) {
  62450. this._panningModel = "HRTF";
  62451. }
  62452. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62453. this._updateSpatialParameters();
  62454. this._soundPanner.connect(this._ouputAudioNode);
  62455. this._inputAudioNode = this._soundPanner;
  62456. }
  62457. };
  62458. Sound.prototype._updateSpatialParameters = function () {
  62459. if (this.spatialSound && this._soundPanner) {
  62460. if (this.useCustomAttenuation) {
  62461. // Tricks to disable in a way embedded Web Audio attenuation
  62462. this._soundPanner.distanceModel = "linear";
  62463. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62464. this._soundPanner.refDistance = 1;
  62465. this._soundPanner.rolloffFactor = 1;
  62466. this._soundPanner.panningModel = this._panningModel;
  62467. }
  62468. else {
  62469. this._soundPanner.distanceModel = this.distanceModel;
  62470. this._soundPanner.maxDistance = this.maxDistance;
  62471. this._soundPanner.refDistance = this.refDistance;
  62472. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62473. this._soundPanner.panningModel = this._panningModel;
  62474. }
  62475. }
  62476. };
  62477. Sound.prototype.switchPanningModelToHRTF = function () {
  62478. this._panningModel = "HRTF";
  62479. this._switchPanningModel();
  62480. };
  62481. Sound.prototype.switchPanningModelToEqualPower = function () {
  62482. this._panningModel = "equalpower";
  62483. this._switchPanningModel();
  62484. };
  62485. Sound.prototype._switchPanningModel = function () {
  62486. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62487. this._soundPanner.panningModel = this._panningModel;
  62488. }
  62489. };
  62490. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62491. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62492. if (this._isOutputConnected) {
  62493. this._ouputAudioNode.disconnect();
  62494. }
  62495. this._ouputAudioNode.connect(soundTrackAudioNode);
  62496. this._isOutputConnected = true;
  62497. }
  62498. };
  62499. /**
  62500. * Transform this sound into a directional source
  62501. * @param coneInnerAngle Size of the inner cone in degree
  62502. * @param coneOuterAngle Size of the outer cone in degree
  62503. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62504. */
  62505. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62506. if (coneOuterAngle < coneInnerAngle) {
  62507. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62508. return;
  62509. }
  62510. this._coneInnerAngle = coneInnerAngle;
  62511. this._coneOuterAngle = coneOuterAngle;
  62512. this._coneOuterGain = coneOuterGain;
  62513. this._isDirectional = true;
  62514. if (this.isPlaying && this.loop) {
  62515. this.stop();
  62516. this.play();
  62517. }
  62518. };
  62519. Sound.prototype.setPosition = function (newPosition) {
  62520. this._position = newPosition;
  62521. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62522. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62523. }
  62524. };
  62525. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62526. this._localDirection = newLocalDirection;
  62527. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62528. this._updateDirection();
  62529. }
  62530. };
  62531. Sound.prototype._updateDirection = function () {
  62532. if (!this._connectedMesh || !this._soundPanner) {
  62533. return;
  62534. }
  62535. var mat = this._connectedMesh.getWorldMatrix();
  62536. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62537. direction.normalize();
  62538. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62539. };
  62540. Sound.prototype.updateDistanceFromListener = function () {
  62541. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62542. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62543. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62544. }
  62545. };
  62546. Sound.prototype.setAttenuationFunction = function (callback) {
  62547. this._customAttenuationFunction = callback;
  62548. };
  62549. /**
  62550. * Play the sound
  62551. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62552. * @param offset (optional) Start the sound setting it at a specific time
  62553. */
  62554. Sound.prototype.play = function (time, offset) {
  62555. var _this = this;
  62556. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62557. try {
  62558. if (this._startOffset < 0) {
  62559. time = -this._startOffset;
  62560. this._startOffset = 0;
  62561. }
  62562. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62563. if (!this._soundSource || !this._streamingSource) {
  62564. if (this.spatialSound && this._soundPanner) {
  62565. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62566. if (this._isDirectional) {
  62567. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62568. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62569. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62570. if (this._connectedMesh) {
  62571. this._updateDirection();
  62572. }
  62573. else {
  62574. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62575. }
  62576. }
  62577. }
  62578. }
  62579. if (this._streaming) {
  62580. if (!this._streamingSource) {
  62581. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62582. this._htmlAudioElement.onended = function () { _this._onended(); };
  62583. this._htmlAudioElement.playbackRate = this._playbackRate;
  62584. }
  62585. this._streamingSource.disconnect();
  62586. this._streamingSource.connect(this._inputAudioNode);
  62587. if (this._htmlAudioElement) {
  62588. this._htmlAudioElement.play();
  62589. }
  62590. }
  62591. else {
  62592. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62593. this._soundSource.buffer = this._audioBuffer;
  62594. this._soundSource.connect(this._inputAudioNode);
  62595. this._soundSource.loop = this.loop;
  62596. this._soundSource.playbackRate.value = this._playbackRate;
  62597. this._soundSource.onended = function () { _this._onended(); };
  62598. if (this._soundSource.buffer) {
  62599. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62600. }
  62601. }
  62602. this._startTime = startTime;
  62603. this.isPlaying = true;
  62604. this.isPaused = false;
  62605. }
  62606. catch (ex) {
  62607. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62608. }
  62609. }
  62610. };
  62611. Sound.prototype._onended = function () {
  62612. this.isPlaying = false;
  62613. if (this.onended) {
  62614. this.onended();
  62615. }
  62616. };
  62617. /**
  62618. * Stop the sound
  62619. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62620. */
  62621. Sound.prototype.stop = function (time) {
  62622. if (this.isPlaying) {
  62623. if (this._streaming) {
  62624. if (this._htmlAudioElement) {
  62625. this._htmlAudioElement.pause();
  62626. // Test needed for Firefox or it will generate an Invalid State Error
  62627. if (this._htmlAudioElement.currentTime > 0) {
  62628. this._htmlAudioElement.currentTime = 0;
  62629. }
  62630. }
  62631. else {
  62632. this._streamingSource.disconnect();
  62633. }
  62634. }
  62635. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62636. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62637. this._soundSource.stop(stopTime);
  62638. this._soundSource.onended = function () { };
  62639. if (!this.isPaused) {
  62640. this._startOffset = 0;
  62641. }
  62642. }
  62643. this.isPlaying = false;
  62644. }
  62645. };
  62646. Sound.prototype.pause = function () {
  62647. if (this.isPlaying) {
  62648. this.isPaused = true;
  62649. if (this._streaming) {
  62650. if (this._htmlAudioElement) {
  62651. this._htmlAudioElement.pause();
  62652. }
  62653. else {
  62654. this._streamingSource.disconnect();
  62655. }
  62656. }
  62657. else if (BABYLON.Engine.audioEngine.audioContext) {
  62658. this.stop(0);
  62659. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62660. }
  62661. }
  62662. };
  62663. Sound.prototype.setVolume = function (newVolume, time) {
  62664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62665. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62666. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62667. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62668. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62669. }
  62670. else {
  62671. this._soundGain.gain.value = newVolume;
  62672. }
  62673. }
  62674. this._volume = newVolume;
  62675. };
  62676. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62677. this._playbackRate = newPlaybackRate;
  62678. if (this.isPlaying) {
  62679. if (this._streaming && this._htmlAudioElement) {
  62680. this._htmlAudioElement.playbackRate = this._playbackRate;
  62681. }
  62682. else if (this._soundSource) {
  62683. this._soundSource.playbackRate.value = this._playbackRate;
  62684. }
  62685. }
  62686. };
  62687. Sound.prototype.getVolume = function () {
  62688. return this._volume;
  62689. };
  62690. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62691. var _this = this;
  62692. if (this._connectedMesh && this._registerFunc) {
  62693. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62694. this._registerFunc = null;
  62695. }
  62696. this._connectedMesh = meshToConnectTo;
  62697. if (!this.spatialSound) {
  62698. this.spatialSound = true;
  62699. this._createSpatialParameters();
  62700. if (this.isPlaying && this.loop) {
  62701. this.stop();
  62702. this.play();
  62703. }
  62704. }
  62705. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62706. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62707. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62708. };
  62709. Sound.prototype.detachFromMesh = function () {
  62710. if (this._connectedMesh && this._registerFunc) {
  62711. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62712. this._registerFunc = null;
  62713. this._connectedMesh = null;
  62714. }
  62715. };
  62716. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62717. if (!node.getBoundingInfo) {
  62718. return;
  62719. }
  62720. var mesh = node;
  62721. var boundingInfo = mesh.getBoundingInfo();
  62722. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62723. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62724. this._updateDirection();
  62725. }
  62726. };
  62727. Sound.prototype.clone = function () {
  62728. var _this = this;
  62729. if (!this._streaming) {
  62730. var setBufferAndRun = function () {
  62731. if (_this._isReadyToPlay) {
  62732. clonedSound._audioBuffer = _this.getAudioBuffer();
  62733. clonedSound._isReadyToPlay = true;
  62734. if (clonedSound.autoplay) {
  62735. clonedSound.play();
  62736. }
  62737. }
  62738. else {
  62739. window.setTimeout(setBufferAndRun, 300);
  62740. }
  62741. };
  62742. var currentOptions = {
  62743. autoplay: this.autoplay, loop: this.loop,
  62744. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62745. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62746. refDistance: this.refDistance, distanceModel: this.distanceModel
  62747. };
  62748. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62749. if (this.useCustomAttenuation) {
  62750. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62751. }
  62752. clonedSound.setPosition(this._position);
  62753. clonedSound.setPlaybackRate(this._playbackRate);
  62754. setBufferAndRun();
  62755. return clonedSound;
  62756. }
  62757. // Can't clone a streaming sound
  62758. else {
  62759. return null;
  62760. }
  62761. };
  62762. Sound.prototype.getAudioBuffer = function () {
  62763. return this._audioBuffer;
  62764. };
  62765. Sound.prototype.serialize = function () {
  62766. var serializationObject = {
  62767. name: this.name,
  62768. url: this.name,
  62769. autoplay: this.autoplay,
  62770. loop: this.loop,
  62771. volume: this._volume,
  62772. spatialSound: this.spatialSound,
  62773. maxDistance: this.maxDistance,
  62774. rolloffFactor: this.rolloffFactor,
  62775. refDistance: this.refDistance,
  62776. distanceModel: this.distanceModel,
  62777. playbackRate: this._playbackRate,
  62778. panningModel: this._panningModel,
  62779. soundTrackId: this.soundTrackId
  62780. };
  62781. if (this.spatialSound) {
  62782. if (this._connectedMesh)
  62783. serializationObject.connectedMeshId = this._connectedMesh.id;
  62784. serializationObject.position = this._position.asArray();
  62785. serializationObject.refDistance = this.refDistance;
  62786. serializationObject.distanceModel = this.distanceModel;
  62787. serializationObject.isDirectional = this._isDirectional;
  62788. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62789. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62790. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62791. serializationObject.coneOuterGain = this._coneOuterGain;
  62792. }
  62793. return serializationObject;
  62794. };
  62795. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62796. var soundName = parsedSound.name;
  62797. var soundUrl;
  62798. if (parsedSound.url) {
  62799. soundUrl = rootUrl + parsedSound.url;
  62800. }
  62801. else {
  62802. soundUrl = rootUrl + soundName;
  62803. }
  62804. var options = {
  62805. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62806. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62807. rolloffFactor: parsedSound.rolloffFactor,
  62808. refDistance: parsedSound.refDistance,
  62809. distanceModel: parsedSound.distanceModel,
  62810. playbackRate: parsedSound.playbackRate
  62811. };
  62812. var newSound;
  62813. if (!sourceSound) {
  62814. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62815. scene._addPendingData(newSound);
  62816. }
  62817. else {
  62818. var setBufferAndRun = function () {
  62819. if (sourceSound._isReadyToPlay) {
  62820. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62821. newSound._isReadyToPlay = true;
  62822. if (newSound.autoplay) {
  62823. newSound.play();
  62824. }
  62825. }
  62826. else {
  62827. window.setTimeout(setBufferAndRun, 300);
  62828. }
  62829. };
  62830. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62831. setBufferAndRun();
  62832. }
  62833. if (parsedSound.position) {
  62834. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62835. newSound.setPosition(soundPosition);
  62836. }
  62837. if (parsedSound.isDirectional) {
  62838. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62839. if (parsedSound.localDirectionToMesh) {
  62840. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62841. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62842. }
  62843. }
  62844. if (parsedSound.connectedMeshId) {
  62845. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62846. if (connectedMesh) {
  62847. newSound.attachToMesh(connectedMesh);
  62848. }
  62849. }
  62850. return newSound;
  62851. };
  62852. return Sound;
  62853. }());
  62854. BABYLON.Sound = Sound;
  62855. })(BABYLON || (BABYLON = {}));
  62856. //# sourceMappingURL=babylon.sound.js.map
  62857. var BABYLON;
  62858. (function (BABYLON) {
  62859. var SoundTrack = /** @class */ (function () {
  62860. function SoundTrack(scene, options) {
  62861. this.id = -1;
  62862. this._isMainTrack = false;
  62863. this._isInitialized = false;
  62864. this._scene = scene;
  62865. this.soundCollection = new Array();
  62866. this._options = options;
  62867. if (!this._isMainTrack) {
  62868. this._scene.soundTracks.push(this);
  62869. this.id = this._scene.soundTracks.length - 1;
  62870. }
  62871. }
  62872. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62873. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62874. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62875. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62876. if (this._options) {
  62877. if (this._options.volume) {
  62878. this._outputAudioNode.gain.value = this._options.volume;
  62879. }
  62880. if (this._options.mainTrack) {
  62881. this._isMainTrack = this._options.mainTrack;
  62882. }
  62883. }
  62884. this._isInitialized = true;
  62885. }
  62886. };
  62887. SoundTrack.prototype.dispose = function () {
  62888. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62889. if (this._connectedAnalyser) {
  62890. this._connectedAnalyser.stopDebugCanvas();
  62891. }
  62892. while (this.soundCollection.length) {
  62893. this.soundCollection[0].dispose();
  62894. }
  62895. if (this._outputAudioNode) {
  62896. this._outputAudioNode.disconnect();
  62897. }
  62898. this._outputAudioNode = null;
  62899. }
  62900. };
  62901. SoundTrack.prototype.AddSound = function (sound) {
  62902. if (!this._isInitialized) {
  62903. this._initializeSoundTrackAudioGraph();
  62904. }
  62905. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62906. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62907. }
  62908. if (sound.soundTrackId) {
  62909. if (sound.soundTrackId === -1) {
  62910. this._scene.mainSoundTrack.RemoveSound(sound);
  62911. }
  62912. else {
  62913. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62914. }
  62915. }
  62916. this.soundCollection.push(sound);
  62917. sound.soundTrackId = this.id;
  62918. };
  62919. SoundTrack.prototype.RemoveSound = function (sound) {
  62920. var index = this.soundCollection.indexOf(sound);
  62921. if (index !== -1) {
  62922. this.soundCollection.splice(index, 1);
  62923. }
  62924. };
  62925. SoundTrack.prototype.setVolume = function (newVolume) {
  62926. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62927. this._outputAudioNode.gain.value = newVolume;
  62928. }
  62929. };
  62930. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62932. for (var i = 0; i < this.soundCollection.length; i++) {
  62933. this.soundCollection[i].switchPanningModelToHRTF();
  62934. }
  62935. }
  62936. };
  62937. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62938. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62939. for (var i = 0; i < this.soundCollection.length; i++) {
  62940. this.soundCollection[i].switchPanningModelToEqualPower();
  62941. }
  62942. }
  62943. };
  62944. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62945. if (this._connectedAnalyser) {
  62946. this._connectedAnalyser.stopDebugCanvas();
  62947. }
  62948. this._connectedAnalyser = analyser;
  62949. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62950. this._outputAudioNode.disconnect();
  62951. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62952. }
  62953. };
  62954. return SoundTrack;
  62955. }());
  62956. BABYLON.SoundTrack = SoundTrack;
  62957. })(BABYLON || (BABYLON = {}));
  62958. //# sourceMappingURL=babylon.soundtrack.js.map
  62959. var BABYLON;
  62960. (function (BABYLON) {
  62961. /**
  62962. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62963. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62964. */
  62965. var Analyser = /** @class */ (function () {
  62966. /**
  62967. * Creates a new analyser
  62968. * @param scene defines hosting scene
  62969. */
  62970. function Analyser(scene) {
  62971. /**
  62972. * Gets or sets the smoothing
  62973. * @ignorenaming
  62974. */
  62975. this.SMOOTHING = 0.75;
  62976. /**
  62977. * Gets or sets the FFT table size
  62978. * @ignorenaming
  62979. */
  62980. this.FFT_SIZE = 512;
  62981. /**
  62982. * Gets or sets the bar graph amplitude
  62983. * @ignorenaming
  62984. */
  62985. this.BARGRAPHAMPLITUDE = 256;
  62986. /**
  62987. * Gets or sets the position of the debug canvas
  62988. * @ignorenaming
  62989. */
  62990. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62991. /**
  62992. * Gets or sets the debug canvas size
  62993. * @ignorenaming
  62994. */
  62995. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62996. this._scene = scene;
  62997. this._audioEngine = BABYLON.Engine.audioEngine;
  62998. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62999. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63000. this._webAudioAnalyser.minDecibels = -140;
  63001. this._webAudioAnalyser.maxDecibels = 0;
  63002. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63003. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63004. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63005. }
  63006. }
  63007. /**
  63008. * Get the number of data values you will have to play with for the visualization
  63009. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63010. * @returns a number
  63011. */
  63012. Analyser.prototype.getFrequencyBinCount = function () {
  63013. if (this._audioEngine.canUseWebAudio) {
  63014. return this._webAudioAnalyser.frequencyBinCount;
  63015. }
  63016. else {
  63017. return 0;
  63018. }
  63019. };
  63020. /**
  63021. * Gets the current frequency data as a byte array
  63022. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63023. * @returns a Uint8Array
  63024. */
  63025. Analyser.prototype.getByteFrequencyData = function () {
  63026. if (this._audioEngine.canUseWebAudio) {
  63027. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63028. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63029. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63030. }
  63031. return this._byteFreqs;
  63032. };
  63033. /**
  63034. * Gets the current waveform as a byte array
  63035. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63036. * @returns a Uint8Array
  63037. */
  63038. Analyser.prototype.getByteTimeDomainData = function () {
  63039. if (this._audioEngine.canUseWebAudio) {
  63040. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63041. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63042. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63043. }
  63044. return this._byteTime;
  63045. };
  63046. /**
  63047. * Gets the current frequency data as a float array
  63048. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63049. * @returns a Float32Array
  63050. */
  63051. Analyser.prototype.getFloatFrequencyData = function () {
  63052. if (this._audioEngine.canUseWebAudio) {
  63053. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63054. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63055. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63056. }
  63057. return this._floatFreqs;
  63058. };
  63059. /**
  63060. * Renders the debug canvas
  63061. */
  63062. Analyser.prototype.drawDebugCanvas = function () {
  63063. var _this = this;
  63064. if (this._audioEngine.canUseWebAudio) {
  63065. if (!this._debugCanvas) {
  63066. this._debugCanvas = document.createElement("canvas");
  63067. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63068. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63069. this._debugCanvas.style.position = "absolute";
  63070. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63071. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63072. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63073. document.body.appendChild(this._debugCanvas);
  63074. this._registerFunc = function () {
  63075. _this.drawDebugCanvas();
  63076. };
  63077. this._scene.registerBeforeRender(this._registerFunc);
  63078. }
  63079. if (this._registerFunc && this._debugCanvasContext) {
  63080. var workingArray = this.getByteFrequencyData();
  63081. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63082. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63083. // Draw the frequency domain chart.
  63084. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63085. var value = workingArray[i];
  63086. var percent = value / this.BARGRAPHAMPLITUDE;
  63087. var height = this.DEBUGCANVASSIZE.height * percent;
  63088. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63089. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63090. var hue = i / this.getFrequencyBinCount() * 360;
  63091. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63092. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63093. }
  63094. }
  63095. }
  63096. };
  63097. /**
  63098. * Stops rendering the debug canvas and removes it
  63099. */
  63100. Analyser.prototype.stopDebugCanvas = function () {
  63101. if (this._debugCanvas) {
  63102. if (this._registerFunc) {
  63103. this._scene.unregisterBeforeRender(this._registerFunc);
  63104. this._registerFunc = null;
  63105. }
  63106. document.body.removeChild(this._debugCanvas);
  63107. this._debugCanvas = null;
  63108. this._debugCanvasContext = null;
  63109. }
  63110. };
  63111. /**
  63112. * Connects two audio nodes
  63113. * @param inputAudioNode defines first node to connect
  63114. * @param outputAudioNode defines second node to connect
  63115. */
  63116. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63117. if (this._audioEngine.canUseWebAudio) {
  63118. inputAudioNode.connect(this._webAudioAnalyser);
  63119. this._webAudioAnalyser.connect(outputAudioNode);
  63120. }
  63121. };
  63122. /**
  63123. * Releases all associated resources
  63124. */
  63125. Analyser.prototype.dispose = function () {
  63126. if (this._audioEngine.canUseWebAudio) {
  63127. this._webAudioAnalyser.disconnect();
  63128. }
  63129. };
  63130. return Analyser;
  63131. }());
  63132. BABYLON.Analyser = Analyser;
  63133. })(BABYLON || (BABYLON = {}));
  63134. //# sourceMappingURL=babylon.analyser.js.map
  63135. var BABYLON;
  63136. (function (BABYLON) {
  63137. var CubeTexture = /** @class */ (function (_super) {
  63138. __extends(CubeTexture, _super);
  63139. /**
  63140. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63141. * as prefiltered data.
  63142. * @param rootUrl defines the url of the texture or the root name of the six images
  63143. * @param scene defines the scene the texture is attached to
  63144. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63145. * @param noMipmap defines if mipmaps should be created or not
  63146. * @param files defines the six files to load for the different faces
  63147. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63148. * @param onError defines a callback triggered in case of error during load
  63149. * @param format defines the internal format to use for the texture once loaded
  63150. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63151. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63152. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63153. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63154. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63155. * @return the cube texture
  63156. */
  63157. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63158. if (extensions === void 0) { extensions = null; }
  63159. if (noMipmap === void 0) { noMipmap = false; }
  63160. if (files === void 0) { files = null; }
  63161. if (onLoad === void 0) { onLoad = null; }
  63162. if (onError === void 0) { onError = null; }
  63163. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63164. if (prefiltered === void 0) { prefiltered = false; }
  63165. if (forcedExtension === void 0) { forcedExtension = null; }
  63166. if (createPolynomials === void 0) { createPolynomials = false; }
  63167. if (lodScale === void 0) { lodScale = 0.8; }
  63168. if (lodOffset === void 0) { lodOffset = 0; }
  63169. var _this = _super.call(this, scene) || this;
  63170. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63171. /**
  63172. * Gets or sets the center of the bounding box associated with the cube texture
  63173. * It must define where the camera used to render the texture was set
  63174. */
  63175. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63176. _this._rotationY = 0;
  63177. /** @hidden */
  63178. _this._prefiltered = false;
  63179. _this.name = rootUrl;
  63180. _this.url = rootUrl;
  63181. _this._noMipmap = noMipmap;
  63182. _this.hasAlpha = false;
  63183. _this._format = format;
  63184. _this.isCube = true;
  63185. _this._textureMatrix = BABYLON.Matrix.Identity();
  63186. _this._createPolynomials = createPolynomials;
  63187. if (!rootUrl && !files) {
  63188. return _this;
  63189. }
  63190. var lastDot = rootUrl.lastIndexOf(".");
  63191. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63192. var isDDS = (extension === ".dds");
  63193. var isEnv = (extension === ".env");
  63194. if (isEnv) {
  63195. _this.gammaSpace = false;
  63196. _this._prefiltered = false;
  63197. }
  63198. else {
  63199. _this._prefiltered = prefiltered;
  63200. if (prefiltered) {
  63201. _this.gammaSpace = false;
  63202. }
  63203. }
  63204. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63205. if (!files) {
  63206. if (!isEnv && !isDDS && !extensions) {
  63207. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63208. }
  63209. files = [];
  63210. if (extensions) {
  63211. for (var index = 0; index < extensions.length; index++) {
  63212. files.push(rootUrl + extensions[index]);
  63213. }
  63214. }
  63215. }
  63216. _this._files = files;
  63217. if (!_this._texture) {
  63218. if (!scene.useDelayedTextureLoading) {
  63219. if (prefiltered) {
  63220. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63221. }
  63222. else {
  63223. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63224. }
  63225. }
  63226. else {
  63227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63228. }
  63229. }
  63230. else if (onLoad) {
  63231. if (_this._texture.isReady) {
  63232. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63233. }
  63234. else {
  63235. _this._texture.onLoadedObservable.add(onLoad);
  63236. }
  63237. }
  63238. return _this;
  63239. }
  63240. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63241. get: function () {
  63242. return this._boundingBoxSize;
  63243. },
  63244. /**
  63245. * Gets or sets the size of the bounding box associated with the cube texture
  63246. * When defined, the cubemap will switch to local mode
  63247. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63248. * @example https://www.babylonjs-playground.com/#RNASML
  63249. */
  63250. set: function (value) {
  63251. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63252. return;
  63253. }
  63254. this._boundingBoxSize = value;
  63255. var scene = this.getScene();
  63256. if (scene) {
  63257. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63258. }
  63259. },
  63260. enumerable: true,
  63261. configurable: true
  63262. });
  63263. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63264. /**
  63265. * Gets texture matrix rotation angle around Y axis radians.
  63266. */
  63267. get: function () {
  63268. return this._rotationY;
  63269. },
  63270. /**
  63271. * Sets texture matrix rotation angle around Y axis in radians.
  63272. */
  63273. set: function (value) {
  63274. this._rotationY = value;
  63275. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63276. },
  63277. enumerable: true,
  63278. configurable: true
  63279. });
  63280. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63281. var rootUrlKey = "";
  63282. files.forEach(function (url) { return rootUrlKey += url; });
  63283. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63284. };
  63285. /**
  63286. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63287. * @param url defines the url of the prefiltered texture
  63288. * @param scene defines the scene the texture is attached to
  63289. * @param forcedExtension defines the extension of the file if different from the url
  63290. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63291. * @return the prefiltered texture
  63292. */
  63293. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63294. if (forcedExtension === void 0) { forcedExtension = null; }
  63295. if (createPolynomials === void 0) { createPolynomials = true; }
  63296. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63297. };
  63298. // Methods
  63299. CubeTexture.prototype.delayLoad = function () {
  63300. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63301. return;
  63302. }
  63303. var scene = this.getScene();
  63304. if (!scene) {
  63305. return;
  63306. }
  63307. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63308. this._texture = this._getFromCache(this.url, this._noMipmap);
  63309. if (!this._texture) {
  63310. if (this._prefiltered) {
  63311. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63312. }
  63313. else {
  63314. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63315. }
  63316. }
  63317. };
  63318. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63319. return this._textureMatrix;
  63320. };
  63321. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63322. this._textureMatrix = value;
  63323. };
  63324. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63325. var texture = BABYLON.SerializationHelper.Parse(function () {
  63326. var prefiltered = false;
  63327. if (parsedTexture.prefiltered) {
  63328. prefiltered = parsedTexture.prefiltered;
  63329. }
  63330. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63331. }, parsedTexture, scene);
  63332. // Local Cubemaps
  63333. if (parsedTexture.boundingBoxPosition) {
  63334. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63335. }
  63336. if (parsedTexture.boundingBoxSize) {
  63337. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63338. }
  63339. // Animations
  63340. if (parsedTexture.animations) {
  63341. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63342. var parsedAnimation = parsedTexture.animations[animationIndex];
  63343. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63344. }
  63345. }
  63346. return texture;
  63347. };
  63348. CubeTexture.prototype.clone = function () {
  63349. var _this = this;
  63350. return BABYLON.SerializationHelper.Clone(function () {
  63351. var scene = _this.getScene();
  63352. if (!scene) {
  63353. return _this;
  63354. }
  63355. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63356. }, this);
  63357. };
  63358. __decorate([
  63359. BABYLON.serialize("rotationY")
  63360. ], CubeTexture.prototype, "_rotationY", void 0);
  63361. return CubeTexture;
  63362. }(BABYLON.BaseTexture));
  63363. BABYLON.CubeTexture = CubeTexture;
  63364. })(BABYLON || (BABYLON = {}));
  63365. //# sourceMappingURL=babylon.cubeTexture.js.map
  63366. var BABYLON;
  63367. (function (BABYLON) {
  63368. var RenderTargetTexture = /** @class */ (function (_super) {
  63369. __extends(RenderTargetTexture, _super);
  63370. /**
  63371. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63372. * or used a shadow, depth texture...
  63373. * @param name The friendly name of the texture
  63374. * @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)
  63375. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63376. * @param generateMipMaps True if mip maps need to be generated after render.
  63377. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63378. * @param type The type of the buffer in the RTT (int, half float, float...)
  63379. * @param isCube True if a cube texture needs to be created
  63380. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63381. * @param generateDepthBuffer True to generate a depth buffer
  63382. * @param generateStencilBuffer True to generate a stencil buffer
  63383. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63384. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63385. */
  63386. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63387. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63388. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63389. if (isCube === void 0) { isCube = false; }
  63390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63391. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63392. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63393. if (isMulti === void 0) { isMulti = false; }
  63394. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63395. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63396. _this.isCube = isCube;
  63397. /**
  63398. * Use this list to define the list of mesh you want to render.
  63399. */
  63400. _this.renderList = new Array();
  63401. _this.renderParticles = true;
  63402. _this.renderSprites = false;
  63403. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63404. _this.ignoreCameraViewport = false;
  63405. // Events
  63406. /**
  63407. * An event triggered when the texture is unbind.
  63408. */
  63409. _this.onBeforeBindObservable = new BABYLON.Observable();
  63410. /**
  63411. * An event triggered when the texture is unbind.
  63412. */
  63413. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63414. /**
  63415. * An event triggered before rendering the texture
  63416. */
  63417. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63418. /**
  63419. * An event triggered after rendering the texture
  63420. */
  63421. _this.onAfterRenderObservable = new BABYLON.Observable();
  63422. /**
  63423. * An event triggered after the texture clear
  63424. */
  63425. _this.onClearObservable = new BABYLON.Observable();
  63426. _this._currentRefreshId = -1;
  63427. _this._refreshRate = 1;
  63428. _this._samples = 1;
  63429. /**
  63430. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63431. * It must define where the camera used to render the texture is set
  63432. */
  63433. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63434. scene = _this.getScene();
  63435. if (!scene) {
  63436. return _this;
  63437. }
  63438. _this._engine = scene.getEngine();
  63439. _this.name = name;
  63440. _this.isRenderTarget = true;
  63441. _this._initialSizeParameter = size;
  63442. _this._processSizeParameter(size);
  63443. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63444. });
  63445. _this._generateMipMaps = generateMipMaps ? true : false;
  63446. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63447. // Rendering groups
  63448. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63449. if (isMulti) {
  63450. return _this;
  63451. }
  63452. _this._renderTargetOptions = {
  63453. generateMipMaps: generateMipMaps,
  63454. type: type,
  63455. format: format,
  63456. samplingMode: samplingMode,
  63457. generateDepthBuffer: generateDepthBuffer,
  63458. generateStencilBuffer: generateStencilBuffer
  63459. };
  63460. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63461. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63462. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63463. }
  63464. if (isCube) {
  63465. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63466. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63467. _this._textureMatrix = BABYLON.Matrix.Identity();
  63468. }
  63469. else {
  63470. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63471. }
  63472. return _this;
  63473. }
  63474. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63475. get: function () {
  63476. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63477. },
  63478. enumerable: true,
  63479. configurable: true
  63480. });
  63481. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63482. get: function () {
  63483. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63484. },
  63485. enumerable: true,
  63486. configurable: true
  63487. });
  63488. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63489. get: function () {
  63490. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63491. },
  63492. enumerable: true,
  63493. configurable: true
  63494. });
  63495. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63496. set: function (callback) {
  63497. if (this._onAfterUnbindObserver) {
  63498. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63499. }
  63500. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63501. },
  63502. enumerable: true,
  63503. configurable: true
  63504. });
  63505. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63506. set: function (callback) {
  63507. if (this._onBeforeRenderObserver) {
  63508. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63509. }
  63510. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63511. },
  63512. enumerable: true,
  63513. configurable: true
  63514. });
  63515. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63516. set: function (callback) {
  63517. if (this._onAfterRenderObserver) {
  63518. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63519. }
  63520. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63521. },
  63522. enumerable: true,
  63523. configurable: true
  63524. });
  63525. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63526. set: function (callback) {
  63527. if (this._onClearObserver) {
  63528. this.onClearObservable.remove(this._onClearObserver);
  63529. }
  63530. this._onClearObserver = this.onClearObservable.add(callback);
  63531. },
  63532. enumerable: true,
  63533. configurable: true
  63534. });
  63535. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63536. get: function () {
  63537. return this._renderTargetOptions;
  63538. },
  63539. enumerable: true,
  63540. configurable: true
  63541. });
  63542. RenderTargetTexture.prototype._onRatioRescale = function () {
  63543. if (this._sizeRatio) {
  63544. this.resize(this._initialSizeParameter);
  63545. }
  63546. };
  63547. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63548. get: function () {
  63549. return this._boundingBoxSize;
  63550. },
  63551. /**
  63552. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63553. * When defined, the cubemap will switch to local mode
  63554. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63555. * @example https://www.babylonjs-playground.com/#RNASML
  63556. */
  63557. set: function (value) {
  63558. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63559. return;
  63560. }
  63561. this._boundingBoxSize = value;
  63562. var scene = this.getScene();
  63563. if (scene) {
  63564. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63565. }
  63566. },
  63567. enumerable: true,
  63568. configurable: true
  63569. });
  63570. /**
  63571. * Creates a depth stencil texture.
  63572. * This is only available in WebGL 2 or with the depth texture extension available.
  63573. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63574. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63575. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63576. */
  63577. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63578. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63579. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63580. if (generateStencil === void 0) { generateStencil = false; }
  63581. if (!this.getScene()) {
  63582. return;
  63583. }
  63584. var engine = this.getScene().getEngine();
  63585. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63586. bilinearFiltering: bilinearFiltering,
  63587. comparisonFunction: comparisonFunction,
  63588. generateStencil: generateStencil,
  63589. isCube: this.isCube
  63590. });
  63591. engine.setFrameBufferDepthStencilTexture(this);
  63592. };
  63593. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63594. if (size.ratio) {
  63595. this._sizeRatio = size.ratio;
  63596. this._size = {
  63597. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63598. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63599. };
  63600. }
  63601. else {
  63602. this._size = size;
  63603. }
  63604. };
  63605. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63606. get: function () {
  63607. return this._samples;
  63608. },
  63609. set: function (value) {
  63610. if (this._samples === value) {
  63611. return;
  63612. }
  63613. var scene = this.getScene();
  63614. if (!scene) {
  63615. return;
  63616. }
  63617. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63618. },
  63619. enumerable: true,
  63620. configurable: true
  63621. });
  63622. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63623. this._currentRefreshId = -1;
  63624. };
  63625. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63626. get: function () {
  63627. return this._refreshRate;
  63628. },
  63629. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63630. set: function (value) {
  63631. this._refreshRate = value;
  63632. this.resetRefreshCounter();
  63633. },
  63634. enumerable: true,
  63635. configurable: true
  63636. });
  63637. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63638. if (!this._postProcessManager) {
  63639. var scene = this.getScene();
  63640. if (!scene) {
  63641. return;
  63642. }
  63643. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63644. this._postProcesses = new Array();
  63645. }
  63646. this._postProcesses.push(postProcess);
  63647. this._postProcesses[0].autoClear = false;
  63648. };
  63649. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63650. if (!this._postProcesses) {
  63651. return;
  63652. }
  63653. if (dispose) {
  63654. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63655. var postProcess = _a[_i];
  63656. postProcess.dispose();
  63657. }
  63658. }
  63659. this._postProcesses = [];
  63660. };
  63661. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63662. if (!this._postProcesses) {
  63663. return;
  63664. }
  63665. var index = this._postProcesses.indexOf(postProcess);
  63666. if (index === -1) {
  63667. return;
  63668. }
  63669. this._postProcesses.splice(index, 1);
  63670. if (this._postProcesses.length > 0) {
  63671. this._postProcesses[0].autoClear = false;
  63672. }
  63673. };
  63674. RenderTargetTexture.prototype._shouldRender = function () {
  63675. if (this._currentRefreshId === -1) { // At least render once
  63676. this._currentRefreshId = 1;
  63677. return true;
  63678. }
  63679. if (this.refreshRate === this._currentRefreshId) {
  63680. this._currentRefreshId = 1;
  63681. return true;
  63682. }
  63683. this._currentRefreshId++;
  63684. return false;
  63685. };
  63686. RenderTargetTexture.prototype.getRenderSize = function () {
  63687. if (this._size.width) {
  63688. return this._size.width;
  63689. }
  63690. return this._size;
  63691. };
  63692. RenderTargetTexture.prototype.getRenderWidth = function () {
  63693. if (this._size.width) {
  63694. return this._size.width;
  63695. }
  63696. return this._size;
  63697. };
  63698. RenderTargetTexture.prototype.getRenderHeight = function () {
  63699. if (this._size.width) {
  63700. return this._size.height;
  63701. }
  63702. return this._size;
  63703. };
  63704. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63705. get: function () {
  63706. return true;
  63707. },
  63708. enumerable: true,
  63709. configurable: true
  63710. });
  63711. RenderTargetTexture.prototype.scale = function (ratio) {
  63712. var newSize = this.getRenderSize() * ratio;
  63713. this.resize(newSize);
  63714. };
  63715. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63716. if (this.isCube) {
  63717. return this._textureMatrix;
  63718. }
  63719. return _super.prototype.getReflectionTextureMatrix.call(this);
  63720. };
  63721. RenderTargetTexture.prototype.resize = function (size) {
  63722. this.releaseInternalTexture();
  63723. var scene = this.getScene();
  63724. if (!scene) {
  63725. return;
  63726. }
  63727. this._processSizeParameter(size);
  63728. if (this.isCube) {
  63729. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63730. }
  63731. else {
  63732. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63733. }
  63734. };
  63735. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63736. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63737. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63738. var scene = this.getScene();
  63739. if (!scene) {
  63740. return;
  63741. }
  63742. var engine = scene.getEngine();
  63743. if (this.useCameraPostProcesses !== undefined) {
  63744. useCameraPostProcess = this.useCameraPostProcesses;
  63745. }
  63746. if (this._waitingRenderList) {
  63747. this.renderList = [];
  63748. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63749. var id = this._waitingRenderList[index];
  63750. var mesh_1 = scene.getMeshByID(id);
  63751. if (mesh_1) {
  63752. this.renderList.push(mesh_1);
  63753. }
  63754. }
  63755. delete this._waitingRenderList;
  63756. }
  63757. // Is predicate defined?
  63758. if (this.renderListPredicate) {
  63759. if (this.renderList) {
  63760. this.renderList.splice(0); // Clear previous renderList
  63761. }
  63762. else {
  63763. this.renderList = [];
  63764. }
  63765. var scene = this.getScene();
  63766. if (!scene) {
  63767. return;
  63768. }
  63769. var sceneMeshes = scene.meshes;
  63770. for (var index = 0; index < sceneMeshes.length; index++) {
  63771. var mesh = sceneMeshes[index];
  63772. if (this.renderListPredicate(mesh)) {
  63773. this.renderList.push(mesh);
  63774. }
  63775. }
  63776. }
  63777. this.onBeforeBindObservable.notifyObservers(this);
  63778. // Set custom projection.
  63779. // Needs to be before binding to prevent changing the aspect ratio.
  63780. var camera;
  63781. if (this.activeCamera) {
  63782. camera = this.activeCamera;
  63783. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63784. if (this.activeCamera !== scene.activeCamera) {
  63785. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63786. }
  63787. }
  63788. else {
  63789. camera = scene.activeCamera;
  63790. if (camera) {
  63791. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63792. }
  63793. }
  63794. // Prepare renderingManager
  63795. this._renderingManager.reset();
  63796. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63797. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63798. var sceneRenderId = scene.getRenderId();
  63799. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63800. var mesh = currentRenderList[meshIndex];
  63801. if (mesh) {
  63802. if (!mesh.isReady(this.refreshRate === 0)) {
  63803. this.resetRefreshCounter();
  63804. continue;
  63805. }
  63806. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63807. var isMasked = void 0;
  63808. if (!this.renderList && camera) {
  63809. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63810. }
  63811. else {
  63812. isMasked = false;
  63813. }
  63814. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63815. mesh._activate(sceneRenderId);
  63816. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63817. var subMesh = mesh.subMeshes[subIndex];
  63818. scene._activeIndices.addCount(subMesh.indexCount, false);
  63819. this._renderingManager.dispatch(subMesh, mesh);
  63820. }
  63821. }
  63822. }
  63823. }
  63824. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63825. var particleSystem = scene.particleSystems[particleIndex];
  63826. var emitter = particleSystem.emitter;
  63827. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63828. continue;
  63829. }
  63830. if (currentRenderList.indexOf(emitter) >= 0) {
  63831. this._renderingManager.dispatchParticles(particleSystem);
  63832. }
  63833. }
  63834. if (this.isCube) {
  63835. for (var face = 0; face < 6; face++) {
  63836. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63837. scene.incrementRenderId();
  63838. scene.resetCachedMaterial();
  63839. }
  63840. }
  63841. else {
  63842. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63843. }
  63844. this.onAfterUnbindObservable.notifyObservers(this);
  63845. if (scene.activeCamera) {
  63846. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63847. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63848. }
  63849. engine.setViewport(scene.activeCamera.viewport);
  63850. }
  63851. scene.resetCachedMaterial();
  63852. };
  63853. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63854. var minimum = 128;
  63855. var x = renderDimension * scale;
  63856. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63857. // Ensure we don't exceed the render dimension (while staying POT)
  63858. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63859. };
  63860. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63861. var _this = this;
  63862. if (!this._texture) {
  63863. return;
  63864. }
  63865. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63866. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63867. });
  63868. };
  63869. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63870. var scene = this.getScene();
  63871. if (!scene) {
  63872. return;
  63873. }
  63874. var engine = scene.getEngine();
  63875. if (!this._texture) {
  63876. return;
  63877. }
  63878. // Bind
  63879. if (this._postProcessManager) {
  63880. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63881. }
  63882. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63883. if (this._texture) {
  63884. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63885. }
  63886. }
  63887. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63888. // Clear
  63889. if (this.onClearObservable.hasObservers()) {
  63890. this.onClearObservable.notifyObservers(engine);
  63891. }
  63892. else {
  63893. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63894. }
  63895. if (!this._doNotChangeAspectRatio) {
  63896. scene.updateTransformMatrix(true);
  63897. }
  63898. // Render
  63899. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63900. if (this._postProcessManager) {
  63901. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63902. }
  63903. else if (useCameraPostProcess) {
  63904. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63905. }
  63906. if (!this._doNotChangeAspectRatio) {
  63907. scene.updateTransformMatrix(true);
  63908. }
  63909. // Dump ?
  63910. if (dumpForDebug) {
  63911. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63912. }
  63913. // Unbind
  63914. if (!this.isCube || faceIndex === 5) {
  63915. if (this.isCube) {
  63916. if (faceIndex === 5) {
  63917. engine.generateMipMapsForCubemap(this._texture);
  63918. }
  63919. }
  63920. this.unbindFrameBuffer(engine, faceIndex);
  63921. }
  63922. else {
  63923. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63924. }
  63925. };
  63926. /**
  63927. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63928. * This allowed control for front to back rendering or reversly depending of the special needs.
  63929. *
  63930. * @param renderingGroupId The rendering group id corresponding to its index
  63931. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63932. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63933. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63934. */
  63935. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63936. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63937. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63938. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63939. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63940. };
  63941. /**
  63942. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63943. *
  63944. * @param renderingGroupId The rendering group id corresponding to its index
  63945. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63946. */
  63947. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63948. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63949. };
  63950. RenderTargetTexture.prototype.clone = function () {
  63951. var textureSize = this.getSize();
  63952. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63953. // Base texture
  63954. newTexture.hasAlpha = this.hasAlpha;
  63955. newTexture.level = this.level;
  63956. // RenderTarget Texture
  63957. newTexture.coordinatesMode = this.coordinatesMode;
  63958. if (this.renderList) {
  63959. newTexture.renderList = this.renderList.slice(0);
  63960. }
  63961. return newTexture;
  63962. };
  63963. RenderTargetTexture.prototype.serialize = function () {
  63964. if (!this.name) {
  63965. return null;
  63966. }
  63967. var serializationObject = _super.prototype.serialize.call(this);
  63968. serializationObject.renderTargetSize = this.getRenderSize();
  63969. serializationObject.renderList = [];
  63970. if (this.renderList) {
  63971. for (var index = 0; index < this.renderList.length; index++) {
  63972. serializationObject.renderList.push(this.renderList[index].id);
  63973. }
  63974. }
  63975. return serializationObject;
  63976. };
  63977. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63978. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63979. var objBuffer = this.getInternalTexture();
  63980. var scene = this.getScene();
  63981. if (objBuffer && scene) {
  63982. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63983. }
  63984. };
  63985. RenderTargetTexture.prototype.dispose = function () {
  63986. if (this._postProcessManager) {
  63987. this._postProcessManager.dispose();
  63988. this._postProcessManager = null;
  63989. }
  63990. this.clearPostProcesses(true);
  63991. if (this._resizeObserver) {
  63992. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63993. this._resizeObserver = null;
  63994. }
  63995. this.renderList = null;
  63996. // Remove from custom render targets
  63997. var scene = this.getScene();
  63998. if (!scene) {
  63999. return;
  64000. }
  64001. var index = scene.customRenderTargets.indexOf(this);
  64002. if (index >= 0) {
  64003. scene.customRenderTargets.splice(index, 1);
  64004. }
  64005. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64006. var camera = _a[_i];
  64007. index = camera.customRenderTargets.indexOf(this);
  64008. if (index >= 0) {
  64009. camera.customRenderTargets.splice(index, 1);
  64010. }
  64011. }
  64012. _super.prototype.dispose.call(this);
  64013. };
  64014. RenderTargetTexture.prototype._rebuild = function () {
  64015. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64016. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64017. }
  64018. if (this._postProcessManager) {
  64019. this._postProcessManager._rebuild();
  64020. }
  64021. };
  64022. /**
  64023. * Clear the info related to rendering groups preventing retention point in material dispose.
  64024. */
  64025. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64026. if (this._renderingManager) {
  64027. this._renderingManager.freeRenderingGroups();
  64028. }
  64029. };
  64030. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64031. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64032. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64033. return RenderTargetTexture;
  64034. }(BABYLON.Texture));
  64035. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64036. })(BABYLON || (BABYLON = {}));
  64037. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64038. var BABYLON;
  64039. (function (BABYLON) {
  64040. ;
  64041. var MultiRenderTarget = /** @class */ (function (_super) {
  64042. __extends(MultiRenderTarget, _super);
  64043. function MultiRenderTarget(name, size, count, scene, options) {
  64044. var _this = this;
  64045. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64046. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64047. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64048. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64049. _this._engine = scene.getEngine();
  64050. if (!_this.isSupported) {
  64051. _this.dispose();
  64052. return;
  64053. }
  64054. var types = [];
  64055. var samplingModes = [];
  64056. for (var i = 0; i < count; i++) {
  64057. if (options && options.types && options.types[i] !== undefined) {
  64058. types.push(options.types[i]);
  64059. }
  64060. else {
  64061. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64062. }
  64063. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64064. samplingModes.push(options.samplingModes[i]);
  64065. }
  64066. else {
  64067. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64068. }
  64069. }
  64070. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64071. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64072. _this._size = size;
  64073. _this._multiRenderTargetOptions = {
  64074. samplingModes: samplingModes,
  64075. generateMipMaps: generateMipMaps,
  64076. generateDepthBuffer: generateDepthBuffer,
  64077. generateStencilBuffer: generateStencilBuffer,
  64078. generateDepthTexture: generateDepthTexture,
  64079. types: types,
  64080. textureCount: count
  64081. };
  64082. _this._createInternalTextures();
  64083. _this._createTextures();
  64084. return _this;
  64085. }
  64086. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64087. get: function () {
  64088. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64089. },
  64090. enumerable: true,
  64091. configurable: true
  64092. });
  64093. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64094. get: function () {
  64095. return this._textures;
  64096. },
  64097. enumerable: true,
  64098. configurable: true
  64099. });
  64100. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64101. get: function () {
  64102. return this._textures[this._textures.length - 1];
  64103. },
  64104. enumerable: true,
  64105. configurable: true
  64106. });
  64107. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64108. set: function (wrap) {
  64109. if (this._textures) {
  64110. for (var i = 0; i < this._textures.length; i++) {
  64111. this._textures[i].wrapU = wrap;
  64112. }
  64113. }
  64114. },
  64115. enumerable: true,
  64116. configurable: true
  64117. });
  64118. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64119. set: function (wrap) {
  64120. if (this._textures) {
  64121. for (var i = 0; i < this._textures.length; i++) {
  64122. this._textures[i].wrapV = wrap;
  64123. }
  64124. }
  64125. },
  64126. enumerable: true,
  64127. configurable: true
  64128. });
  64129. MultiRenderTarget.prototype._rebuild = function () {
  64130. this.releaseInternalTextures();
  64131. this._createInternalTextures();
  64132. for (var i = 0; i < this._internalTextures.length; i++) {
  64133. var texture = this._textures[i];
  64134. texture._texture = this._internalTextures[i];
  64135. }
  64136. // Keeps references to frame buffer and stencil/depth buffer
  64137. this._texture = this._internalTextures[0];
  64138. };
  64139. MultiRenderTarget.prototype._createInternalTextures = function () {
  64140. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64141. };
  64142. MultiRenderTarget.prototype._createTextures = function () {
  64143. this._textures = [];
  64144. for (var i = 0; i < this._internalTextures.length; i++) {
  64145. var texture = new BABYLON.Texture(null, this.getScene());
  64146. texture._texture = this._internalTextures[i];
  64147. this._textures.push(texture);
  64148. }
  64149. // Keeps references to frame buffer and stencil/depth buffer
  64150. this._texture = this._internalTextures[0];
  64151. };
  64152. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64153. get: function () {
  64154. return this._samples;
  64155. },
  64156. set: function (value) {
  64157. if (this._samples === value) {
  64158. return;
  64159. }
  64160. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64161. },
  64162. enumerable: true,
  64163. configurable: true
  64164. });
  64165. MultiRenderTarget.prototype.resize = function (size) {
  64166. this.releaseInternalTextures();
  64167. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64168. this._createInternalTextures();
  64169. };
  64170. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64171. var _this = this;
  64172. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64173. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64174. });
  64175. };
  64176. MultiRenderTarget.prototype.dispose = function () {
  64177. this.releaseInternalTextures();
  64178. _super.prototype.dispose.call(this);
  64179. };
  64180. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64181. if (!this._internalTextures) {
  64182. return;
  64183. }
  64184. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64185. if (this._internalTextures[i] !== undefined) {
  64186. this._internalTextures[i].dispose();
  64187. this._internalTextures.splice(i, 1);
  64188. }
  64189. }
  64190. };
  64191. return MultiRenderTarget;
  64192. }(BABYLON.RenderTargetTexture));
  64193. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64194. })(BABYLON || (BABYLON = {}));
  64195. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64196. var BABYLON;
  64197. (function (BABYLON) {
  64198. var MirrorTexture = /** @class */ (function (_super) {
  64199. __extends(MirrorTexture, _super);
  64200. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64201. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64203. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64204. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64205. _this.scene = scene;
  64206. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64207. _this._transformMatrix = BABYLON.Matrix.Zero();
  64208. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64209. _this._adaptiveBlurKernel = 0;
  64210. _this._blurKernelX = 0;
  64211. _this._blurKernelY = 0;
  64212. _this._blurRatio = 1.0;
  64213. _this.ignoreCameraViewport = true;
  64214. _this._updateGammaSpace();
  64215. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64216. _this._updateGammaSpace;
  64217. });
  64218. _this.onBeforeRenderObservable.add(function () {
  64219. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64220. _this._savedViewMatrix = scene.getViewMatrix();
  64221. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64222. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64223. scene.clipPlane = _this.mirrorPlane;
  64224. scene.getEngine().cullBackFaces = false;
  64225. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64226. });
  64227. _this.onAfterRenderObservable.add(function () {
  64228. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64229. scene.getEngine().cullBackFaces = true;
  64230. scene._mirroredCameraPosition = null;
  64231. delete scene.clipPlane;
  64232. });
  64233. return _this;
  64234. }
  64235. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64236. get: function () {
  64237. return this._blurRatio;
  64238. },
  64239. set: function (value) {
  64240. if (this._blurRatio === value) {
  64241. return;
  64242. }
  64243. this._blurRatio = value;
  64244. this._preparePostProcesses();
  64245. },
  64246. enumerable: true,
  64247. configurable: true
  64248. });
  64249. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64250. set: function (value) {
  64251. this._adaptiveBlurKernel = value;
  64252. this._autoComputeBlurKernel();
  64253. },
  64254. enumerable: true,
  64255. configurable: true
  64256. });
  64257. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64258. set: function (value) {
  64259. this.blurKernelX = value;
  64260. this.blurKernelY = value;
  64261. },
  64262. enumerable: true,
  64263. configurable: true
  64264. });
  64265. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64266. get: function () {
  64267. return this._blurKernelX;
  64268. },
  64269. set: function (value) {
  64270. if (this._blurKernelX === value) {
  64271. return;
  64272. }
  64273. this._blurKernelX = value;
  64274. this._preparePostProcesses();
  64275. },
  64276. enumerable: true,
  64277. configurable: true
  64278. });
  64279. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64280. get: function () {
  64281. return this._blurKernelY;
  64282. },
  64283. set: function (value) {
  64284. if (this._blurKernelY === value) {
  64285. return;
  64286. }
  64287. this._blurKernelY = value;
  64288. this._preparePostProcesses();
  64289. },
  64290. enumerable: true,
  64291. configurable: true
  64292. });
  64293. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64294. var engine = this.getScene().getEngine();
  64295. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64296. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64297. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64298. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64299. };
  64300. MirrorTexture.prototype._onRatioRescale = function () {
  64301. if (this._sizeRatio) {
  64302. this.resize(this._initialSizeParameter);
  64303. if (!this._adaptiveBlurKernel) {
  64304. this._preparePostProcesses();
  64305. }
  64306. }
  64307. if (this._adaptiveBlurKernel) {
  64308. this._autoComputeBlurKernel();
  64309. }
  64310. };
  64311. MirrorTexture.prototype._updateGammaSpace = function () {
  64312. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64313. };
  64314. MirrorTexture.prototype._preparePostProcesses = function () {
  64315. this.clearPostProcesses(true);
  64316. if (this._blurKernelX && this._blurKernelY) {
  64317. var engine = this.getScene().getEngine();
  64318. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64319. 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);
  64320. this._blurX.autoClear = false;
  64321. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64322. this._blurX.inputTexture = this._texture;
  64323. }
  64324. else {
  64325. this._blurX.alwaysForcePOT = true;
  64326. }
  64327. 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);
  64328. this._blurY.autoClear = false;
  64329. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64330. this.addPostProcess(this._blurX);
  64331. this.addPostProcess(this._blurY);
  64332. }
  64333. else {
  64334. if (this._blurY) {
  64335. this.removePostProcess(this._blurY);
  64336. this._blurY.dispose();
  64337. this._blurY = null;
  64338. }
  64339. if (this._blurX) {
  64340. this.removePostProcess(this._blurX);
  64341. this._blurX.dispose();
  64342. this._blurX = null;
  64343. }
  64344. }
  64345. };
  64346. MirrorTexture.prototype.clone = function () {
  64347. var scene = this.getScene();
  64348. if (!scene) {
  64349. return this;
  64350. }
  64351. var textureSize = this.getSize();
  64352. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64353. // Base texture
  64354. newTexture.hasAlpha = this.hasAlpha;
  64355. newTexture.level = this.level;
  64356. // Mirror Texture
  64357. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64358. if (this.renderList) {
  64359. newTexture.renderList = this.renderList.slice(0);
  64360. }
  64361. return newTexture;
  64362. };
  64363. MirrorTexture.prototype.serialize = function () {
  64364. if (!this.name) {
  64365. return null;
  64366. }
  64367. var serializationObject = _super.prototype.serialize.call(this);
  64368. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64369. return serializationObject;
  64370. };
  64371. MirrorTexture.prototype.dispose = function () {
  64372. _super.prototype.dispose.call(this);
  64373. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64374. };
  64375. return MirrorTexture;
  64376. }(BABYLON.RenderTargetTexture));
  64377. BABYLON.MirrorTexture = MirrorTexture;
  64378. })(BABYLON || (BABYLON = {}));
  64379. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64380. var BABYLON;
  64381. (function (BABYLON) {
  64382. /**
  64383. * Creates a refraction texture used by refraction channel of the standard material.
  64384. * @param name the texture name
  64385. * @param size size of the underlying texture
  64386. * @param scene root scene
  64387. */
  64388. var RefractionTexture = /** @class */ (function (_super) {
  64389. __extends(RefractionTexture, _super);
  64390. function RefractionTexture(name, size, scene, generateMipMaps) {
  64391. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64392. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64393. _this.depth = 2.0;
  64394. _this.onBeforeRenderObservable.add(function () {
  64395. scene.clipPlane = _this.refractionPlane;
  64396. });
  64397. _this.onAfterRenderObservable.add(function () {
  64398. delete scene.clipPlane;
  64399. });
  64400. return _this;
  64401. }
  64402. RefractionTexture.prototype.clone = function () {
  64403. var scene = this.getScene();
  64404. if (!scene) {
  64405. return this;
  64406. }
  64407. var textureSize = this.getSize();
  64408. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64409. // Base texture
  64410. newTexture.hasAlpha = this.hasAlpha;
  64411. newTexture.level = this.level;
  64412. // Refraction Texture
  64413. newTexture.refractionPlane = this.refractionPlane.clone();
  64414. if (this.renderList) {
  64415. newTexture.renderList = this.renderList.slice(0);
  64416. }
  64417. newTexture.depth = this.depth;
  64418. return newTexture;
  64419. };
  64420. RefractionTexture.prototype.serialize = function () {
  64421. if (!this.name) {
  64422. return null;
  64423. }
  64424. var serializationObject = _super.prototype.serialize.call(this);
  64425. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64426. serializationObject.depth = this.depth;
  64427. return serializationObject;
  64428. };
  64429. return RefractionTexture;
  64430. }(BABYLON.RenderTargetTexture));
  64431. BABYLON.RefractionTexture = RefractionTexture;
  64432. })(BABYLON || (BABYLON = {}));
  64433. //# sourceMappingURL=babylon.refractionTexture.js.map
  64434. var BABYLON;
  64435. (function (BABYLON) {
  64436. /**
  64437. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64438. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64439. */
  64440. var DynamicTexture = /** @class */ (function (_super) {
  64441. __extends(DynamicTexture, _super);
  64442. /**
  64443. * Creates a {BABYLON.DynamicTexture}
  64444. * @param name defines the name of the texture
  64445. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64446. * @param scene defines the scene where you want the texture
  64447. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64448. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64449. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64450. */
  64451. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64452. if (scene === void 0) { scene = null; }
  64453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64454. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64455. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64456. _this.name = name;
  64457. _this._engine = _this.getScene().getEngine();
  64458. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64459. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64460. _this._generateMipMaps = generateMipMaps;
  64461. if (options.getContext) {
  64462. _this._canvas = options;
  64463. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64464. }
  64465. else {
  64466. _this._canvas = document.createElement("canvas");
  64467. if (options.width || options.width === 0) {
  64468. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64469. }
  64470. else {
  64471. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64472. }
  64473. }
  64474. var textureSize = _this.getSize();
  64475. _this._canvas.width = textureSize.width;
  64476. _this._canvas.height = textureSize.height;
  64477. _this._context = _this._canvas.getContext("2d");
  64478. return _this;
  64479. }
  64480. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64481. /**
  64482. * Gets the current state of canRescale
  64483. */
  64484. get: function () {
  64485. return true;
  64486. },
  64487. enumerable: true,
  64488. configurable: true
  64489. });
  64490. DynamicTexture.prototype._recreate = function (textureSize) {
  64491. this._canvas.width = textureSize.width;
  64492. this._canvas.height = textureSize.height;
  64493. this.releaseInternalTexture();
  64494. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64495. };
  64496. /**
  64497. * Scales the texture
  64498. * @param ratio the scale factor to apply to both width and height
  64499. */
  64500. DynamicTexture.prototype.scale = function (ratio) {
  64501. var textureSize = this.getSize();
  64502. textureSize.width *= ratio;
  64503. textureSize.height *= ratio;
  64504. this._recreate(textureSize);
  64505. };
  64506. /**
  64507. * Resizes the texture
  64508. * @param width the new width
  64509. * @param height the new height
  64510. */
  64511. DynamicTexture.prototype.scaleTo = function (width, height) {
  64512. var textureSize = this.getSize();
  64513. textureSize.width = width;
  64514. textureSize.height = height;
  64515. this._recreate(textureSize);
  64516. };
  64517. /**
  64518. * Gets the context of the canvas used by the texture
  64519. * @returns the canvas context of the dynamic texture
  64520. */
  64521. DynamicTexture.prototype.getContext = function () {
  64522. return this._context;
  64523. };
  64524. /**
  64525. * Clears the texture
  64526. */
  64527. DynamicTexture.prototype.clear = function () {
  64528. var size = this.getSize();
  64529. this._context.fillRect(0, 0, size.width, size.height);
  64530. };
  64531. /**
  64532. * Updates the texture
  64533. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64534. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64535. */
  64536. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64537. if (premulAlpha === void 0) { premulAlpha = false; }
  64538. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64539. };
  64540. /**
  64541. * Draws text onto the texture
  64542. * @param text defines the text to be drawn
  64543. * @param x defines the placement of the text from the left
  64544. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64545. * @param font defines the font to be used with font-style, font-size, font-name
  64546. * @param color defines the color used for the text
  64547. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64548. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64549. * @param update defines whether texture is immediately update (default is true)
  64550. */
  64551. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64552. if (update === void 0) { update = true; }
  64553. var size = this.getSize();
  64554. if (clearColor) {
  64555. this._context.fillStyle = clearColor;
  64556. this._context.fillRect(0, 0, size.width, size.height);
  64557. }
  64558. this._context.font = font;
  64559. if (x === null || x === undefined) {
  64560. var textSize = this._context.measureText(text);
  64561. x = (size.width - textSize.width) / 2;
  64562. }
  64563. if (y === null || y === undefined) {
  64564. var fontSize = parseInt((font.replace(/\D/g, '')));
  64565. y = (size.height / 2) + (fontSize / 3.65);
  64566. }
  64567. this._context.fillStyle = color;
  64568. this._context.fillText(text, x, y);
  64569. if (update) {
  64570. this.update(invertY);
  64571. }
  64572. };
  64573. /**
  64574. * Clones the texture
  64575. * @returns the clone of the texture.
  64576. */
  64577. DynamicTexture.prototype.clone = function () {
  64578. var scene = this.getScene();
  64579. if (!scene) {
  64580. return this;
  64581. }
  64582. var textureSize = this.getSize();
  64583. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64584. // Base texture
  64585. newTexture.hasAlpha = this.hasAlpha;
  64586. newTexture.level = this.level;
  64587. // Dynamic Texture
  64588. newTexture.wrapU = this.wrapU;
  64589. newTexture.wrapV = this.wrapV;
  64590. return newTexture;
  64591. };
  64592. /** @hidden */
  64593. DynamicTexture.prototype._rebuild = function () {
  64594. this.update();
  64595. };
  64596. return DynamicTexture;
  64597. }(BABYLON.Texture));
  64598. BABYLON.DynamicTexture = DynamicTexture;
  64599. })(BABYLON || (BABYLON = {}));
  64600. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64601. var BABYLON;
  64602. (function (BABYLON) {
  64603. var VideoTexture = /** @class */ (function (_super) {
  64604. __extends(VideoTexture, _super);
  64605. /**
  64606. * Creates a video texture.
  64607. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64608. * @param {string | null} name optional name, will detect from video source, if not defined
  64609. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64610. * @param {BABYLON.Scene} scene is obviously the current scene.
  64611. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64612. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64613. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64614. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64615. */
  64616. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64617. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64618. if (invertY === void 0) { invertY = false; }
  64619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64620. if (settings === void 0) { settings = {
  64621. autoPlay: true,
  64622. loop: true,
  64623. autoUpdateTexture: true,
  64624. }; }
  64625. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64626. _this._onUserActionRequestedObservable = null;
  64627. _this._stillImageCaptured = false;
  64628. _this._createInternalTexture = function () {
  64629. if (_this._texture != null) {
  64630. return;
  64631. }
  64632. if (!_this._engine.needPOTTextures ||
  64633. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64634. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64635. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64636. }
  64637. else {
  64638. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64639. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64640. _this._generateMipMaps = false;
  64641. }
  64642. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64643. if (!_this.video.autoplay) {
  64644. var oldHandler_1 = _this.video.onplaying;
  64645. var error_1 = false;
  64646. _this.video.onplaying = function () {
  64647. _this.video.onplaying = oldHandler_1;
  64648. _this._texture.isReady = true;
  64649. _this._updateInternalTexture();
  64650. if (!error_1) {
  64651. _this.video.pause();
  64652. }
  64653. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64654. _this.onLoadObservable.notifyObservers(_this);
  64655. }
  64656. };
  64657. var playing = _this.video.play();
  64658. if (playing) {
  64659. playing.then(function () {
  64660. // Everything is good.
  64661. })
  64662. .catch(function () {
  64663. error_1 = true;
  64664. // On Chrome for instance, new policies might prevent playing without user interaction.
  64665. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64666. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64667. }
  64668. });
  64669. }
  64670. else {
  64671. _this.video.onplaying = oldHandler_1;
  64672. _this._texture.isReady = true;
  64673. _this._updateInternalTexture();
  64674. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64675. _this.onLoadObservable.notifyObservers(_this);
  64676. }
  64677. }
  64678. }
  64679. else {
  64680. _this._texture.isReady = true;
  64681. _this._updateInternalTexture();
  64682. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64683. _this.onLoadObservable.notifyObservers(_this);
  64684. }
  64685. }
  64686. };
  64687. _this.reset = function () {
  64688. if (_this._texture == null) {
  64689. return;
  64690. }
  64691. _this._texture.dispose();
  64692. _this._texture = null;
  64693. };
  64694. _this._updateInternalTexture = function (e) {
  64695. if (_this._texture == null || !_this._texture.isReady) {
  64696. return;
  64697. }
  64698. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64699. return;
  64700. }
  64701. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64702. };
  64703. _this._engine = _this.getScene().getEngine();
  64704. _this._generateMipMaps = generateMipMaps;
  64705. _this._samplingMode = samplingMode;
  64706. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64707. _this.name = name || _this._getName(src);
  64708. _this.video = _this._getVideo(src);
  64709. if (settings.poster) {
  64710. _this.video.poster = settings.poster;
  64711. }
  64712. if (settings.autoPlay !== undefined) {
  64713. _this.video.autoplay = settings.autoPlay;
  64714. }
  64715. if (settings.loop !== undefined) {
  64716. _this.video.loop = settings.loop;
  64717. }
  64718. _this.video.setAttribute("playsinline", "");
  64719. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64720. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64721. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64722. _this.video.addEventListener("emptied", _this.reset);
  64723. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64724. _this._createInternalTexture();
  64725. }
  64726. return _this;
  64727. }
  64728. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64729. get: function () {
  64730. if (!this._onUserActionRequestedObservable) {
  64731. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64732. }
  64733. return this._onUserActionRequestedObservable;
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. VideoTexture.prototype._getName = function (src) {
  64739. if (src instanceof HTMLVideoElement) {
  64740. return src.currentSrc;
  64741. }
  64742. if (typeof src === "object") {
  64743. return src.toString();
  64744. }
  64745. return src;
  64746. };
  64747. ;
  64748. VideoTexture.prototype._getVideo = function (src) {
  64749. if (src instanceof HTMLVideoElement) {
  64750. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64751. return src;
  64752. }
  64753. var video = document.createElement("video");
  64754. if (typeof src === "string") {
  64755. BABYLON.Tools.SetCorsBehavior(src, video);
  64756. video.src = src;
  64757. }
  64758. else {
  64759. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64760. src.forEach(function (url) {
  64761. var source = document.createElement("source");
  64762. source.src = url;
  64763. video.appendChild(source);
  64764. });
  64765. }
  64766. return video;
  64767. };
  64768. ;
  64769. /**
  64770. * Internal method to initiate `update`.
  64771. */
  64772. VideoTexture.prototype._rebuild = function () {
  64773. this.update();
  64774. };
  64775. /**
  64776. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64777. */
  64778. VideoTexture.prototype.update = function () {
  64779. if (!this.autoUpdateTexture) {
  64780. // Expecting user to call `updateTexture` manually
  64781. return;
  64782. }
  64783. this.updateTexture(true);
  64784. };
  64785. /**
  64786. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64787. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64788. */
  64789. VideoTexture.prototype.updateTexture = function (isVisible) {
  64790. if (!isVisible) {
  64791. return;
  64792. }
  64793. if (this.video.paused && this._stillImageCaptured) {
  64794. return;
  64795. }
  64796. this._stillImageCaptured = true;
  64797. this._updateInternalTexture();
  64798. };
  64799. /**
  64800. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64801. * @param url New url.
  64802. */
  64803. VideoTexture.prototype.updateURL = function (url) {
  64804. this.video.src = url;
  64805. };
  64806. VideoTexture.prototype.dispose = function () {
  64807. _super.prototype.dispose.call(this);
  64808. if (this._onUserActionRequestedObservable) {
  64809. this._onUserActionRequestedObservable.clear();
  64810. this._onUserActionRequestedObservable = null;
  64811. }
  64812. this.video.removeEventListener("canplay", this._createInternalTexture);
  64813. this.video.removeEventListener("paused", this._updateInternalTexture);
  64814. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64815. this.video.removeEventListener("emptied", this.reset);
  64816. this.video.pause();
  64817. };
  64818. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64819. var video = document.createElement("video");
  64820. video.setAttribute('autoplay', '');
  64821. video.setAttribute('muted', '');
  64822. video.setAttribute('playsinline', '');
  64823. var constraintsDeviceId;
  64824. if (constraints && constraints.deviceId) {
  64825. constraintsDeviceId = {
  64826. exact: constraints.deviceId,
  64827. };
  64828. }
  64829. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64830. if (navigator.mediaDevices) {
  64831. navigator.mediaDevices.getUserMedia({ video: constraints })
  64832. .then(function (stream) {
  64833. if (video.mozSrcObject !== undefined) {
  64834. // hack for Firefox < 19
  64835. video.mozSrcObject = stream;
  64836. }
  64837. else {
  64838. video.srcObject = stream;
  64839. }
  64840. var onPlaying = function () {
  64841. if (onReady) {
  64842. onReady(new VideoTexture("video", video, scene, true, true));
  64843. }
  64844. video.removeEventListener("playing", onPlaying);
  64845. };
  64846. video.addEventListener("playing", onPlaying);
  64847. video.play();
  64848. })
  64849. .catch(function (err) {
  64850. BABYLON.Tools.Error(err.name);
  64851. });
  64852. }
  64853. else {
  64854. navigator.getUserMedia =
  64855. navigator.getUserMedia ||
  64856. navigator.webkitGetUserMedia ||
  64857. navigator.mozGetUserMedia ||
  64858. navigator.msGetUserMedia;
  64859. if (navigator.getUserMedia) {
  64860. navigator.getUserMedia({
  64861. video: {
  64862. deviceId: constraintsDeviceId,
  64863. width: {
  64864. min: (constraints && constraints.minWidth) || 256,
  64865. max: (constraints && constraints.maxWidth) || 640,
  64866. },
  64867. height: {
  64868. min: (constraints && constraints.minHeight) || 256,
  64869. max: (constraints && constraints.maxHeight) || 480,
  64870. },
  64871. },
  64872. }, function (stream) {
  64873. if (video.mozSrcObject !== undefined) {
  64874. // hack for Firefox < 19
  64875. video.mozSrcObject = stream;
  64876. }
  64877. else {
  64878. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64879. }
  64880. video.play();
  64881. if (onReady) {
  64882. onReady(new VideoTexture("video", video, scene, true, true));
  64883. }
  64884. }, function (e) {
  64885. BABYLON.Tools.Error(e.name);
  64886. });
  64887. }
  64888. }
  64889. };
  64890. return VideoTexture;
  64891. }(BABYLON.Texture));
  64892. BABYLON.VideoTexture = VideoTexture;
  64893. })(BABYLON || (BABYLON = {}));
  64894. //# sourceMappingURL=babylon.videoTexture.js.map
  64895. var BABYLON;
  64896. (function (BABYLON) {
  64897. var RawTexture = /** @class */ (function (_super) {
  64898. __extends(RawTexture, _super);
  64899. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64901. if (invertY === void 0) { invertY = false; }
  64902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64904. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64905. _this.format = format;
  64906. _this._engine = scene.getEngine();
  64907. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64908. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64909. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64910. return _this;
  64911. }
  64912. RawTexture.prototype.update = function (data) {
  64913. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64914. };
  64915. // Statics
  64916. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64918. if (invertY === void 0) { invertY = false; }
  64919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64920. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64921. };
  64922. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64924. if (invertY === void 0) { invertY = false; }
  64925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64927. };
  64928. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64929. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64930. if (invertY === void 0) { invertY = false; }
  64931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64932. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64933. };
  64934. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64935. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64936. if (invertY === void 0) { invertY = false; }
  64937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64938. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64939. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64940. };
  64941. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64942. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64943. if (invertY === void 0) { invertY = false; }
  64944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64945. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64946. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64947. };
  64948. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64949. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64950. if (invertY === void 0) { invertY = false; }
  64951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64952. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64953. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64954. };
  64955. return RawTexture;
  64956. }(BABYLON.Texture));
  64957. BABYLON.RawTexture = RawTexture;
  64958. })(BABYLON || (BABYLON = {}));
  64959. //# sourceMappingURL=babylon.rawTexture.js.map
  64960. var BABYLON;
  64961. (function (BABYLON) {
  64962. /**
  64963. * Class used to store 3D textures containing user data
  64964. */
  64965. var RawTexture3D = /** @class */ (function (_super) {
  64966. __extends(RawTexture3D, _super);
  64967. /**
  64968. * Create a new RawTexture3D
  64969. * @param data defines the data of the texture
  64970. * @param width defines the width of the texture
  64971. * @param height defines the height of the texture
  64972. * @param depth defines the depth of the texture
  64973. * @param format defines the texture format to use
  64974. * @param scene defines the hosting scene
  64975. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64976. * @param invertY defines if texture must be stored with Y axis inverted
  64977. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64978. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64979. */
  64980. function RawTexture3D(data, width, height, depth,
  64981. /** Gets or sets the texture format to use */
  64982. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64984. if (invertY === void 0) { invertY = false; }
  64985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64987. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64988. _this.format = format;
  64989. _this._engine = scene.getEngine();
  64990. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64991. _this.is3D = true;
  64992. return _this;
  64993. }
  64994. /**
  64995. * Update the texture with new data
  64996. * @param data defines the data to store in the texture
  64997. */
  64998. RawTexture3D.prototype.update = function (data) {
  64999. if (!this._texture) {
  65000. return;
  65001. }
  65002. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65003. };
  65004. return RawTexture3D;
  65005. }(BABYLON.Texture));
  65006. BABYLON.RawTexture3D = RawTexture3D;
  65007. })(BABYLON || (BABYLON = {}));
  65008. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65009. var BABYLON;
  65010. (function (BABYLON) {
  65011. /**
  65012. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65013. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65014. */
  65015. var PostProcessManager = /** @class */ (function () {
  65016. /**
  65017. * Creates a new instance PostProcess
  65018. * @param scene The scene that the post process is associated with.
  65019. */
  65020. function PostProcessManager(scene) {
  65021. this._vertexBuffers = {};
  65022. this._scene = scene;
  65023. }
  65024. PostProcessManager.prototype._prepareBuffers = function () {
  65025. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65026. return;
  65027. }
  65028. // VBO
  65029. var vertices = [];
  65030. vertices.push(1, 1);
  65031. vertices.push(-1, 1);
  65032. vertices.push(-1, -1);
  65033. vertices.push(1, -1);
  65034. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65035. this._buildIndexBuffer();
  65036. };
  65037. PostProcessManager.prototype._buildIndexBuffer = function () {
  65038. // Indices
  65039. var indices = [];
  65040. indices.push(0);
  65041. indices.push(1);
  65042. indices.push(2);
  65043. indices.push(0);
  65044. indices.push(2);
  65045. indices.push(3);
  65046. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65047. };
  65048. /**
  65049. * Rebuilds the vertex buffers of the manager.
  65050. */
  65051. PostProcessManager.prototype._rebuild = function () {
  65052. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65053. if (!vb) {
  65054. return;
  65055. }
  65056. vb._rebuild();
  65057. this._buildIndexBuffer();
  65058. };
  65059. // Methods
  65060. /**
  65061. * Prepares a frame to be run through a post process.
  65062. * @param sourceTexture The input texture to the post procesess. (default: null)
  65063. * @param postProcesses An array of post processes to be run. (default: null)
  65064. * @returns True if the post processes were able to be run.
  65065. */
  65066. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65067. if (sourceTexture === void 0) { sourceTexture = null; }
  65068. if (postProcesses === void 0) { postProcesses = null; }
  65069. var camera = this._scene.activeCamera;
  65070. if (!camera) {
  65071. return false;
  65072. }
  65073. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65074. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65075. return false;
  65076. }
  65077. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65078. return true;
  65079. };
  65080. /**
  65081. * Manually render a set of post processes to a texture.
  65082. * @param postProcesses An array of post processes to be run.
  65083. * @param targetTexture The target texture to render to.
  65084. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65085. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65086. * @param lodLevel defines which lod of the texture to render to
  65087. */
  65088. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65089. if (targetTexture === void 0) { targetTexture = null; }
  65090. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65091. if (faceIndex === void 0) { faceIndex = 0; }
  65092. if (lodLevel === void 0) { lodLevel = 0; }
  65093. var engine = this._scene.getEngine();
  65094. for (var index = 0; index < postProcesses.length; index++) {
  65095. if (index < postProcesses.length - 1) {
  65096. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65097. }
  65098. else {
  65099. if (targetTexture) {
  65100. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65101. }
  65102. else {
  65103. engine.restoreDefaultFramebuffer();
  65104. }
  65105. }
  65106. var pp = postProcesses[index];
  65107. var effect = pp.apply();
  65108. if (effect) {
  65109. pp.onBeforeRenderObservable.notifyObservers(effect);
  65110. // VBOs
  65111. this._prepareBuffers();
  65112. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65113. // Draw order
  65114. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65115. pp.onAfterRenderObservable.notifyObservers(effect);
  65116. }
  65117. }
  65118. // Restore depth buffer
  65119. engine.setDepthBuffer(true);
  65120. engine.setDepthWrite(true);
  65121. };
  65122. /**
  65123. * Finalize the result of the output of the postprocesses.
  65124. * @param doNotPresent If true the result will not be displayed to the screen.
  65125. * @param targetTexture The target texture to render to.
  65126. * @param faceIndex The index of the face to bind the target texture to.
  65127. * @param postProcesses The array of post processes to render.
  65128. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65129. */
  65130. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65131. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65132. var camera = this._scene.activeCamera;
  65133. if (!camera) {
  65134. return;
  65135. }
  65136. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65137. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65138. return;
  65139. }
  65140. var engine = this._scene.getEngine();
  65141. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65142. var pp = postProcesses[index];
  65143. if (index < len - 1) {
  65144. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65145. }
  65146. else {
  65147. if (targetTexture) {
  65148. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65149. pp._outputTexture = targetTexture;
  65150. }
  65151. else {
  65152. engine.restoreDefaultFramebuffer();
  65153. pp._outputTexture = null;
  65154. }
  65155. }
  65156. if (doNotPresent) {
  65157. break;
  65158. }
  65159. var effect = pp.apply();
  65160. if (effect) {
  65161. pp.onBeforeRenderObservable.notifyObservers(effect);
  65162. // VBOs
  65163. this._prepareBuffers();
  65164. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65165. // Draw order
  65166. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65167. pp.onAfterRenderObservable.notifyObservers(effect);
  65168. }
  65169. }
  65170. // Restore states
  65171. engine.setDepthBuffer(true);
  65172. engine.setDepthWrite(true);
  65173. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65174. };
  65175. /**
  65176. * Disposes of the post process manager.
  65177. */
  65178. PostProcessManager.prototype.dispose = function () {
  65179. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65180. if (buffer) {
  65181. buffer.dispose();
  65182. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65183. }
  65184. if (this._indexBuffer) {
  65185. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65186. this._indexBuffer = null;
  65187. }
  65188. };
  65189. return PostProcessManager;
  65190. }());
  65191. BABYLON.PostProcessManager = PostProcessManager;
  65192. })(BABYLON || (BABYLON = {}));
  65193. //# sourceMappingURL=babylon.postProcessManager.js.map
  65194. var BABYLON;
  65195. (function (BABYLON) {
  65196. /**
  65197. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65198. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65199. */
  65200. var PostProcess = /** @class */ (function () {
  65201. /**
  65202. * Creates a new instance PostProcess
  65203. * @param name The name of the PostProcess.
  65204. * @param fragmentUrl The url of the fragment shader to be used.
  65205. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65206. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65207. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65208. * @param camera The camera to apply the render pass to.
  65209. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65210. * @param engine The engine which the post process will be applied. (default: current engine)
  65211. * @param reusable If the post process can be reused on the same frame. (default: false)
  65212. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65213. * @param textureType Type of textures used when performing the post process. (default: 0)
  65214. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65215. * @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
  65216. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65217. */
  65218. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65219. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65220. if (defines === void 0) { defines = null; }
  65221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65222. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65223. if (blockCompilation === void 0) { blockCompilation = false; }
  65224. this.name = name;
  65225. /**
  65226. * Width of the texture to apply the post process on
  65227. */
  65228. this.width = -1;
  65229. /**
  65230. * Height of the texture to apply the post process on
  65231. */
  65232. this.height = -1;
  65233. /**
  65234. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65235. */
  65236. this._outputTexture = null;
  65237. /**
  65238. * If the buffer needs to be cleared before applying the post process. (default: true)
  65239. * Should be set to false if shader will overwrite all previous pixels.
  65240. */
  65241. this.autoClear = true;
  65242. /**
  65243. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65244. */
  65245. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65246. /**
  65247. * Animations to be used for the post processing
  65248. */
  65249. this.animations = new Array();
  65250. /**
  65251. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65252. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65253. */
  65254. this.enablePixelPerfectMode = false;
  65255. /**
  65256. * Force the postprocess to be applied without taking in account viewport
  65257. */
  65258. this.forceFullscreenViewport = true;
  65259. /**
  65260. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65261. *
  65262. * | Value | Type | Description |
  65263. * | ----- | ----------------------------------- | ----------- |
  65264. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65265. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65266. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65267. *
  65268. */
  65269. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65270. /**
  65271. * Force textures to be a power of two (default: false)
  65272. */
  65273. this.alwaysForcePOT = false;
  65274. /**
  65275. * Number of sample textures (default: 1)
  65276. */
  65277. this.samples = 1;
  65278. /**
  65279. * Modify the scale of the post process to be the same as the viewport (default: false)
  65280. */
  65281. this.adaptScaleToCurrentViewport = false;
  65282. this._reusable = false;
  65283. /**
  65284. * Smart array of input and output textures for the post process.
  65285. */
  65286. this._textures = new BABYLON.SmartArray(2);
  65287. /**
  65288. * The index in _textures that corresponds to the output texture.
  65289. */
  65290. this._currentRenderTextureInd = 0;
  65291. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65292. this._texelSize = BABYLON.Vector2.Zero();
  65293. // Events
  65294. /**
  65295. * An event triggered when the postprocess is activated.
  65296. */
  65297. this.onActivateObservable = new BABYLON.Observable();
  65298. /**
  65299. * An event triggered when the postprocess changes its size.
  65300. */
  65301. this.onSizeChangedObservable = new BABYLON.Observable();
  65302. /**
  65303. * An event triggered when the postprocess applies its effect.
  65304. */
  65305. this.onApplyObservable = new BABYLON.Observable();
  65306. /**
  65307. * An event triggered before rendering the postprocess
  65308. */
  65309. this.onBeforeRenderObservable = new BABYLON.Observable();
  65310. /**
  65311. * An event triggered after rendering the postprocess
  65312. */
  65313. this.onAfterRenderObservable = new BABYLON.Observable();
  65314. if (camera != null) {
  65315. this._camera = camera;
  65316. this._scene = camera.getScene();
  65317. camera.attachPostProcess(this);
  65318. this._engine = this._scene.getEngine();
  65319. this._scene.postProcesses.push(this);
  65320. }
  65321. else if (engine) {
  65322. this._engine = engine;
  65323. this._engine.postProcesses.push(this);
  65324. }
  65325. this._options = options;
  65326. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65327. this._reusable = reusable || false;
  65328. this._textureType = textureType;
  65329. this._samplers = samplers || [];
  65330. this._samplers.push("textureSampler");
  65331. this._fragmentUrl = fragmentUrl;
  65332. this._vertexUrl = vertexUrl;
  65333. this._parameters = parameters || [];
  65334. this._parameters.push("scale");
  65335. this._indexParameters = indexParameters;
  65336. if (!blockCompilation) {
  65337. this.updateEffect(defines);
  65338. }
  65339. }
  65340. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65341. /**
  65342. * A function that is added to the onActivateObservable
  65343. */
  65344. set: function (callback) {
  65345. if (this._onActivateObserver) {
  65346. this.onActivateObservable.remove(this._onActivateObserver);
  65347. }
  65348. if (callback) {
  65349. this._onActivateObserver = this.onActivateObservable.add(callback);
  65350. }
  65351. },
  65352. enumerable: true,
  65353. configurable: true
  65354. });
  65355. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65356. /**
  65357. * A function that is added to the onSizeChangedObservable
  65358. */
  65359. set: function (callback) {
  65360. if (this._onSizeChangedObserver) {
  65361. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65362. }
  65363. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65364. },
  65365. enumerable: true,
  65366. configurable: true
  65367. });
  65368. Object.defineProperty(PostProcess.prototype, "onApply", {
  65369. /**
  65370. * A function that is added to the onApplyObservable
  65371. */
  65372. set: function (callback) {
  65373. if (this._onApplyObserver) {
  65374. this.onApplyObservable.remove(this._onApplyObserver);
  65375. }
  65376. this._onApplyObserver = this.onApplyObservable.add(callback);
  65377. },
  65378. enumerable: true,
  65379. configurable: true
  65380. });
  65381. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65382. /**
  65383. * A function that is added to the onBeforeRenderObservable
  65384. */
  65385. set: function (callback) {
  65386. if (this._onBeforeRenderObserver) {
  65387. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65388. }
  65389. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65390. },
  65391. enumerable: true,
  65392. configurable: true
  65393. });
  65394. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65395. /**
  65396. * A function that is added to the onAfterRenderObservable
  65397. */
  65398. set: function (callback) {
  65399. if (this._onAfterRenderObserver) {
  65400. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65401. }
  65402. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65403. },
  65404. enumerable: true,
  65405. configurable: true
  65406. });
  65407. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65408. /**
  65409. * 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
  65410. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65411. */
  65412. get: function () {
  65413. return this._textures.data[this._currentRenderTextureInd];
  65414. },
  65415. set: function (value) {
  65416. this._forcedOutputTexture = value;
  65417. },
  65418. enumerable: true,
  65419. configurable: true
  65420. });
  65421. /**
  65422. * Gets the camera which post process is applied to.
  65423. * @returns The camera the post process is applied to.
  65424. */
  65425. PostProcess.prototype.getCamera = function () {
  65426. return this._camera;
  65427. };
  65428. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65429. /**
  65430. * Gets the texel size of the postprocess.
  65431. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65432. */
  65433. get: function () {
  65434. if (this._shareOutputWithPostProcess) {
  65435. return this._shareOutputWithPostProcess.texelSize;
  65436. }
  65437. if (this._forcedOutputTexture) {
  65438. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65439. }
  65440. return this._texelSize;
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. /**
  65446. * Gets the engine which this post process belongs to.
  65447. * @returns The engine the post process was enabled with.
  65448. */
  65449. PostProcess.prototype.getEngine = function () {
  65450. return this._engine;
  65451. };
  65452. /**
  65453. * The effect that is created when initializing the post process.
  65454. * @returns The created effect corrisponding the the postprocess.
  65455. */
  65456. PostProcess.prototype.getEffect = function () {
  65457. return this._effect;
  65458. };
  65459. /**
  65460. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65461. * @param postProcess The post process to share the output with.
  65462. * @returns This post process.
  65463. */
  65464. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65465. this._disposeTextures();
  65466. this._shareOutputWithPostProcess = postProcess;
  65467. return this;
  65468. };
  65469. /**
  65470. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65471. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65472. */
  65473. PostProcess.prototype.useOwnOutput = function () {
  65474. if (this._textures.length == 0) {
  65475. this._textures = new BABYLON.SmartArray(2);
  65476. }
  65477. this._shareOutputWithPostProcess = null;
  65478. };
  65479. /**
  65480. * Updates the effect with the current post process compile time values and recompiles the shader.
  65481. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65482. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65483. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65484. * @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
  65485. * @param onCompiled Called when the shader has been compiled.
  65486. * @param onError Called if there is an error when compiling a shader.
  65487. */
  65488. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65489. if (defines === void 0) { defines = null; }
  65490. if (uniforms === void 0) { uniforms = null; }
  65491. if (samplers === void 0) { samplers = null; }
  65492. 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);
  65493. };
  65494. /**
  65495. * The post process is reusable if it can be used multiple times within one frame.
  65496. * @returns If the post process is reusable
  65497. */
  65498. PostProcess.prototype.isReusable = function () {
  65499. return this._reusable;
  65500. };
  65501. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65502. PostProcess.prototype.markTextureDirty = function () {
  65503. this.width = -1;
  65504. };
  65505. /**
  65506. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65507. * 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.
  65508. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65509. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65510. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65511. * @returns The target texture that was bound to be written to.
  65512. */
  65513. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65514. var _this = this;
  65515. if (sourceTexture === void 0) { sourceTexture = null; }
  65516. camera = camera || this._camera;
  65517. var scene = camera.getScene();
  65518. var engine = scene.getEngine();
  65519. var maxSize = engine.getCaps().maxTextureSize;
  65520. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65521. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65522. // 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
  65523. var webVRCamera = camera.parent;
  65524. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65525. requiredWidth /= 2;
  65526. }
  65527. var desiredWidth = (this._options.width || requiredWidth);
  65528. var desiredHeight = this._options.height || requiredHeight;
  65529. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65530. if (this.adaptScaleToCurrentViewport) {
  65531. var currentViewport = engine.currentViewport;
  65532. if (currentViewport) {
  65533. desiredWidth *= currentViewport.width;
  65534. desiredHeight *= currentViewport.height;
  65535. }
  65536. }
  65537. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65538. if (!this._options.width) {
  65539. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65540. }
  65541. if (!this._options.height) {
  65542. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65543. }
  65544. }
  65545. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65546. if (this._textures.length > 0) {
  65547. for (var i = 0; i < this._textures.length; i++) {
  65548. this._engine._releaseTexture(this._textures.data[i]);
  65549. }
  65550. this._textures.reset();
  65551. }
  65552. this.width = desiredWidth;
  65553. this.height = desiredHeight;
  65554. var textureSize = { width: this.width, height: this.height };
  65555. var textureOptions = {
  65556. generateMipMaps: false,
  65557. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65558. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65559. samplingMode: this.renderTargetSamplingMode,
  65560. type: this._textureType
  65561. };
  65562. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65563. if (this._reusable) {
  65564. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65565. }
  65566. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65567. this.onSizeChangedObservable.notifyObservers(this);
  65568. }
  65569. this._textures.forEach(function (texture) {
  65570. if (texture.samples !== _this.samples) {
  65571. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65572. }
  65573. });
  65574. }
  65575. var target;
  65576. if (this._shareOutputWithPostProcess) {
  65577. target = this._shareOutputWithPostProcess.inputTexture;
  65578. }
  65579. else if (this._forcedOutputTexture) {
  65580. target = this._forcedOutputTexture;
  65581. this.width = this._forcedOutputTexture.width;
  65582. this.height = this._forcedOutputTexture.height;
  65583. }
  65584. else {
  65585. target = this.inputTexture;
  65586. }
  65587. // Bind the input of this post process to be used as the output of the previous post process.
  65588. if (this.enablePixelPerfectMode) {
  65589. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65590. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65591. }
  65592. else {
  65593. this._scaleRatio.copyFromFloats(1, 1);
  65594. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65595. }
  65596. this.onActivateObservable.notifyObservers(camera);
  65597. // Clear
  65598. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65599. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65600. }
  65601. if (this._reusable) {
  65602. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65603. }
  65604. return target;
  65605. };
  65606. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65607. /**
  65608. * If the post process is supported.
  65609. */
  65610. get: function () {
  65611. return this._effect.isSupported;
  65612. },
  65613. enumerable: true,
  65614. configurable: true
  65615. });
  65616. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65617. /**
  65618. * The aspect ratio of the output texture.
  65619. */
  65620. get: function () {
  65621. if (this._shareOutputWithPostProcess) {
  65622. return this._shareOutputWithPostProcess.aspectRatio;
  65623. }
  65624. if (this._forcedOutputTexture) {
  65625. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65626. }
  65627. return this.width / this.height;
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. /**
  65633. * Get a value indicating if the post-process is ready to be used
  65634. * @returns true if the post-process is ready (shader is compiled)
  65635. */
  65636. PostProcess.prototype.isReady = function () {
  65637. return this._effect && this._effect.isReady();
  65638. };
  65639. /**
  65640. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65641. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65642. */
  65643. PostProcess.prototype.apply = function () {
  65644. // Check
  65645. if (!this._effect || !this._effect.isReady())
  65646. return null;
  65647. // States
  65648. this._engine.enableEffect(this._effect);
  65649. this._engine.setState(false);
  65650. this._engine.setDepthBuffer(false);
  65651. this._engine.setDepthWrite(false);
  65652. // Alpha
  65653. this._engine.setAlphaMode(this.alphaMode);
  65654. if (this.alphaConstants) {
  65655. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65656. }
  65657. // Bind the output texture of the preivous post process as the input to this post process.
  65658. var source;
  65659. if (this._shareOutputWithPostProcess) {
  65660. source = this._shareOutputWithPostProcess.inputTexture;
  65661. }
  65662. else if (this._forcedOutputTexture) {
  65663. source = this._forcedOutputTexture;
  65664. }
  65665. else {
  65666. source = this.inputTexture;
  65667. }
  65668. this._effect._bindTexture("textureSampler", source);
  65669. // Parameters
  65670. this._effect.setVector2("scale", this._scaleRatio);
  65671. this.onApplyObservable.notifyObservers(this._effect);
  65672. return this._effect;
  65673. };
  65674. PostProcess.prototype._disposeTextures = function () {
  65675. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65676. return;
  65677. }
  65678. if (this._textures.length > 0) {
  65679. for (var i = 0; i < this._textures.length; i++) {
  65680. this._engine._releaseTexture(this._textures.data[i]);
  65681. }
  65682. }
  65683. this._textures.dispose();
  65684. };
  65685. /**
  65686. * Disposes the post process.
  65687. * @param camera The camera to dispose the post process on.
  65688. */
  65689. PostProcess.prototype.dispose = function (camera) {
  65690. camera = camera || this._camera;
  65691. this._disposeTextures();
  65692. if (this._scene) {
  65693. var index_1 = this._scene.postProcesses.indexOf(this);
  65694. if (index_1 !== -1) {
  65695. this._scene.postProcesses.splice(index_1, 1);
  65696. }
  65697. }
  65698. else {
  65699. var index_2 = this._engine.postProcesses.indexOf(this);
  65700. if (index_2 !== -1) {
  65701. this._engine.postProcesses.splice(index_2, 1);
  65702. }
  65703. }
  65704. if (!camera) {
  65705. return;
  65706. }
  65707. camera.detachPostProcess(this);
  65708. var index = camera._postProcesses.indexOf(this);
  65709. if (index === 0 && camera._postProcesses.length > 0) {
  65710. var firstPostProcess = this._camera._getFirstPostProcess();
  65711. if (firstPostProcess) {
  65712. firstPostProcess.markTextureDirty();
  65713. }
  65714. }
  65715. this.onActivateObservable.clear();
  65716. this.onAfterRenderObservable.clear();
  65717. this.onApplyObservable.clear();
  65718. this.onBeforeRenderObservable.clear();
  65719. this.onSizeChangedObservable.clear();
  65720. };
  65721. return PostProcess;
  65722. }());
  65723. BABYLON.PostProcess = PostProcess;
  65724. })(BABYLON || (BABYLON = {}));
  65725. //# sourceMappingURL=babylon.postProcess.js.map
  65726. var BABYLON;
  65727. (function (BABYLON) {
  65728. var PassPostProcess = /** @class */ (function (_super) {
  65729. __extends(PassPostProcess, _super);
  65730. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65731. if (camera === void 0) { camera = null; }
  65732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65733. if (blockCompilation === void 0) { blockCompilation = false; }
  65734. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65735. }
  65736. return PassPostProcess;
  65737. }(BABYLON.PostProcess));
  65738. BABYLON.PassPostProcess = PassPostProcess;
  65739. })(BABYLON || (BABYLON = {}));
  65740. //# sourceMappingURL=babylon.passPostProcess.js.map
  65741. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65742. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65743. s = arguments[i];
  65744. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65745. t[p] = s[p];
  65746. }
  65747. return t;
  65748. };
  65749. var BABYLON;
  65750. (function (BABYLON) {
  65751. /**
  65752. * Default implementation IShadowGenerator.
  65753. * This is the main object responsible of generating shadows in the framework.
  65754. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65755. */
  65756. var ShadowGenerator = /** @class */ (function () {
  65757. /**
  65758. * Creates a ShadowGenerator object.
  65759. * A ShadowGenerator is the required tool to use the shadows.
  65760. * Each light casting shadows needs to use its own ShadowGenerator.
  65761. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65762. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65763. * @param light The light object generating the shadows.
  65764. * @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.
  65765. */
  65766. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65767. this._bias = 0.00005;
  65768. this._normalBias = 0;
  65769. this._blurBoxOffset = 1;
  65770. this._blurScale = 2;
  65771. this._blurKernel = 1;
  65772. this._useKernelBlur = false;
  65773. this._filter = ShadowGenerator.FILTER_NONE;
  65774. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65775. this._contactHardeningLightSizeUVRatio = 0.1;
  65776. this._darkness = 0;
  65777. this._transparencyShadow = false;
  65778. /**
  65779. * Controls the extent to which the shadows fade out at the edge of the frustum
  65780. * Used only by directionals and spots
  65781. */
  65782. this.frustumEdgeFalloff = 0;
  65783. /**
  65784. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65785. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65786. * It might on the other hand introduce peter panning.
  65787. */
  65788. this.forceBackFacesOnly = false;
  65789. this._lightDirection = BABYLON.Vector3.Zero();
  65790. this._viewMatrix = BABYLON.Matrix.Zero();
  65791. this._projectionMatrix = BABYLON.Matrix.Zero();
  65792. this._transformMatrix = BABYLON.Matrix.Zero();
  65793. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65794. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65795. this._currentFaceIndex = 0;
  65796. this._currentFaceIndexCache = 0;
  65797. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65798. this._mapSize = mapSize;
  65799. this._light = light;
  65800. this._scene = light.getScene();
  65801. light._shadowGenerator = this;
  65802. // Texture type fallback from float to int if not supported.
  65803. var caps = this._scene.getEngine().getCaps();
  65804. if (!useFullFloatFirst) {
  65805. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65806. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65807. }
  65808. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65809. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65810. }
  65811. else {
  65812. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65813. }
  65814. }
  65815. else {
  65816. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65817. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65818. }
  65819. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65820. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65821. }
  65822. else {
  65823. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65824. }
  65825. }
  65826. this._initializeGenerator();
  65827. this._applyFilterValues();
  65828. }
  65829. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65830. /**
  65831. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65832. */
  65833. get: function () {
  65834. return this._bias;
  65835. },
  65836. /**
  65837. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65838. */
  65839. set: function (bias) {
  65840. this._bias = bias;
  65841. },
  65842. enumerable: true,
  65843. configurable: true
  65844. });
  65845. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65846. /**
  65847. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65848. */
  65849. get: function () {
  65850. return this._normalBias;
  65851. },
  65852. /**
  65853. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65854. */
  65855. set: function (normalBias) {
  65856. this._normalBias = normalBias;
  65857. },
  65858. enumerable: true,
  65859. configurable: true
  65860. });
  65861. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65862. /**
  65863. * Gets the blur box offset: offset applied during the blur pass.
  65864. * Only usefull if useKernelBlur = false
  65865. */
  65866. get: function () {
  65867. return this._blurBoxOffset;
  65868. },
  65869. /**
  65870. * Sets the blur box offset: offset applied during the blur pass.
  65871. * Only usefull if useKernelBlur = false
  65872. */
  65873. set: function (value) {
  65874. if (this._blurBoxOffset === value) {
  65875. return;
  65876. }
  65877. this._blurBoxOffset = value;
  65878. this._disposeBlurPostProcesses();
  65879. },
  65880. enumerable: true,
  65881. configurable: true
  65882. });
  65883. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65884. /**
  65885. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65886. * 2 means half of the size.
  65887. */
  65888. get: function () {
  65889. return this._blurScale;
  65890. },
  65891. /**
  65892. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65893. * 2 means half of the size.
  65894. */
  65895. set: function (value) {
  65896. if (this._blurScale === value) {
  65897. return;
  65898. }
  65899. this._blurScale = value;
  65900. this._disposeBlurPostProcesses();
  65901. },
  65902. enumerable: true,
  65903. configurable: true
  65904. });
  65905. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65906. /**
  65907. * Gets the blur kernel: kernel size of the blur pass.
  65908. * Only usefull if useKernelBlur = true
  65909. */
  65910. get: function () {
  65911. return this._blurKernel;
  65912. },
  65913. /**
  65914. * Sets the blur kernel: kernel size of the blur pass.
  65915. * Only usefull if useKernelBlur = true
  65916. */
  65917. set: function (value) {
  65918. if (this._blurKernel === value) {
  65919. return;
  65920. }
  65921. this._blurKernel = value;
  65922. this._disposeBlurPostProcesses();
  65923. },
  65924. enumerable: true,
  65925. configurable: true
  65926. });
  65927. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65928. /**
  65929. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65930. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65931. */
  65932. get: function () {
  65933. return this._useKernelBlur;
  65934. },
  65935. /**
  65936. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65937. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65938. */
  65939. set: function (value) {
  65940. if (this._useKernelBlur === value) {
  65941. return;
  65942. }
  65943. this._useKernelBlur = value;
  65944. this._disposeBlurPostProcesses();
  65945. },
  65946. enumerable: true,
  65947. configurable: true
  65948. });
  65949. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65950. /**
  65951. * Gets the depth scale used in ESM mode.
  65952. */
  65953. get: function () {
  65954. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65955. },
  65956. /**
  65957. * Sets the depth scale used in ESM mode.
  65958. * This can override the scale stored on the light.
  65959. */
  65960. set: function (value) {
  65961. this._depthScale = value;
  65962. },
  65963. enumerable: true,
  65964. configurable: true
  65965. });
  65966. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65967. /**
  65968. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65969. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65970. */
  65971. get: function () {
  65972. return this._filter;
  65973. },
  65974. /**
  65975. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65976. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65977. */
  65978. set: function (value) {
  65979. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65980. if (this._light.needCube()) {
  65981. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65982. this.useExponentialShadowMap = true;
  65983. return;
  65984. }
  65985. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65986. this.useCloseExponentialShadowMap = true;
  65987. return;
  65988. }
  65989. // PCF on cubemap would also be expensive
  65990. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65991. this.usePoissonSampling = true;
  65992. return;
  65993. }
  65994. }
  65995. // Weblg1 fallback for PCF.
  65996. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65997. if (this._scene.getEngine().webGLVersion === 1) {
  65998. this.usePoissonSampling = true;
  65999. return;
  66000. }
  66001. }
  66002. if (this._filter === value) {
  66003. return;
  66004. }
  66005. this._filter = value;
  66006. this._disposeBlurPostProcesses();
  66007. this._applyFilterValues();
  66008. this._light._markMeshesAsLightDirty();
  66009. },
  66010. enumerable: true,
  66011. configurable: true
  66012. });
  66013. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66014. /**
  66015. * Gets if the current filter is set to Poisson Sampling.
  66016. */
  66017. get: function () {
  66018. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66019. },
  66020. /**
  66021. * Sets the current filter to Poisson Sampling.
  66022. */
  66023. set: function (value) {
  66024. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66025. return;
  66026. }
  66027. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66028. },
  66029. enumerable: true,
  66030. configurable: true
  66031. });
  66032. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66033. /**
  66034. * Gets if the current filter is set to VSM.
  66035. * DEPRECATED. Should use useExponentialShadowMap instead.
  66036. */
  66037. get: function () {
  66038. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66039. return this.useExponentialShadowMap;
  66040. },
  66041. /**
  66042. * Sets the current filter is to VSM.
  66043. * DEPRECATED. Should use useExponentialShadowMap instead.
  66044. */
  66045. set: function (value) {
  66046. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66047. this.useExponentialShadowMap = value;
  66048. },
  66049. enumerable: true,
  66050. configurable: true
  66051. });
  66052. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66053. /**
  66054. * Gets if the current filter is set to blurred VSM.
  66055. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66056. */
  66057. get: function () {
  66058. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66059. return this.useBlurExponentialShadowMap;
  66060. },
  66061. /**
  66062. * Sets the current filter is to blurred VSM.
  66063. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66064. */
  66065. set: function (value) {
  66066. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66067. this.useBlurExponentialShadowMap = value;
  66068. },
  66069. enumerable: true,
  66070. configurable: true
  66071. });
  66072. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66073. /**
  66074. * Gets if the current filter is set to ESM.
  66075. */
  66076. get: function () {
  66077. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66078. },
  66079. /**
  66080. * Sets the current filter is to ESM.
  66081. */
  66082. set: function (value) {
  66083. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66084. return;
  66085. }
  66086. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66087. },
  66088. enumerable: true,
  66089. configurable: true
  66090. });
  66091. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66092. /**
  66093. * Gets if the current filter is set to filtered ESM.
  66094. */
  66095. get: function () {
  66096. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66097. },
  66098. /**
  66099. * Gets if the current filter is set to filtered ESM.
  66100. */
  66101. set: function (value) {
  66102. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66103. return;
  66104. }
  66105. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66106. },
  66107. enumerable: true,
  66108. configurable: true
  66109. });
  66110. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66111. /**
  66112. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66113. * exponential to prevent steep falloff artifacts).
  66114. */
  66115. get: function () {
  66116. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66117. },
  66118. /**
  66119. * Sets the current filter to "close ESM" (using the inverse of the
  66120. * exponential to prevent steep falloff artifacts).
  66121. */
  66122. set: function (value) {
  66123. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66124. return;
  66125. }
  66126. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66127. },
  66128. enumerable: true,
  66129. configurable: true
  66130. });
  66131. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66132. /**
  66133. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66134. * exponential to prevent steep falloff artifacts).
  66135. */
  66136. get: function () {
  66137. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66138. },
  66139. /**
  66140. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66141. * exponential to prevent steep falloff artifacts).
  66142. */
  66143. set: function (value) {
  66144. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66145. return;
  66146. }
  66147. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66148. },
  66149. enumerable: true,
  66150. configurable: true
  66151. });
  66152. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66153. /**
  66154. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66155. */
  66156. get: function () {
  66157. return this.filter === ShadowGenerator.FILTER_PCF;
  66158. },
  66159. /**
  66160. * Sets the current filter to "PCF" (percentage closer filtering).
  66161. */
  66162. set: function (value) {
  66163. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66164. return;
  66165. }
  66166. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66167. },
  66168. enumerable: true,
  66169. configurable: true
  66170. });
  66171. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66172. /**
  66173. * Gets the PCF or PCSS Quality.
  66174. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66175. */
  66176. get: function () {
  66177. return this._filteringQuality;
  66178. },
  66179. /**
  66180. * Sets the PCF or PCSS Quality.
  66181. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66182. */
  66183. set: function (filteringQuality) {
  66184. this._filteringQuality = filteringQuality;
  66185. },
  66186. enumerable: true,
  66187. configurable: true
  66188. });
  66189. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66190. /**
  66191. * Gets if the current filter is set to "PCSS" (contact hardening).
  66192. */
  66193. get: function () {
  66194. return this.filter === ShadowGenerator.FILTER_PCSS;
  66195. },
  66196. /**
  66197. * Sets the current filter to "PCSS" (contact hardening).
  66198. */
  66199. set: function (value) {
  66200. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66201. return;
  66202. }
  66203. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66204. },
  66205. enumerable: true,
  66206. configurable: true
  66207. });
  66208. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66209. /**
  66210. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66211. * Using a ratio helps keeping shape stability independently of the map size.
  66212. *
  66213. * It does not account for the light projection as it was having too much
  66214. * instability during the light setup or during light position changes.
  66215. *
  66216. * Only valid if useContactHardeningShadow is true.
  66217. */
  66218. get: function () {
  66219. return this._contactHardeningLightSizeUVRatio;
  66220. },
  66221. /**
  66222. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66223. * Using a ratio helps keeping shape stability independently of the map size.
  66224. *
  66225. * It does not account for the light projection as it was having too much
  66226. * instability during the light setup or during light position changes.
  66227. *
  66228. * Only valid if useContactHardeningShadow is true.
  66229. */
  66230. set: function (contactHardeningLightSizeUVRatio) {
  66231. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66232. },
  66233. enumerable: true,
  66234. configurable: true
  66235. });
  66236. /**
  66237. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66238. * 0 means strongest and 1 would means no shadow.
  66239. * @returns the darkness.
  66240. */
  66241. ShadowGenerator.prototype.getDarkness = function () {
  66242. return this._darkness;
  66243. };
  66244. /**
  66245. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66246. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66247. * @returns the shadow generator allowing fluent coding.
  66248. */
  66249. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66250. if (darkness >= 1.0)
  66251. this._darkness = 1.0;
  66252. else if (darkness <= 0.0)
  66253. this._darkness = 0.0;
  66254. else
  66255. this._darkness = darkness;
  66256. return this;
  66257. };
  66258. /**
  66259. * Sets the ability to have transparent shadow (boolean).
  66260. * @param transparent True if transparent else False
  66261. * @returns the shadow generator allowing fluent coding
  66262. */
  66263. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66264. this._transparencyShadow = transparent;
  66265. return this;
  66266. };
  66267. /**
  66268. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66269. * @returns The render target texture if present otherwise, null
  66270. */
  66271. ShadowGenerator.prototype.getShadowMap = function () {
  66272. return this._shadowMap;
  66273. };
  66274. /**
  66275. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66276. * @returns The render target texture if the shadow map is present otherwise, null
  66277. */
  66278. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66279. if (this._shadowMap2) {
  66280. return this._shadowMap2;
  66281. }
  66282. return this._shadowMap;
  66283. };
  66284. /**
  66285. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66286. * @param mesh Mesh to add
  66287. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66288. * @returns the Shadow Generator itself
  66289. */
  66290. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66291. if (includeDescendants === void 0) { includeDescendants = true; }
  66292. if (!this._shadowMap) {
  66293. return this;
  66294. }
  66295. if (!this._shadowMap.renderList) {
  66296. this._shadowMap.renderList = [];
  66297. }
  66298. this._shadowMap.renderList.push(mesh);
  66299. if (includeDescendants) {
  66300. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66301. }
  66302. return this;
  66303. var _a;
  66304. };
  66305. /**
  66306. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66307. * @param mesh Mesh to remove
  66308. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66309. * @returns the Shadow Generator itself
  66310. */
  66311. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66312. if (includeDescendants === void 0) { includeDescendants = true; }
  66313. if (!this._shadowMap || !this._shadowMap.renderList) {
  66314. return this;
  66315. }
  66316. var index = this._shadowMap.renderList.indexOf(mesh);
  66317. if (index !== -1) {
  66318. this._shadowMap.renderList.splice(index, 1);
  66319. }
  66320. if (includeDescendants) {
  66321. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66322. var child = _a[_i];
  66323. this.removeShadowCaster(child);
  66324. }
  66325. }
  66326. return this;
  66327. };
  66328. /**
  66329. * Returns the associated light object.
  66330. * @returns the light generating the shadow
  66331. */
  66332. ShadowGenerator.prototype.getLight = function () {
  66333. return this._light;
  66334. };
  66335. ShadowGenerator.prototype._initializeGenerator = function () {
  66336. this._light._markMeshesAsLightDirty();
  66337. this._initializeShadowMap();
  66338. };
  66339. ShadowGenerator.prototype._initializeShadowMap = function () {
  66340. var _this = this;
  66341. // Render target
  66342. var engine = this._scene.getEngine();
  66343. if (engine.webGLVersion > 1) {
  66344. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66345. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66346. }
  66347. else {
  66348. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66349. }
  66350. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66351. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66352. this._shadowMap.anisotropicFilteringLevel = 1;
  66353. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66354. this._shadowMap.renderParticles = false;
  66355. this._shadowMap.ignoreCameraViewport = true;
  66356. // Record Face Index before render.
  66357. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66358. _this._currentFaceIndex = faceIndex;
  66359. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66360. engine.setColorWrite(false);
  66361. }
  66362. });
  66363. // Custom render function.
  66364. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66365. // Blur if required afer render.
  66366. this._shadowMap.onAfterUnbindObservable.add(function () {
  66367. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66368. engine.setColorWrite(true);
  66369. }
  66370. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66371. return;
  66372. }
  66373. var shadowMap = _this.getShadowMapForRendering();
  66374. if (shadowMap) {
  66375. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66376. }
  66377. });
  66378. // Clear according to the chosen filter.
  66379. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66380. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66381. this._shadowMap.onClearObservable.add(function (engine) {
  66382. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66383. engine.clear(clearOne, false, true, false);
  66384. }
  66385. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66386. engine.clear(clearZero, true, true, false);
  66387. }
  66388. else {
  66389. engine.clear(clearOne, true, true, false);
  66390. }
  66391. });
  66392. };
  66393. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66394. var _this = this;
  66395. var engine = this._scene.getEngine();
  66396. var targetSize = this._mapSize / this.blurScale;
  66397. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66398. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66399. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66400. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66401. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66402. }
  66403. if (this.useKernelBlur) {
  66404. 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);
  66405. this._kernelBlurXPostprocess.width = targetSize;
  66406. this._kernelBlurXPostprocess.height = targetSize;
  66407. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66408. effect.setTexture("textureSampler", _this._shadowMap);
  66409. });
  66410. 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);
  66411. this._kernelBlurXPostprocess.autoClear = false;
  66412. this._kernelBlurYPostprocess.autoClear = false;
  66413. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66414. this._kernelBlurXPostprocess.packedFloat = true;
  66415. this._kernelBlurYPostprocess.packedFloat = true;
  66416. }
  66417. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66418. }
  66419. else {
  66420. 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);
  66421. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66422. effect.setFloat2("screenSize", targetSize, targetSize);
  66423. effect.setTexture("textureSampler", _this._shadowMap);
  66424. });
  66425. this._boxBlurPostprocess.autoClear = false;
  66426. this._blurPostProcesses = [this._boxBlurPostprocess];
  66427. }
  66428. };
  66429. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66430. var index;
  66431. var engine = this._scene.getEngine();
  66432. if (depthOnlySubMeshes.length) {
  66433. engine.setColorWrite(false);
  66434. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66435. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66436. }
  66437. engine.setColorWrite(true);
  66438. }
  66439. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66440. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66441. }
  66442. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66443. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66444. }
  66445. if (this._transparencyShadow) {
  66446. for (index = 0; index < transparentSubMeshes.length; index++) {
  66447. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66448. }
  66449. }
  66450. };
  66451. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66452. var _this = this;
  66453. var mesh = subMesh.getRenderingMesh();
  66454. var scene = this._scene;
  66455. var engine = scene.getEngine();
  66456. var material = subMesh.getMaterial();
  66457. if (!material) {
  66458. return;
  66459. }
  66460. // Culling
  66461. engine.setState(material.backFaceCulling);
  66462. // Managing instances
  66463. var batch = mesh._getInstancesRenderList(subMesh._id);
  66464. if (batch.mustReturn) {
  66465. return;
  66466. }
  66467. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66468. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66469. engine.enableEffect(this._effect);
  66470. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66471. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66472. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66473. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66474. this._effect.setVector3("lightData", this._cachedDirection);
  66475. }
  66476. else {
  66477. this._effect.setVector3("lightData", this._cachedPosition);
  66478. }
  66479. if (scene.activeCamera) {
  66480. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66481. }
  66482. // Alpha test
  66483. if (material && material.needAlphaTesting()) {
  66484. var alphaTexture = material.getAlphaTestTexture();
  66485. if (alphaTexture) {
  66486. this._effect.setTexture("diffuseSampler", alphaTexture);
  66487. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66488. }
  66489. }
  66490. // Bones
  66491. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66492. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66493. }
  66494. // Morph targets
  66495. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66496. if (this.forceBackFacesOnly) {
  66497. engine.setState(true, 0, false, true);
  66498. }
  66499. // Draw
  66500. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66501. if (this.forceBackFacesOnly) {
  66502. engine.setState(true, 0, false, false);
  66503. }
  66504. }
  66505. else {
  66506. // Need to reset refresh rate of the shadowMap
  66507. if (this._shadowMap) {
  66508. this._shadowMap.resetRefreshCounter();
  66509. }
  66510. }
  66511. };
  66512. ShadowGenerator.prototype._applyFilterValues = function () {
  66513. if (!this._shadowMap) {
  66514. return;
  66515. }
  66516. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66517. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66518. }
  66519. else {
  66520. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66521. }
  66522. };
  66523. /**
  66524. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66525. * @param onCompiled Callback triggered at the and of the effects compilation
  66526. * @param options Sets of optional options forcing the compilation with different modes
  66527. */
  66528. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66529. var _this = this;
  66530. var localOptions = __assign({ useInstances: false }, options);
  66531. var shadowMap = this.getShadowMap();
  66532. if (!shadowMap) {
  66533. if (onCompiled) {
  66534. onCompiled(this);
  66535. }
  66536. return;
  66537. }
  66538. var renderList = shadowMap.renderList;
  66539. if (!renderList) {
  66540. if (onCompiled) {
  66541. onCompiled(this);
  66542. }
  66543. return;
  66544. }
  66545. var subMeshes = new Array();
  66546. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66547. var mesh = renderList_1[_i];
  66548. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66549. }
  66550. if (subMeshes.length === 0) {
  66551. if (onCompiled) {
  66552. onCompiled(this);
  66553. }
  66554. return;
  66555. }
  66556. var currentIndex = 0;
  66557. var checkReady = function () {
  66558. if (!_this._scene || !_this._scene.getEngine()) {
  66559. return;
  66560. }
  66561. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66562. currentIndex++;
  66563. if (currentIndex >= subMeshes.length) {
  66564. if (onCompiled) {
  66565. onCompiled(_this);
  66566. }
  66567. return;
  66568. }
  66569. }
  66570. setTimeout(checkReady, 16);
  66571. };
  66572. checkReady();
  66573. };
  66574. /**
  66575. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66576. * @param options Sets of optional options forcing the compilation with different modes
  66577. * @returns A promise that resolves when the compilation completes
  66578. */
  66579. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66580. var _this = this;
  66581. return new Promise(function (resolve) {
  66582. _this.forceCompilation(function () {
  66583. resolve();
  66584. }, options);
  66585. });
  66586. };
  66587. /**
  66588. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66589. * @param subMesh The submesh we want to render in the shadow map
  66590. * @param useInstances Defines wether will draw in the map using instances
  66591. * @returns true if ready otherwise, false
  66592. */
  66593. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66594. var defines = [];
  66595. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66596. defines.push("#define FLOAT");
  66597. }
  66598. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66599. defines.push("#define ESM");
  66600. }
  66601. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66602. defines.push("#define DEPTHTEXTURE");
  66603. }
  66604. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66605. var mesh = subMesh.getMesh();
  66606. var material = subMesh.getMaterial();
  66607. // Normal bias.
  66608. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66609. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66610. defines.push("#define NORMAL");
  66611. if (mesh.nonUniformScaling) {
  66612. defines.push("#define NONUNIFORMSCALING");
  66613. }
  66614. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66615. defines.push("#define DIRECTIONINLIGHTDATA");
  66616. }
  66617. }
  66618. // Alpha test
  66619. if (material && material.needAlphaTesting()) {
  66620. var alphaTexture = material.getAlphaTestTexture();
  66621. if (alphaTexture) {
  66622. defines.push("#define ALPHATEST");
  66623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66624. attribs.push(BABYLON.VertexBuffer.UVKind);
  66625. defines.push("#define UV1");
  66626. }
  66627. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66628. if (alphaTexture.coordinatesIndex === 1) {
  66629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66630. defines.push("#define UV2");
  66631. }
  66632. }
  66633. }
  66634. }
  66635. // Bones
  66636. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66639. if (mesh.numBoneInfluencers > 4) {
  66640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66642. }
  66643. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66644. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66645. }
  66646. else {
  66647. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66648. }
  66649. // Morph targets
  66650. var manager = mesh.morphTargetManager;
  66651. var morphInfluencers = 0;
  66652. if (manager) {
  66653. if (manager.numInfluencers > 0) {
  66654. defines.push("#define MORPHTARGETS");
  66655. morphInfluencers = manager.numInfluencers;
  66656. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66657. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66658. }
  66659. }
  66660. // Instances
  66661. if (useInstances) {
  66662. defines.push("#define INSTANCES");
  66663. attribs.push("world0");
  66664. attribs.push("world1");
  66665. attribs.push("world2");
  66666. attribs.push("world3");
  66667. }
  66668. // Get correct effect
  66669. var join = defines.join("\n");
  66670. if (this._cachedDefines !== join) {
  66671. this._cachedDefines = join;
  66672. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66673. }
  66674. if (!this._effect.isReady()) {
  66675. return false;
  66676. }
  66677. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66678. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66679. this._initializeBlurRTTAndPostProcesses();
  66680. }
  66681. }
  66682. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66683. return false;
  66684. }
  66685. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66686. return false;
  66687. }
  66688. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66689. return false;
  66690. }
  66691. return true;
  66692. };
  66693. /**
  66694. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66695. * @param defines Defines of the material we want to update
  66696. * @param lightIndex Index of the light in the enabled light list of the material
  66697. */
  66698. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66699. var scene = this._scene;
  66700. var light = this._light;
  66701. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66702. return;
  66703. }
  66704. defines["SHADOW" + lightIndex] = true;
  66705. if (this.useContactHardeningShadow) {
  66706. defines["SHADOWPCSS" + lightIndex] = true;
  66707. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66708. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66709. }
  66710. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66711. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66712. }
  66713. // else default to high.
  66714. }
  66715. if (this.usePercentageCloserFiltering) {
  66716. defines["SHADOWPCF" + lightIndex] = true;
  66717. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66718. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66719. }
  66720. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66721. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66722. }
  66723. // else default to high.
  66724. }
  66725. else if (this.usePoissonSampling) {
  66726. defines["SHADOWPOISSON" + lightIndex] = true;
  66727. }
  66728. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66729. defines["SHADOWESM" + lightIndex] = true;
  66730. }
  66731. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66732. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66733. }
  66734. if (light.needCube()) {
  66735. defines["SHADOWCUBE" + lightIndex] = true;
  66736. }
  66737. };
  66738. /**
  66739. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66740. * defined in the generator but impacting the effect).
  66741. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66742. * @param effect The effect we are binfing the information for
  66743. */
  66744. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66745. var light = this._light;
  66746. var scene = this._scene;
  66747. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66748. return;
  66749. }
  66750. var camera = scene.activeCamera;
  66751. if (!camera) {
  66752. return;
  66753. }
  66754. var shadowMap = this.getShadowMap();
  66755. if (!shadowMap) {
  66756. return;
  66757. }
  66758. if (!light.needCube()) {
  66759. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66760. }
  66761. // Only PCF uses depth stencil texture.
  66762. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66763. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66764. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66765. }
  66766. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66767. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66768. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66769. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66770. }
  66771. else {
  66772. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66773. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66774. }
  66775. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66776. };
  66777. /**
  66778. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66779. * (eq to shadow prjection matrix * light transform matrix)
  66780. * @returns The transform matrix used to create the shadow map
  66781. */
  66782. ShadowGenerator.prototype.getTransformMatrix = function () {
  66783. var scene = this._scene;
  66784. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66785. return this._transformMatrix;
  66786. }
  66787. this._currentRenderID = scene.getRenderId();
  66788. this._currentFaceIndexCache = this._currentFaceIndex;
  66789. var lightPosition = this._light.position;
  66790. if (this._light.computeTransformedInformation()) {
  66791. lightPosition = this._light.transformedPosition;
  66792. }
  66793. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66794. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66795. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66796. }
  66797. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66798. this._cachedPosition.copyFrom(lightPosition);
  66799. this._cachedDirection.copyFrom(this._lightDirection);
  66800. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66801. var shadowMap = this.getShadowMap();
  66802. if (shadowMap) {
  66803. var renderList = shadowMap.renderList;
  66804. if (renderList) {
  66805. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66806. }
  66807. }
  66808. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66809. }
  66810. return this._transformMatrix;
  66811. };
  66812. /**
  66813. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66814. * Cube and 2D textures for instance.
  66815. */
  66816. ShadowGenerator.prototype.recreateShadowMap = function () {
  66817. var shadowMap = this._shadowMap;
  66818. if (!shadowMap) {
  66819. return;
  66820. }
  66821. // Track render list.
  66822. var renderList = shadowMap.renderList;
  66823. // Clean up existing data.
  66824. this._disposeRTTandPostProcesses();
  66825. // Reinitializes.
  66826. this._initializeGenerator();
  66827. // Reaffect the filter to ensure a correct fallback if necessary.
  66828. this.filter = this.filter;
  66829. // Reaffect the filter.
  66830. this._applyFilterValues();
  66831. // Reaffect Render List.
  66832. this._shadowMap.renderList = renderList;
  66833. };
  66834. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66835. if (this._shadowMap2) {
  66836. this._shadowMap2.dispose();
  66837. this._shadowMap2 = null;
  66838. }
  66839. if (this._boxBlurPostprocess) {
  66840. this._boxBlurPostprocess.dispose();
  66841. this._boxBlurPostprocess = null;
  66842. }
  66843. if (this._kernelBlurXPostprocess) {
  66844. this._kernelBlurXPostprocess.dispose();
  66845. this._kernelBlurXPostprocess = null;
  66846. }
  66847. if (this._kernelBlurYPostprocess) {
  66848. this._kernelBlurYPostprocess.dispose();
  66849. this._kernelBlurYPostprocess = null;
  66850. }
  66851. this._blurPostProcesses = [];
  66852. };
  66853. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66854. if (this._shadowMap) {
  66855. this._shadowMap.dispose();
  66856. this._shadowMap = null;
  66857. }
  66858. this._disposeBlurPostProcesses();
  66859. };
  66860. /**
  66861. * Disposes the ShadowGenerator.
  66862. * Returns nothing.
  66863. */
  66864. ShadowGenerator.prototype.dispose = function () {
  66865. this._disposeRTTandPostProcesses();
  66866. if (this._light) {
  66867. this._light._shadowGenerator = null;
  66868. this._light._markMeshesAsLightDirty();
  66869. }
  66870. };
  66871. /**
  66872. * Serializes the shadow generator setup to a json object.
  66873. * @returns The serialized JSON object
  66874. */
  66875. ShadowGenerator.prototype.serialize = function () {
  66876. var serializationObject = {};
  66877. var shadowMap = this.getShadowMap();
  66878. if (!shadowMap) {
  66879. return serializationObject;
  66880. }
  66881. serializationObject.lightId = this._light.id;
  66882. serializationObject.mapSize = shadowMap.getRenderSize();
  66883. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66884. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66885. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66886. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66887. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66888. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66889. serializationObject.depthScale = this.depthScale;
  66890. serializationObject.darkness = this.getDarkness();
  66891. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66892. serializationObject.blurKernel = this.blurKernel;
  66893. serializationObject.blurScale = this.blurScale;
  66894. serializationObject.useKernelBlur = this.useKernelBlur;
  66895. serializationObject.transparencyShadow = this._transparencyShadow;
  66896. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66897. serializationObject.bias = this.bias;
  66898. serializationObject.normalBias = this.normalBias;
  66899. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66900. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66901. serializationObject.filteringQuality = this.filteringQuality;
  66902. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66903. serializationObject.renderList = [];
  66904. if (shadowMap.renderList) {
  66905. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66906. var mesh = shadowMap.renderList[meshIndex];
  66907. serializationObject.renderList.push(mesh.id);
  66908. }
  66909. }
  66910. return serializationObject;
  66911. };
  66912. /**
  66913. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66914. * @param parsedShadowGenerator The JSON object to parse
  66915. * @param scene The scene to create the shadow map for
  66916. * @returns The parsed shadow generator
  66917. */
  66918. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66919. //casting to point light, as light is missing the position attr and typescript complains.
  66920. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66921. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66922. var shadowMap = shadowGenerator.getShadowMap();
  66923. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66924. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66925. meshes.forEach(function (mesh) {
  66926. if (!shadowMap) {
  66927. return;
  66928. }
  66929. if (!shadowMap.renderList) {
  66930. shadowMap.renderList = [];
  66931. }
  66932. shadowMap.renderList.push(mesh);
  66933. });
  66934. }
  66935. if (parsedShadowGenerator.usePoissonSampling) {
  66936. shadowGenerator.usePoissonSampling = true;
  66937. }
  66938. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66939. shadowGenerator.useExponentialShadowMap = true;
  66940. }
  66941. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66942. shadowGenerator.useBlurExponentialShadowMap = true;
  66943. }
  66944. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66945. shadowGenerator.useCloseExponentialShadowMap = true;
  66946. }
  66947. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66948. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66949. }
  66950. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66951. shadowGenerator.usePercentageCloserFiltering = true;
  66952. }
  66953. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66954. shadowGenerator.useContactHardeningShadow = true;
  66955. }
  66956. if (parsedShadowGenerator.filteringQuality) {
  66957. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66958. }
  66959. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66960. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66961. }
  66962. // Backward compat
  66963. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66964. shadowGenerator.useExponentialShadowMap = true;
  66965. }
  66966. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66967. shadowGenerator.useBlurExponentialShadowMap = true;
  66968. }
  66969. if (parsedShadowGenerator.depthScale) {
  66970. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66971. }
  66972. if (parsedShadowGenerator.blurScale) {
  66973. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66974. }
  66975. if (parsedShadowGenerator.blurBoxOffset) {
  66976. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66977. }
  66978. if (parsedShadowGenerator.useKernelBlur) {
  66979. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66980. }
  66981. if (parsedShadowGenerator.blurKernel) {
  66982. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66983. }
  66984. if (parsedShadowGenerator.bias !== undefined) {
  66985. shadowGenerator.bias = parsedShadowGenerator.bias;
  66986. }
  66987. if (parsedShadowGenerator.normalBias !== undefined) {
  66988. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66989. }
  66990. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66991. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66992. }
  66993. if (parsedShadowGenerator.darkness) {
  66994. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66995. }
  66996. if (parsedShadowGenerator.transparencyShadow) {
  66997. shadowGenerator.setTransparencyShadow(true);
  66998. }
  66999. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67000. return shadowGenerator;
  67001. };
  67002. /**
  67003. * Shadow generator mode None: no filtering applied.
  67004. */
  67005. ShadowGenerator.FILTER_NONE = 0;
  67006. /**
  67007. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67008. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67009. */
  67010. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67011. /**
  67012. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67013. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67014. */
  67015. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67016. /**
  67017. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67018. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67019. */
  67020. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67021. /**
  67022. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67023. * edge artifacts on steep falloff.
  67024. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67025. */
  67026. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67027. /**
  67028. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67029. * edge artifacts on steep falloff.
  67030. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67031. */
  67032. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67033. /**
  67034. * Shadow generator mode PCF: Percentage Closer Filtering
  67035. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67036. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67037. */
  67038. ShadowGenerator.FILTER_PCF = 6;
  67039. /**
  67040. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67041. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67042. * Contact Hardening
  67043. */
  67044. ShadowGenerator.FILTER_PCSS = 7;
  67045. /**
  67046. * Reserved for PCF and PCSS
  67047. * Highest Quality.
  67048. *
  67049. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67050. *
  67051. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67052. */
  67053. ShadowGenerator.QUALITY_HIGH = 0;
  67054. /**
  67055. * Reserved for PCF and PCSS
  67056. * Good tradeoff for quality/perf cross devices
  67057. *
  67058. * Execute PCF on a 3*3 kernel.
  67059. *
  67060. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67061. */
  67062. ShadowGenerator.QUALITY_MEDIUM = 1;
  67063. /**
  67064. * Reserved for PCF and PCSS
  67065. * The lowest quality but the fastest.
  67066. *
  67067. * Execute PCF on a 1*1 kernel.
  67068. *
  67069. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67070. */
  67071. ShadowGenerator.QUALITY_LOW = 2;
  67072. return ShadowGenerator;
  67073. }());
  67074. BABYLON.ShadowGenerator = ShadowGenerator;
  67075. })(BABYLON || (BABYLON = {}));
  67076. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67077. var BABYLON;
  67078. (function (BABYLON) {
  67079. var DefaultLoadingScreen = /** @class */ (function () {
  67080. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67081. if (_loadingText === void 0) { _loadingText = ""; }
  67082. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67083. var _this = this;
  67084. this._renderingCanvas = _renderingCanvas;
  67085. this._loadingText = _loadingText;
  67086. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67087. // Resize
  67088. this._resizeLoadingUI = function () {
  67089. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67090. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67091. if (!_this._loadingDiv) {
  67092. return;
  67093. }
  67094. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67095. _this._loadingDiv.style.left = canvasRect.left + "px";
  67096. _this._loadingDiv.style.top = canvasRect.top + "px";
  67097. _this._loadingDiv.style.width = canvasRect.width + "px";
  67098. _this._loadingDiv.style.height = canvasRect.height + "px";
  67099. };
  67100. }
  67101. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67102. if (this._loadingDiv) {
  67103. // Do not add a loading screen if there is already one
  67104. return;
  67105. }
  67106. this._loadingDiv = document.createElement("div");
  67107. this._loadingDiv.id = "babylonjsLoadingDiv";
  67108. this._loadingDiv.style.opacity = "0";
  67109. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67110. this._loadingDiv.style.pointerEvents = "none";
  67111. // Loading text
  67112. this._loadingTextDiv = document.createElement("div");
  67113. this._loadingTextDiv.style.position = "absolute";
  67114. this._loadingTextDiv.style.left = "0";
  67115. this._loadingTextDiv.style.top = "50%";
  67116. this._loadingTextDiv.style.marginTop = "80px";
  67117. this._loadingTextDiv.style.width = "100%";
  67118. this._loadingTextDiv.style.height = "20px";
  67119. this._loadingTextDiv.style.fontFamily = "Arial";
  67120. this._loadingTextDiv.style.fontSize = "14px";
  67121. this._loadingTextDiv.style.color = "white";
  67122. this._loadingTextDiv.style.textAlign = "center";
  67123. this._loadingTextDiv.innerHTML = "Loading";
  67124. this._loadingDiv.appendChild(this._loadingTextDiv);
  67125. //set the predefined text
  67126. this._loadingTextDiv.innerHTML = this._loadingText;
  67127. // Generating keyframes
  67128. var style = document.createElement('style');
  67129. style.type = 'text/css';
  67130. 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 }";
  67131. style.innerHTML = keyFrames;
  67132. document.getElementsByTagName('head')[0].appendChild(style);
  67133. // Loading img
  67134. var imgBack = new Image();
  67135. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB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cWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67136. imgBack.style.position = "absolute";
  67137. imgBack.style.left = "50%";
  67138. imgBack.style.top = "50%";
  67139. imgBack.style.marginLeft = "-60px";
  67140. imgBack.style.marginTop = "-60px";
  67141. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67142. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67143. imgBack.style.transformOrigin = "50% 50%";
  67144. imgBack.style.webkitTransformOrigin = "50% 50%";
  67145. this._loadingDiv.appendChild(imgBack);
  67146. this._resizeLoadingUI();
  67147. window.addEventListener("resize", this._resizeLoadingUI);
  67148. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67149. document.body.appendChild(this._loadingDiv);
  67150. this._loadingDiv.style.opacity = "1";
  67151. };
  67152. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67153. var _this = this;
  67154. if (!this._loadingDiv) {
  67155. return;
  67156. }
  67157. var onTransitionEnd = function () {
  67158. if (!_this._loadingDiv) {
  67159. return;
  67160. }
  67161. document.body.removeChild(_this._loadingDiv);
  67162. window.removeEventListener("resize", _this._resizeLoadingUI);
  67163. _this._loadingDiv = null;
  67164. };
  67165. this._loadingDiv.style.opacity = "0";
  67166. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67167. };
  67168. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67169. set: function (text) {
  67170. this._loadingText = text;
  67171. if (this._loadingTextDiv) {
  67172. this._loadingTextDiv.innerHTML = this._loadingText;
  67173. }
  67174. },
  67175. enumerable: true,
  67176. configurable: true
  67177. });
  67178. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67179. get: function () {
  67180. return this._loadingDivBackgroundColor;
  67181. },
  67182. set: function (color) {
  67183. this._loadingDivBackgroundColor = color;
  67184. if (!this._loadingDiv) {
  67185. return;
  67186. }
  67187. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67188. },
  67189. enumerable: true,
  67190. configurable: true
  67191. });
  67192. return DefaultLoadingScreen;
  67193. }());
  67194. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67195. })(BABYLON || (BABYLON = {}));
  67196. //# sourceMappingURL=babylon.loadingScreen.js.map
  67197. var BABYLON;
  67198. (function (BABYLON) {
  67199. var SceneLoaderProgressEvent = /** @class */ (function () {
  67200. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67201. this.lengthComputable = lengthComputable;
  67202. this.loaded = loaded;
  67203. this.total = total;
  67204. }
  67205. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67206. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67207. };
  67208. return SceneLoaderProgressEvent;
  67209. }());
  67210. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67211. var SceneLoader = /** @class */ (function () {
  67212. function SceneLoader() {
  67213. }
  67214. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67215. get: function () {
  67216. return 0;
  67217. },
  67218. enumerable: true,
  67219. configurable: true
  67220. });
  67221. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67222. get: function () {
  67223. return 1;
  67224. },
  67225. enumerable: true,
  67226. configurable: true
  67227. });
  67228. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67229. get: function () {
  67230. return 2;
  67231. },
  67232. enumerable: true,
  67233. configurable: true
  67234. });
  67235. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67236. get: function () {
  67237. return 3;
  67238. },
  67239. enumerable: true,
  67240. configurable: true
  67241. });
  67242. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67243. get: function () {
  67244. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67245. },
  67246. set: function (value) {
  67247. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67248. },
  67249. enumerable: true,
  67250. configurable: true
  67251. });
  67252. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67253. get: function () {
  67254. return SceneLoader._ShowLoadingScreen;
  67255. },
  67256. set: function (value) {
  67257. SceneLoader._ShowLoadingScreen = value;
  67258. },
  67259. enumerable: true,
  67260. configurable: true
  67261. });
  67262. Object.defineProperty(SceneLoader, "loggingLevel", {
  67263. get: function () {
  67264. return SceneLoader._loggingLevel;
  67265. },
  67266. set: function (value) {
  67267. SceneLoader._loggingLevel = value;
  67268. },
  67269. enumerable: true,
  67270. configurable: true
  67271. });
  67272. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67273. get: function () {
  67274. return SceneLoader._CleanBoneMatrixWeights;
  67275. },
  67276. set: function (value) {
  67277. SceneLoader._CleanBoneMatrixWeights = value;
  67278. },
  67279. enumerable: true,
  67280. configurable: true
  67281. });
  67282. SceneLoader._getDefaultPlugin = function () {
  67283. return SceneLoader._registeredPlugins[".babylon"];
  67284. };
  67285. SceneLoader._getPluginForExtension = function (extension) {
  67286. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67287. if (registeredPlugin) {
  67288. return registeredPlugin;
  67289. }
  67290. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67291. return SceneLoader._getDefaultPlugin();
  67292. };
  67293. SceneLoader._getPluginForDirectLoad = function (data) {
  67294. for (var extension in SceneLoader._registeredPlugins) {
  67295. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67296. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67297. return SceneLoader._registeredPlugins[extension];
  67298. }
  67299. }
  67300. return SceneLoader._getDefaultPlugin();
  67301. };
  67302. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67303. if (sceneFilename.name) {
  67304. sceneFilename = sceneFilename.name;
  67305. }
  67306. var queryStringPosition = sceneFilename.indexOf("?");
  67307. if (queryStringPosition !== -1) {
  67308. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67309. }
  67310. var dotPosition = sceneFilename.lastIndexOf(".");
  67311. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67312. return SceneLoader._getPluginForExtension(extension);
  67313. };
  67314. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67315. SceneLoader._getDirectLoad = function (sceneFilename) {
  67316. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67317. return sceneFilename.substr(5);
  67318. }
  67319. return null;
  67320. };
  67321. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67322. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67323. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67324. var plugin;
  67325. if (registeredPlugin.plugin.createPlugin) {
  67326. plugin = registeredPlugin.plugin.createPlugin();
  67327. }
  67328. else {
  67329. plugin = registeredPlugin.plugin;
  67330. }
  67331. var useArrayBuffer = registeredPlugin.isBinary;
  67332. var database;
  67333. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67334. var dataCallback = function (data, responseURL) {
  67335. if (scene.isDisposed) {
  67336. onError("Scene has been disposed");
  67337. return;
  67338. }
  67339. scene.database = database;
  67340. onSuccess(plugin, data, responseURL);
  67341. };
  67342. var request = null;
  67343. var pluginDisposed = false;
  67344. var onDisposeObservable = plugin.onDisposeObservable;
  67345. if (onDisposeObservable) {
  67346. onDisposeObservable.add(function () {
  67347. pluginDisposed = true;
  67348. if (request) {
  67349. request.abort();
  67350. request = null;
  67351. }
  67352. onDispose();
  67353. });
  67354. }
  67355. var manifestChecked = function () {
  67356. if (pluginDisposed) {
  67357. return;
  67358. }
  67359. var url = rootUrl + sceneFilename;
  67360. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67361. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67362. } : undefined, database, useArrayBuffer, function (request, exception) {
  67363. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67364. });
  67365. };
  67366. if (directLoad) {
  67367. dataCallback(directLoad);
  67368. return plugin;
  67369. }
  67370. if (rootUrl.indexOf("file:") === -1) {
  67371. var engine = scene.getEngine();
  67372. var canUseOfflineSupport = engine.enableOfflineSupport;
  67373. if (canUseOfflineSupport) {
  67374. // Also check for exceptions
  67375. var exceptionFound = false;
  67376. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67377. var regex = _a[_i];
  67378. if (regex.test(rootUrl + sceneFilename)) {
  67379. exceptionFound = true;
  67380. break;
  67381. }
  67382. }
  67383. canUseOfflineSupport = !exceptionFound;
  67384. }
  67385. if (canUseOfflineSupport) {
  67386. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67387. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67388. }
  67389. else {
  67390. manifestChecked();
  67391. }
  67392. }
  67393. // Loading file from disk via input file or drag'n'drop
  67394. else {
  67395. var fileOrString = sceneFilename;
  67396. if (fileOrString.name) { // File
  67397. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67398. }
  67399. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67400. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67401. }
  67402. else {
  67403. onError("Unable to find file named " + sceneFilename);
  67404. }
  67405. }
  67406. return plugin;
  67407. };
  67408. // Public functions
  67409. SceneLoader.GetPluginForExtension = function (extension) {
  67410. return SceneLoader._getPluginForExtension(extension).plugin;
  67411. };
  67412. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67413. return !!SceneLoader._registeredPlugins[extension];
  67414. };
  67415. SceneLoader.RegisterPlugin = function (plugin) {
  67416. if (typeof plugin.extensions === "string") {
  67417. var extension = plugin.extensions;
  67418. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67419. plugin: plugin,
  67420. isBinary: false
  67421. };
  67422. }
  67423. else {
  67424. var extensions = plugin.extensions;
  67425. Object.keys(extensions).forEach(function (extension) {
  67426. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67427. plugin: plugin,
  67428. isBinary: extensions[extension].isBinary
  67429. };
  67430. });
  67431. }
  67432. };
  67433. /**
  67434. * Import meshes into a scene
  67435. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67436. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67437. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67438. * @param scene the instance of BABYLON.Scene to append to
  67439. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67440. * @param onProgress a callback with a progress event for each file being loaded
  67441. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67442. * @param pluginExtension the extension used to determine the plugin
  67443. * @returns The loaded plugin
  67444. */
  67445. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67446. if (sceneFilename === void 0) { sceneFilename = ""; }
  67447. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67448. if (onSuccess === void 0) { onSuccess = null; }
  67449. if (onProgress === void 0) { onProgress = null; }
  67450. if (onError === void 0) { onError = null; }
  67451. if (pluginExtension === void 0) { pluginExtension = null; }
  67452. if (!scene) {
  67453. BABYLON.Tools.Error("No scene available to import mesh to");
  67454. return null;
  67455. }
  67456. if (!sceneFilename) {
  67457. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67458. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67459. }
  67460. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67461. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67462. return null;
  67463. }
  67464. var loadingToken = {};
  67465. scene._addPendingData(loadingToken);
  67466. var disposeHandler = function () {
  67467. scene._removePendingData(loadingToken);
  67468. };
  67469. var errorHandler = function (message, exception) {
  67470. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67471. if (onError) {
  67472. onError(scene, errorMessage, exception);
  67473. }
  67474. else {
  67475. BABYLON.Tools.Error(errorMessage);
  67476. // should the exception be thrown?
  67477. }
  67478. disposeHandler();
  67479. };
  67480. var progressHandler = onProgress ? function (event) {
  67481. try {
  67482. onProgress(event);
  67483. }
  67484. catch (e) {
  67485. errorHandler("Error in onProgress callback", e);
  67486. }
  67487. } : undefined;
  67488. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67489. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67490. if (onSuccess) {
  67491. try {
  67492. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67493. }
  67494. catch (e) {
  67495. errorHandler("Error in onSuccess callback", e);
  67496. }
  67497. }
  67498. scene._removePendingData(loadingToken);
  67499. };
  67500. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67501. if (plugin.rewriteRootURL) {
  67502. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67503. }
  67504. if (sceneFilename === "") {
  67505. if (sceneFilename === "") {
  67506. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67507. }
  67508. }
  67509. if (plugin.importMesh) {
  67510. var syncedPlugin = plugin;
  67511. var meshes = new Array();
  67512. var particleSystems = new Array();
  67513. var skeletons = new Array();
  67514. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67515. return;
  67516. }
  67517. scene.loadingPluginName = plugin.name;
  67518. successHandler(meshes, particleSystems, skeletons, []);
  67519. }
  67520. else {
  67521. var asyncedPlugin = plugin;
  67522. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67523. scene.loadingPluginName = plugin.name;
  67524. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67525. }).catch(function (error) {
  67526. errorHandler(error.message, error);
  67527. });
  67528. }
  67529. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67530. };
  67531. /**
  67532. * Import meshes into a scene
  67533. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67534. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67535. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67536. * @param scene the instance of BABYLON.Scene to append to
  67537. * @param onProgress a callback with a progress event for each file being loaded
  67538. * @param pluginExtension the extension used to determine the plugin
  67539. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67540. */
  67541. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67542. if (sceneFilename === void 0) { sceneFilename = ""; }
  67543. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67544. if (onProgress === void 0) { onProgress = null; }
  67545. if (pluginExtension === void 0) { pluginExtension = null; }
  67546. return new Promise(function (resolve, reject) {
  67547. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67548. resolve({
  67549. meshes: meshes,
  67550. particleSystems: particleSystems,
  67551. skeletons: skeletons,
  67552. animationGroups: animationGroups
  67553. });
  67554. }, onProgress, function (scene, message, exception) {
  67555. reject(exception || new Error(message));
  67556. }, pluginExtension);
  67557. });
  67558. };
  67559. /**
  67560. * Load a scene
  67561. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67562. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67563. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67564. * @param onSuccess a callback with the scene when import succeeds
  67565. * @param onProgress a callback with a progress event for each file being loaded
  67566. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67567. * @param pluginExtension the extension used to determine the plugin
  67568. * @returns The loaded plugin
  67569. */
  67570. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67571. if (onSuccess === void 0) { onSuccess = null; }
  67572. if (onProgress === void 0) { onProgress = null; }
  67573. if (onError === void 0) { onError = null; }
  67574. if (pluginExtension === void 0) { pluginExtension = null; }
  67575. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67576. };
  67577. /**
  67578. * Load a scene
  67579. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67580. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67581. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67582. * @param onProgress a callback with a progress event for each file being loaded
  67583. * @param pluginExtension the extension used to determine the plugin
  67584. * @returns The loaded scene
  67585. */
  67586. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67587. if (onProgress === void 0) { onProgress = null; }
  67588. if (pluginExtension === void 0) { pluginExtension = null; }
  67589. return new Promise(function (resolve, reject) {
  67590. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67591. resolve(scene);
  67592. }, onProgress, function (scene, message, exception) {
  67593. reject(exception || new Error(message));
  67594. }, pluginExtension);
  67595. });
  67596. };
  67597. /**
  67598. * Append a scene
  67599. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67600. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67601. * @param scene is the instance of BABYLON.Scene to append to
  67602. * @param onSuccess a callback with the scene when import succeeds
  67603. * @param onProgress a callback with a progress event for each file being loaded
  67604. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67605. * @param pluginExtension the extension used to determine the plugin
  67606. * @returns The loaded plugin
  67607. */
  67608. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67609. if (sceneFilename === void 0) { sceneFilename = ""; }
  67610. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67611. if (onSuccess === void 0) { onSuccess = null; }
  67612. if (onProgress === void 0) { onProgress = null; }
  67613. if (onError === void 0) { onError = null; }
  67614. if (pluginExtension === void 0) { pluginExtension = null; }
  67615. if (!scene) {
  67616. BABYLON.Tools.Error("No scene available to append to");
  67617. return null;
  67618. }
  67619. if (!sceneFilename) {
  67620. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67621. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67622. }
  67623. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67624. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67625. return null;
  67626. }
  67627. if (SceneLoader.ShowLoadingScreen) {
  67628. scene.getEngine().displayLoadingUI();
  67629. }
  67630. var loadingToken = {};
  67631. scene._addPendingData(loadingToken);
  67632. var disposeHandler = function () {
  67633. scene._removePendingData(loadingToken);
  67634. scene.getEngine().hideLoadingUI();
  67635. };
  67636. var errorHandler = function (message, exception) {
  67637. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67638. if (onError) {
  67639. onError(scene, errorMessage, exception);
  67640. }
  67641. else {
  67642. BABYLON.Tools.Error(errorMessage);
  67643. // should the exception be thrown?
  67644. }
  67645. disposeHandler();
  67646. };
  67647. var progressHandler = onProgress ? function (event) {
  67648. try {
  67649. onProgress(event);
  67650. }
  67651. catch (e) {
  67652. errorHandler("Error in onProgress callback", e);
  67653. }
  67654. } : undefined;
  67655. var successHandler = function () {
  67656. if (onSuccess) {
  67657. try {
  67658. onSuccess(scene);
  67659. }
  67660. catch (e) {
  67661. errorHandler("Error in onSuccess callback", e);
  67662. }
  67663. }
  67664. scene._removePendingData(loadingToken);
  67665. };
  67666. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67667. if (sceneFilename === "") {
  67668. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67669. }
  67670. if (plugin.load) {
  67671. var syncedPlugin = plugin;
  67672. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67673. return;
  67674. }
  67675. scene.loadingPluginName = plugin.name;
  67676. successHandler();
  67677. }
  67678. else {
  67679. var asyncedPlugin = plugin;
  67680. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67681. scene.loadingPluginName = plugin.name;
  67682. successHandler();
  67683. }).catch(function (error) {
  67684. errorHandler(error.message, error);
  67685. });
  67686. }
  67687. if (SceneLoader.ShowLoadingScreen) {
  67688. scene.executeWhenReady(function () {
  67689. scene.getEngine().hideLoadingUI();
  67690. });
  67691. }
  67692. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67693. };
  67694. /**
  67695. * Append a scene
  67696. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67697. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67698. * @param scene is the instance of BABYLON.Scene to append to
  67699. * @param onProgress a callback with a progress event for each file being loaded
  67700. * @param pluginExtension the extension used to determine the plugin
  67701. * @returns The given scene
  67702. */
  67703. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67704. if (sceneFilename === void 0) { sceneFilename = ""; }
  67705. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67706. if (onProgress === void 0) { onProgress = null; }
  67707. if (pluginExtension === void 0) { pluginExtension = null; }
  67708. return new Promise(function (resolve, reject) {
  67709. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67710. resolve(scene);
  67711. }, onProgress, function (scene, message, exception) {
  67712. reject(exception || new Error(message));
  67713. }, pluginExtension);
  67714. });
  67715. };
  67716. /**
  67717. * Load a scene into an asset container
  67718. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67719. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67720. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67721. * @param onSuccess a callback with the scene when import succeeds
  67722. * @param onProgress a callback with a progress event for each file being loaded
  67723. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67724. * @param pluginExtension the extension used to determine the plugin
  67725. * @returns The loaded plugin
  67726. */
  67727. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67728. if (sceneFilename === void 0) { sceneFilename = ""; }
  67729. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67730. if (onSuccess === void 0) { onSuccess = null; }
  67731. if (onProgress === void 0) { onProgress = null; }
  67732. if (onError === void 0) { onError = null; }
  67733. if (pluginExtension === void 0) { pluginExtension = null; }
  67734. if (!scene) {
  67735. BABYLON.Tools.Error("No scene available to load asset container to");
  67736. return null;
  67737. }
  67738. if (!sceneFilename) {
  67739. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67740. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67741. }
  67742. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67743. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67744. return null;
  67745. }
  67746. var loadingToken = {};
  67747. scene._addPendingData(loadingToken);
  67748. var disposeHandler = function () {
  67749. scene._removePendingData(loadingToken);
  67750. };
  67751. var errorHandler = function (message, exception) {
  67752. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67753. if (onError) {
  67754. onError(scene, errorMessage, exception);
  67755. }
  67756. else {
  67757. BABYLON.Tools.Error(errorMessage);
  67758. // should the exception be thrown?
  67759. }
  67760. disposeHandler();
  67761. };
  67762. var progressHandler = onProgress ? function (event) {
  67763. try {
  67764. onProgress(event);
  67765. }
  67766. catch (e) {
  67767. errorHandler("Error in onProgress callback", e);
  67768. }
  67769. } : undefined;
  67770. var successHandler = function (assets) {
  67771. if (onSuccess) {
  67772. try {
  67773. onSuccess(assets);
  67774. }
  67775. catch (e) {
  67776. errorHandler("Error in onSuccess callback", e);
  67777. }
  67778. }
  67779. scene._removePendingData(loadingToken);
  67780. };
  67781. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67782. if (plugin.loadAssetContainer) {
  67783. var syncedPlugin = plugin;
  67784. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67785. if (!assetContainer) {
  67786. return;
  67787. }
  67788. scene.loadingPluginName = plugin.name;
  67789. successHandler(assetContainer);
  67790. }
  67791. else if (plugin.loadAssetContainerAsync) {
  67792. var asyncedPlugin = plugin;
  67793. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67794. scene.loadingPluginName = plugin.name;
  67795. successHandler(assetContainer);
  67796. }).catch(function (error) {
  67797. errorHandler(error.message, error);
  67798. });
  67799. }
  67800. else {
  67801. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67802. }
  67803. if (SceneLoader.ShowLoadingScreen) {
  67804. scene.executeWhenReady(function () {
  67805. scene.getEngine().hideLoadingUI();
  67806. });
  67807. }
  67808. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67809. };
  67810. /**
  67811. * Load a scene into an asset container
  67812. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67813. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67814. * @param scene is the instance of BABYLON.Scene to append to
  67815. * @param onProgress a callback with a progress event for each file being loaded
  67816. * @param pluginExtension the extension used to determine the plugin
  67817. * @returns The loaded asset container
  67818. */
  67819. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67820. if (sceneFilename === void 0) { sceneFilename = ""; }
  67821. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67822. if (onProgress === void 0) { onProgress = null; }
  67823. if (pluginExtension === void 0) { pluginExtension = null; }
  67824. return new Promise(function (resolve, reject) {
  67825. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67826. resolve(assetContainer);
  67827. }, onProgress, function (scene, message, exception) {
  67828. reject(exception || new Error(message));
  67829. }, pluginExtension);
  67830. });
  67831. };
  67832. // Flags
  67833. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67834. SceneLoader._ShowLoadingScreen = true;
  67835. SceneLoader._CleanBoneMatrixWeights = false;
  67836. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67837. // Members
  67838. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67839. SceneLoader._registeredPlugins = {};
  67840. return SceneLoader;
  67841. }());
  67842. BABYLON.SceneLoader = SceneLoader;
  67843. ;
  67844. })(BABYLON || (BABYLON = {}));
  67845. //# sourceMappingURL=babylon.sceneLoader.js.map
  67846. var BABYLON;
  67847. (function (BABYLON) {
  67848. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67849. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67850. var parsedMaterial = parsedData.materials[index];
  67851. if (parsedMaterial.id === id) {
  67852. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67853. }
  67854. }
  67855. return null;
  67856. };
  67857. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67858. for (var i in names) {
  67859. if (mesh.name === names[i]) {
  67860. hierarchyIds.push(mesh.id);
  67861. return true;
  67862. }
  67863. }
  67864. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67865. hierarchyIds.push(mesh.id);
  67866. return true;
  67867. }
  67868. return false;
  67869. };
  67870. var logOperation = function (operation, producer) {
  67871. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67872. };
  67873. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67874. if (addToScene === void 0) { addToScene = false; }
  67875. var container = new BABYLON.AssetContainer(scene);
  67876. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67877. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67878. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67879. // and avoid problems with multiple concurrent .babylon loads.
  67880. var log = "importScene has failed JSON parse";
  67881. try {
  67882. var parsedData = JSON.parse(data);
  67883. log = "";
  67884. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67885. var index;
  67886. var cache;
  67887. // Lights
  67888. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67889. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67890. var parsedLight = parsedData.lights[index];
  67891. var light = BABYLON.Light.Parse(parsedLight, scene);
  67892. if (light) {
  67893. container.lights.push(light);
  67894. log += (index === 0 ? "\n\tLights:" : "");
  67895. log += "\n\t\t" + light.toString(fullDetails);
  67896. }
  67897. }
  67898. }
  67899. // Animations
  67900. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67901. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67902. var parsedAnimation = parsedData.animations[index];
  67903. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67904. scene.animations.push(animation);
  67905. container.animations.push(animation);
  67906. log += (index === 0 ? "\n\tAnimations:" : "");
  67907. log += "\n\t\t" + animation.toString(fullDetails);
  67908. }
  67909. }
  67910. // Materials
  67911. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67912. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67913. var parsedMaterial = parsedData.materials[index];
  67914. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67915. container.materials.push(mat);
  67916. log += (index === 0 ? "\n\tMaterials:" : "");
  67917. log += "\n\t\t" + mat.toString(fullDetails);
  67918. }
  67919. }
  67920. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67921. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67922. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67923. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67924. container.multiMaterials.push(mmat);
  67925. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67926. log += "\n\t\t" + mmat.toString(fullDetails);
  67927. }
  67928. }
  67929. // Morph targets
  67930. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67931. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67932. var managerData = _a[_i];
  67933. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67934. }
  67935. }
  67936. // Skeletons
  67937. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67938. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67939. var parsedSkeleton = parsedData.skeletons[index];
  67940. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67941. container.skeletons.push(skeleton);
  67942. log += (index === 0 ? "\n\tSkeletons:" : "");
  67943. log += "\n\t\t" + skeleton.toString(fullDetails);
  67944. }
  67945. }
  67946. // Geometries
  67947. var geometries = parsedData.geometries;
  67948. if (geometries !== undefined && geometries !== null) {
  67949. var addedGeometry = new Array();
  67950. // Boxes
  67951. var boxes = geometries.boxes;
  67952. if (boxes !== undefined && boxes !== null) {
  67953. for (index = 0, cache = boxes.length; index < cache; index++) {
  67954. var parsedBox = boxes[index];
  67955. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67956. }
  67957. }
  67958. // Spheres
  67959. var spheres = geometries.spheres;
  67960. if (spheres !== undefined && spheres !== null) {
  67961. for (index = 0, cache = spheres.length; index < cache; index++) {
  67962. var parsedSphere = spheres[index];
  67963. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67964. }
  67965. }
  67966. // Cylinders
  67967. var cylinders = geometries.cylinders;
  67968. if (cylinders !== undefined && cylinders !== null) {
  67969. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67970. var parsedCylinder = cylinders[index];
  67971. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67972. }
  67973. }
  67974. // Toruses
  67975. var toruses = geometries.toruses;
  67976. if (toruses !== undefined && toruses !== null) {
  67977. for (index = 0, cache = toruses.length; index < cache; index++) {
  67978. var parsedTorus = toruses[index];
  67979. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67980. }
  67981. }
  67982. // Grounds
  67983. var grounds = geometries.grounds;
  67984. if (grounds !== undefined && grounds !== null) {
  67985. for (index = 0, cache = grounds.length; index < cache; index++) {
  67986. var parsedGround = grounds[index];
  67987. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67988. }
  67989. }
  67990. // Planes
  67991. var planes = geometries.planes;
  67992. if (planes !== undefined && planes !== null) {
  67993. for (index = 0, cache = planes.length; index < cache; index++) {
  67994. var parsedPlane = planes[index];
  67995. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67996. }
  67997. }
  67998. // TorusKnots
  67999. var torusKnots = geometries.torusKnots;
  68000. if (torusKnots !== undefined && torusKnots !== null) {
  68001. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68002. var parsedTorusKnot = torusKnots[index];
  68003. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68004. }
  68005. }
  68006. // VertexData
  68007. var vertexData = geometries.vertexData;
  68008. if (vertexData !== undefined && vertexData !== null) {
  68009. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68010. var parsedVertexData = vertexData[index];
  68011. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68012. }
  68013. }
  68014. addedGeometry.forEach(function (g) {
  68015. if (g) {
  68016. container.geometries.push(g);
  68017. }
  68018. });
  68019. }
  68020. // Transform nodes
  68021. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68022. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68023. var parsedTransformNode = parsedData.transformNodes[index];
  68024. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68025. container.transformNodes.push(node);
  68026. }
  68027. }
  68028. // Meshes
  68029. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68030. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68031. var parsedMesh = parsedData.meshes[index];
  68032. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68033. container.meshes.push(mesh);
  68034. log += (index === 0 ? "\n\tMeshes:" : "");
  68035. log += "\n\t\t" + mesh.toString(fullDetails);
  68036. }
  68037. }
  68038. // Cameras
  68039. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68040. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68041. var parsedCamera = parsedData.cameras[index];
  68042. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68043. container.cameras.push(camera);
  68044. log += (index === 0 ? "\n\tCameras:" : "");
  68045. log += "\n\t\t" + camera.toString(fullDetails);
  68046. }
  68047. }
  68048. // Browsing all the graph to connect the dots
  68049. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68050. var camera = scene.cameras[index];
  68051. if (camera._waitingParentId) {
  68052. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68053. camera._waitingParentId = null;
  68054. }
  68055. }
  68056. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68057. var light_1 = scene.lights[index];
  68058. if (light_1 && light_1._waitingParentId) {
  68059. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68060. light_1._waitingParentId = null;
  68061. }
  68062. }
  68063. // Sounds
  68064. // TODO: add sound
  68065. var loadedSounds = [];
  68066. var loadedSound;
  68067. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68068. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68069. var parsedSound = parsedData.sounds[index];
  68070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68071. if (!parsedSound.url)
  68072. parsedSound.url = parsedSound.name;
  68073. if (!loadedSounds[parsedSound.url]) {
  68074. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68075. loadedSounds[parsedSound.url] = loadedSound;
  68076. container.sounds.push(loadedSound);
  68077. }
  68078. else {
  68079. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68080. }
  68081. }
  68082. else {
  68083. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68084. }
  68085. }
  68086. }
  68087. loadedSounds = [];
  68088. // Connect parents & children and parse actions
  68089. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68090. var transformNode = scene.transformNodes[index];
  68091. if (transformNode._waitingParentId) {
  68092. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68093. transformNode._waitingParentId = null;
  68094. }
  68095. }
  68096. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68097. var mesh = scene.meshes[index];
  68098. if (mesh._waitingParentId) {
  68099. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68100. mesh._waitingParentId = null;
  68101. }
  68102. if (mesh._waitingActions) {
  68103. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68104. mesh._waitingActions = null;
  68105. }
  68106. }
  68107. // freeze world matrix application
  68108. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68109. var currentMesh = scene.meshes[index];
  68110. if (currentMesh._waitingFreezeWorldMatrix) {
  68111. currentMesh.freezeWorldMatrix();
  68112. currentMesh._waitingFreezeWorldMatrix = null;
  68113. }
  68114. else {
  68115. currentMesh.computeWorldMatrix(true);
  68116. }
  68117. }
  68118. // Particles Systems
  68119. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68120. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68121. var parsedParticleSystem = parsedData.particleSystems[index];
  68122. if (parsedParticleSystem.activeParticleCount) {
  68123. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68124. container.particleSystems.push(ps);
  68125. }
  68126. else {
  68127. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68128. container.particleSystems.push(ps);
  68129. }
  68130. }
  68131. }
  68132. // Lens flares
  68133. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68134. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68135. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68136. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68137. container.lensFlareSystems.push(lf);
  68138. }
  68139. }
  68140. // Shadows
  68141. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68142. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68143. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68144. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68145. container.shadowGenerators.push(sg);
  68146. }
  68147. }
  68148. // Lights exclusions / inclusions
  68149. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68150. var light_2 = scene.lights[index];
  68151. // Excluded check
  68152. if (light_2._excludedMeshesIds.length > 0) {
  68153. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68154. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68155. if (excludedMesh) {
  68156. light_2.excludedMeshes.push(excludedMesh);
  68157. }
  68158. }
  68159. light_2._excludedMeshesIds = [];
  68160. }
  68161. // Included check
  68162. if (light_2._includedOnlyMeshesIds.length > 0) {
  68163. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68164. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68165. if (includedOnlyMesh) {
  68166. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68167. }
  68168. }
  68169. light_2._includedOnlyMeshesIds = [];
  68170. }
  68171. }
  68172. // Effect layers
  68173. if (parsedData.effectLayers) {
  68174. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68175. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68176. container.effectLayers.push(effectLayer);
  68177. }
  68178. }
  68179. // Actions (scene)
  68180. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68181. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68182. }
  68183. if (!addToScene) {
  68184. container.removeAllFromScene();
  68185. }
  68186. }
  68187. catch (err) {
  68188. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68189. if (onError) {
  68190. onError(msg, err);
  68191. }
  68192. else {
  68193. BABYLON.Tools.Log(msg);
  68194. throw err;
  68195. }
  68196. }
  68197. finally {
  68198. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68199. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68200. }
  68201. }
  68202. return container;
  68203. };
  68204. BABYLON.SceneLoader.RegisterPlugin({
  68205. name: "babylon.js",
  68206. extensions: ".babylon",
  68207. canDirectLoad: function (data) {
  68208. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68209. return true;
  68210. }
  68211. return false;
  68212. },
  68213. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68214. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68215. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68216. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68217. // and avoid problems with multiple concurrent .babylon loads.
  68218. var log = "importMesh has failed JSON parse";
  68219. try {
  68220. var parsedData = JSON.parse(data);
  68221. log = "";
  68222. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68223. if (!meshesNames) {
  68224. meshesNames = null;
  68225. }
  68226. else if (!Array.isArray(meshesNames)) {
  68227. meshesNames = [meshesNames];
  68228. }
  68229. var hierarchyIds = new Array();
  68230. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68231. var loadedSkeletonsIds = [];
  68232. var loadedMaterialsIds = [];
  68233. var index;
  68234. var cache;
  68235. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68236. var parsedMesh = parsedData.meshes[index];
  68237. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68238. if (meshesNames !== null) {
  68239. // Remove found mesh name from list.
  68240. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68241. }
  68242. //Geometry?
  68243. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68244. //does the file contain geometries?
  68245. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68246. //find the correct geometry and add it to the scene
  68247. var found = false;
  68248. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68249. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68250. return;
  68251. }
  68252. else {
  68253. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68254. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68255. switch (geometryType) {
  68256. case "boxes":
  68257. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68258. break;
  68259. case "spheres":
  68260. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68261. break;
  68262. case "cylinders":
  68263. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68264. break;
  68265. case "toruses":
  68266. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68267. break;
  68268. case "grounds":
  68269. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68270. break;
  68271. case "planes":
  68272. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68273. break;
  68274. case "torusKnots":
  68275. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68276. break;
  68277. case "vertexData":
  68278. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68279. break;
  68280. }
  68281. found = true;
  68282. }
  68283. });
  68284. }
  68285. });
  68286. if (found === false) {
  68287. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68288. }
  68289. }
  68290. }
  68291. // Material ?
  68292. if (parsedMesh.materialId) {
  68293. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68294. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68295. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68296. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68297. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68298. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68299. var subMatId = parsedMultiMaterial.materials[matIndex];
  68300. loadedMaterialsIds.push(subMatId);
  68301. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68302. if (mat) {
  68303. log += "\n\tMaterial " + mat.toString(fullDetails);
  68304. }
  68305. }
  68306. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68307. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68308. if (mmat) {
  68309. materialFound = true;
  68310. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68311. }
  68312. break;
  68313. }
  68314. }
  68315. }
  68316. if (materialFound === false) {
  68317. loadedMaterialsIds.push(parsedMesh.materialId);
  68318. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68319. if (!mat) {
  68320. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68321. }
  68322. else {
  68323. log += "\n\tMaterial " + mat.toString(fullDetails);
  68324. }
  68325. }
  68326. }
  68327. // Skeleton ?
  68328. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68329. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68330. if (skeletonAlreadyLoaded === false) {
  68331. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68332. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68333. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68334. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68335. skeletons.push(skeleton);
  68336. loadedSkeletonsIds.push(parsedSkeleton.id);
  68337. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68338. }
  68339. }
  68340. }
  68341. }
  68342. // Morph targets ?
  68343. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68344. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68345. var managerData = _a[_i];
  68346. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68347. }
  68348. }
  68349. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68350. meshes.push(mesh);
  68351. log += "\n\tMesh " + mesh.toString(fullDetails);
  68352. }
  68353. }
  68354. // Connecting parents
  68355. var currentMesh;
  68356. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68357. currentMesh = scene.meshes[index];
  68358. if (currentMesh._waitingParentId) {
  68359. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68360. currentMesh._waitingParentId = null;
  68361. }
  68362. }
  68363. // freeze and compute world matrix application
  68364. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68365. currentMesh = scene.meshes[index];
  68366. if (currentMesh._waitingFreezeWorldMatrix) {
  68367. currentMesh.freezeWorldMatrix();
  68368. currentMesh._waitingFreezeWorldMatrix = null;
  68369. }
  68370. else {
  68371. currentMesh.computeWorldMatrix(true);
  68372. }
  68373. }
  68374. }
  68375. // Particles
  68376. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68377. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68378. var parsedParticleSystem = parsedData.particleSystems[index];
  68379. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68380. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68381. }
  68382. }
  68383. }
  68384. return true;
  68385. }
  68386. catch (err) {
  68387. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68388. if (onError) {
  68389. onError(msg, err);
  68390. }
  68391. else {
  68392. BABYLON.Tools.Log(msg);
  68393. throw err;
  68394. }
  68395. }
  68396. finally {
  68397. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68398. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68399. }
  68400. }
  68401. return false;
  68402. },
  68403. load: function (scene, data, rootUrl, onError) {
  68404. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68405. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68406. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68407. // and avoid problems with multiple concurrent .babylon loads.
  68408. var log = "importScene has failed JSON parse";
  68409. try {
  68410. var parsedData = JSON.parse(data);
  68411. log = "";
  68412. // Scene
  68413. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68414. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68415. }
  68416. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68417. scene.autoClear = parsedData.autoClear;
  68418. }
  68419. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68420. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68421. }
  68422. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68423. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68424. }
  68425. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68426. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68427. }
  68428. // Fog
  68429. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68430. scene.fogMode = parsedData.fogMode;
  68431. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68432. scene.fogStart = parsedData.fogStart;
  68433. scene.fogEnd = parsedData.fogEnd;
  68434. scene.fogDensity = parsedData.fogDensity;
  68435. log += "\tFog mode for scene: ";
  68436. switch (scene.fogMode) {
  68437. // getters not compiling, so using hardcoded
  68438. case 1:
  68439. log += "exp\n";
  68440. break;
  68441. case 2:
  68442. log += "exp2\n";
  68443. break;
  68444. case 3:
  68445. log += "linear\n";
  68446. break;
  68447. }
  68448. }
  68449. //Physics
  68450. if (parsedData.physicsEnabled) {
  68451. var physicsPlugin;
  68452. if (parsedData.physicsEngine === "cannon") {
  68453. physicsPlugin = new BABYLON.CannonJSPlugin();
  68454. }
  68455. else if (parsedData.physicsEngine === "oimo") {
  68456. physicsPlugin = new BABYLON.OimoJSPlugin();
  68457. }
  68458. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68459. //else - default engine, which is currently oimo
  68460. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68461. scene.enablePhysics(physicsGravity, physicsPlugin);
  68462. }
  68463. // Metadata
  68464. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68465. scene.metadata = parsedData.metadata;
  68466. }
  68467. //collisions, if defined. otherwise, default is true
  68468. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68469. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68470. }
  68471. scene.workerCollisions = !!parsedData.workerCollisions;
  68472. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68473. if (!container) {
  68474. return false;
  68475. }
  68476. if (parsedData.autoAnimate) {
  68477. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68478. }
  68479. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68480. scene.setActiveCameraByID(parsedData.activeCameraID);
  68481. }
  68482. // Environment texture
  68483. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68484. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68485. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68486. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68487. if (parsedData.environmentTextureRotationY) {
  68488. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68489. }
  68490. scene.environmentTexture = hdrTexture;
  68491. }
  68492. else {
  68493. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68494. if (parsedData.environmentTextureRotationY) {
  68495. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68496. }
  68497. scene.environmentTexture = cubeTexture;
  68498. }
  68499. if (parsedData.createDefaultSkybox === true) {
  68500. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68501. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68502. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68503. }
  68504. }
  68505. // Finish
  68506. return true;
  68507. }
  68508. catch (err) {
  68509. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68510. if (onError) {
  68511. onError(msg, err);
  68512. }
  68513. else {
  68514. BABYLON.Tools.Log(msg);
  68515. throw err;
  68516. }
  68517. }
  68518. finally {
  68519. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68520. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68521. }
  68522. }
  68523. return false;
  68524. },
  68525. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68526. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68527. return container;
  68528. }
  68529. });
  68530. })(BABYLON || (BABYLON = {}));
  68531. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68532. var BABYLON;
  68533. (function (BABYLON) {
  68534. var FilesInput = /** @class */ (function () {
  68535. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68536. this.onProcessFileCallback = function () { return true; };
  68537. this._engine = engine;
  68538. this._currentScene = scene;
  68539. this._sceneLoadedCallback = sceneLoadedCallback;
  68540. this._progressCallback = progressCallback;
  68541. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68542. this._textureLoadingCallback = textureLoadingCallback;
  68543. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68544. this._onReloadCallback = onReloadCallback;
  68545. this._errorCallback = errorCallback;
  68546. }
  68547. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68548. var _this = this;
  68549. if (elementToMonitor) {
  68550. this._elementToMonitor = elementToMonitor;
  68551. this._dragEnterHandler = function (e) { _this.drag(e); };
  68552. this._dragOverHandler = function (e) { _this.drag(e); };
  68553. this._dropHandler = function (e) { _this.drop(e); };
  68554. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68555. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68556. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68557. }
  68558. };
  68559. FilesInput.prototype.dispose = function () {
  68560. if (!this._elementToMonitor) {
  68561. return;
  68562. }
  68563. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68564. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68565. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68566. };
  68567. FilesInput.prototype.renderFunction = function () {
  68568. if (this._additionalRenderLoopLogicCallback) {
  68569. this._additionalRenderLoopLogicCallback();
  68570. }
  68571. if (this._currentScene) {
  68572. if (this._textureLoadingCallback) {
  68573. var remaining = this._currentScene.getWaitingItemsCount();
  68574. if (remaining > 0) {
  68575. this._textureLoadingCallback(remaining);
  68576. }
  68577. }
  68578. this._currentScene.render();
  68579. }
  68580. };
  68581. FilesInput.prototype.drag = function (e) {
  68582. e.stopPropagation();
  68583. e.preventDefault();
  68584. };
  68585. FilesInput.prototype.drop = function (eventDrop) {
  68586. eventDrop.stopPropagation();
  68587. eventDrop.preventDefault();
  68588. this.loadFiles(eventDrop);
  68589. };
  68590. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68591. var _this = this;
  68592. var reader = folder.createReader();
  68593. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68594. reader.readEntries(function (entries) {
  68595. remaining.count += entries.length;
  68596. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68597. var entry = entries_1[_i];
  68598. if (entry.isFile) {
  68599. entry.file(function (file) {
  68600. file.correctName = relativePath + file.name;
  68601. files.push(file);
  68602. if (--remaining.count === 0) {
  68603. callback();
  68604. }
  68605. });
  68606. }
  68607. else if (entry.isDirectory) {
  68608. _this._traverseFolder(entry, files, remaining, callback);
  68609. }
  68610. }
  68611. if (--remaining.count) {
  68612. callback();
  68613. }
  68614. });
  68615. };
  68616. FilesInput.prototype._processFiles = function (files) {
  68617. for (var i = 0; i < files.length; i++) {
  68618. var name = files[i].correctName.toLowerCase();
  68619. var extension = name.split('.').pop();
  68620. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68621. continue;
  68622. }
  68623. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68624. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68625. this._sceneFileToLoad = files[i];
  68626. }
  68627. else {
  68628. FilesInput.FilesToLoad[name] = files[i];
  68629. }
  68630. }
  68631. };
  68632. FilesInput.prototype.loadFiles = function (event) {
  68633. var _this = this;
  68634. if (this._startingProcessingFilesCallback)
  68635. this._startingProcessingFilesCallback();
  68636. // Handling data transfer via drag'n'drop
  68637. if (event && event.dataTransfer && event.dataTransfer.files) {
  68638. this._filesToLoad = event.dataTransfer.files;
  68639. }
  68640. // Handling files from input files
  68641. if (event && event.target && event.target.files) {
  68642. this._filesToLoad = event.target.files;
  68643. }
  68644. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68645. var files_1 = new Array();
  68646. var folders = [];
  68647. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68648. for (var i = 0; i < this._filesToLoad.length; i++) {
  68649. var fileToLoad = this._filesToLoad[i];
  68650. var name_1 = fileToLoad.name.toLowerCase();
  68651. var entry = void 0;
  68652. fileToLoad.correctName = name_1;
  68653. if (items) {
  68654. var item = items[i];
  68655. if (item.getAsEntry) {
  68656. entry = item.getAsEntry();
  68657. }
  68658. else if (item.webkitGetAsEntry) {
  68659. entry = item.webkitGetAsEntry();
  68660. }
  68661. }
  68662. if (!entry) {
  68663. files_1.push(fileToLoad);
  68664. }
  68665. else {
  68666. if (entry.isDirectory) {
  68667. folders.push(entry);
  68668. }
  68669. else {
  68670. files_1.push(fileToLoad);
  68671. }
  68672. }
  68673. }
  68674. if (folders.length === 0) {
  68675. this._processFiles(files_1);
  68676. this._processReload();
  68677. }
  68678. else {
  68679. var remaining = { count: folders.length };
  68680. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68681. var folder = folders_1[_i];
  68682. this._traverseFolder(folder, files_1, remaining, function () {
  68683. _this._processFiles(files_1);
  68684. if (remaining.count === 0) {
  68685. _this._processReload();
  68686. }
  68687. });
  68688. }
  68689. }
  68690. }
  68691. };
  68692. FilesInput.prototype._processReload = function () {
  68693. if (this._onReloadCallback) {
  68694. this._onReloadCallback(this._sceneFileToLoad);
  68695. }
  68696. else {
  68697. this.reload();
  68698. }
  68699. };
  68700. FilesInput.prototype.reload = function () {
  68701. var _this = this;
  68702. // If a scene file has been provided
  68703. if (this._sceneFileToLoad) {
  68704. if (this._currentScene) {
  68705. if (BABYLON.Tools.errorsCount > 0) {
  68706. BABYLON.Tools.ClearLogCache();
  68707. }
  68708. this._engine.stopRenderLoop();
  68709. }
  68710. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68711. if (_this._progressCallback) {
  68712. _this._progressCallback(progress);
  68713. }
  68714. }).then(function (scene) {
  68715. if (_this._currentScene) {
  68716. _this._currentScene.dispose();
  68717. }
  68718. _this._currentScene = scene;
  68719. if (_this._sceneLoadedCallback) {
  68720. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68721. }
  68722. // Wait for textures and shaders to be ready
  68723. _this._currentScene.executeWhenReady(function () {
  68724. _this._engine.runRenderLoop(function () {
  68725. _this.renderFunction();
  68726. });
  68727. });
  68728. }).catch(function (error) {
  68729. if (_this._errorCallback) {
  68730. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68731. }
  68732. });
  68733. }
  68734. else {
  68735. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68736. }
  68737. };
  68738. FilesInput.FilesToLoad = {};
  68739. return FilesInput;
  68740. }());
  68741. BABYLON.FilesInput = FilesInput;
  68742. })(BABYLON || (BABYLON = {}));
  68743. //# sourceMappingURL=babylon.filesInput.js.map
  68744. var BABYLON;
  68745. (function (BABYLON) {
  68746. /**
  68747. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68748. * The underlying implementation relies on an associative array to ensure the best performances.
  68749. * The value can be anything including 'null' but except 'undefined'
  68750. */
  68751. var StringDictionary = /** @class */ (function () {
  68752. function StringDictionary() {
  68753. this._count = 0;
  68754. this._data = {};
  68755. }
  68756. /**
  68757. * This will clear this dictionary and copy the content from the 'source' one.
  68758. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68759. * @param source the dictionary to take the content from and copy to this dictionary
  68760. */
  68761. StringDictionary.prototype.copyFrom = function (source) {
  68762. var _this = this;
  68763. this.clear();
  68764. source.forEach(function (t, v) { return _this.add(t, v); });
  68765. };
  68766. /**
  68767. * Get a value based from its key
  68768. * @param key the given key to get the matching value from
  68769. * @return the value if found, otherwise undefined is returned
  68770. */
  68771. StringDictionary.prototype.get = function (key) {
  68772. var val = this._data[key];
  68773. if (val !== undefined) {
  68774. return val;
  68775. }
  68776. return undefined;
  68777. };
  68778. /**
  68779. * Get a value from its key or add it if it doesn't exist.
  68780. * This method will ensure you that a given key/data will be present in the dictionary.
  68781. * @param key the given key to get the matching value from
  68782. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68783. * The factory will only be invoked if there's no data for the given key.
  68784. * @return the value corresponding to the key.
  68785. */
  68786. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68787. var val = this.get(key);
  68788. if (val !== undefined) {
  68789. return val;
  68790. }
  68791. val = factory(key);
  68792. if (val) {
  68793. this.add(key, val);
  68794. }
  68795. return val;
  68796. };
  68797. /**
  68798. * Get a value from its key if present in the dictionary otherwise add it
  68799. * @param key the key to get the value from
  68800. * @param val if there's no such key/value pair in the dictionary add it with this value
  68801. * @return the value corresponding to the key
  68802. */
  68803. StringDictionary.prototype.getOrAdd = function (key, val) {
  68804. var curVal = this.get(key);
  68805. if (curVal !== undefined) {
  68806. return curVal;
  68807. }
  68808. this.add(key, val);
  68809. return val;
  68810. };
  68811. /**
  68812. * Check if there's a given key in the dictionary
  68813. * @param key the key to check for
  68814. * @return true if the key is present, false otherwise
  68815. */
  68816. StringDictionary.prototype.contains = function (key) {
  68817. return this._data[key] !== undefined;
  68818. };
  68819. /**
  68820. * Add a new key and its corresponding value
  68821. * @param key the key to add
  68822. * @param value the value corresponding to the key
  68823. * @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
  68824. */
  68825. StringDictionary.prototype.add = function (key, value) {
  68826. if (this._data[key] !== undefined) {
  68827. return false;
  68828. }
  68829. this._data[key] = value;
  68830. ++this._count;
  68831. return true;
  68832. };
  68833. StringDictionary.prototype.set = function (key, value) {
  68834. if (this._data[key] === undefined) {
  68835. return false;
  68836. }
  68837. this._data[key] = value;
  68838. return true;
  68839. };
  68840. /**
  68841. * Get the element of the given key and remove it from the dictionary
  68842. * @param key
  68843. */
  68844. StringDictionary.prototype.getAndRemove = function (key) {
  68845. var val = this.get(key);
  68846. if (val !== undefined) {
  68847. delete this._data[key];
  68848. --this._count;
  68849. return val;
  68850. }
  68851. return null;
  68852. };
  68853. /**
  68854. * Remove a key/value from the dictionary.
  68855. * @param key the key to remove
  68856. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68857. */
  68858. StringDictionary.prototype.remove = function (key) {
  68859. if (this.contains(key)) {
  68860. delete this._data[key];
  68861. --this._count;
  68862. return true;
  68863. }
  68864. return false;
  68865. };
  68866. /**
  68867. * Clear the whole content of the dictionary
  68868. */
  68869. StringDictionary.prototype.clear = function () {
  68870. this._data = {};
  68871. this._count = 0;
  68872. };
  68873. Object.defineProperty(StringDictionary.prototype, "count", {
  68874. get: function () {
  68875. return this._count;
  68876. },
  68877. enumerable: true,
  68878. configurable: true
  68879. });
  68880. /**
  68881. * Execute a callback on each key/val of the dictionary.
  68882. * Note that you can remove any element in this dictionary in the callback implementation
  68883. * @param callback the callback to execute on a given key/value pair
  68884. */
  68885. StringDictionary.prototype.forEach = function (callback) {
  68886. for (var cur in this._data) {
  68887. var val = this._data[cur];
  68888. callback(cur, val);
  68889. }
  68890. };
  68891. /**
  68892. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68893. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68894. * Note that you can remove any element in this dictionary in the callback implementation
  68895. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68896. */
  68897. StringDictionary.prototype.first = function (callback) {
  68898. for (var cur in this._data) {
  68899. var val = this._data[cur];
  68900. var res = callback(cur, val);
  68901. if (res) {
  68902. return res;
  68903. }
  68904. }
  68905. return null;
  68906. };
  68907. return StringDictionary;
  68908. }());
  68909. BABYLON.StringDictionary = StringDictionary;
  68910. })(BABYLON || (BABYLON = {}));
  68911. //# sourceMappingURL=babylon.stringDictionary.js.map
  68912. var BABYLON;
  68913. (function (BABYLON) {
  68914. var Tags = /** @class */ (function () {
  68915. function Tags() {
  68916. }
  68917. Tags.EnableFor = function (obj) {
  68918. obj._tags = obj._tags || {};
  68919. obj.hasTags = function () {
  68920. return Tags.HasTags(obj);
  68921. };
  68922. obj.addTags = function (tagsString) {
  68923. return Tags.AddTagsTo(obj, tagsString);
  68924. };
  68925. obj.removeTags = function (tagsString) {
  68926. return Tags.RemoveTagsFrom(obj, tagsString);
  68927. };
  68928. obj.matchesTagsQuery = function (tagsQuery) {
  68929. return Tags.MatchesQuery(obj, tagsQuery);
  68930. };
  68931. };
  68932. Tags.DisableFor = function (obj) {
  68933. delete obj._tags;
  68934. delete obj.hasTags;
  68935. delete obj.addTags;
  68936. delete obj.removeTags;
  68937. delete obj.matchesTagsQuery;
  68938. };
  68939. Tags.HasTags = function (obj) {
  68940. if (!obj._tags) {
  68941. return false;
  68942. }
  68943. return !BABYLON.Tools.IsEmpty(obj._tags);
  68944. };
  68945. Tags.GetTags = function (obj, asString) {
  68946. if (asString === void 0) { asString = true; }
  68947. if (!obj._tags) {
  68948. return null;
  68949. }
  68950. if (asString) {
  68951. var tagsArray = [];
  68952. for (var tag in obj._tags) {
  68953. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68954. tagsArray.push(tag);
  68955. }
  68956. }
  68957. return tagsArray.join(" ");
  68958. }
  68959. else {
  68960. return obj._tags;
  68961. }
  68962. };
  68963. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68964. // a tag cannot start with '||', '&&', and '!'
  68965. // it cannot contain whitespaces
  68966. Tags.AddTagsTo = function (obj, tagsString) {
  68967. if (!tagsString) {
  68968. return;
  68969. }
  68970. if (typeof tagsString !== "string") {
  68971. return;
  68972. }
  68973. var tags = tagsString.split(" ");
  68974. tags.forEach(function (tag, index, array) {
  68975. Tags._AddTagTo(obj, tag);
  68976. });
  68977. };
  68978. Tags._AddTagTo = function (obj, tag) {
  68979. tag = tag.trim();
  68980. if (tag === "" || tag === "true" || tag === "false") {
  68981. return;
  68982. }
  68983. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68984. return;
  68985. }
  68986. Tags.EnableFor(obj);
  68987. obj._tags[tag] = true;
  68988. };
  68989. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68990. if (!Tags.HasTags(obj)) {
  68991. return;
  68992. }
  68993. var tags = tagsString.split(" ");
  68994. for (var t in tags) {
  68995. Tags._RemoveTagFrom(obj, tags[t]);
  68996. }
  68997. };
  68998. Tags._RemoveTagFrom = function (obj, tag) {
  68999. delete obj._tags[tag];
  69000. };
  69001. Tags.MatchesQuery = function (obj, tagsQuery) {
  69002. if (tagsQuery === undefined) {
  69003. return true;
  69004. }
  69005. if (tagsQuery === "") {
  69006. return Tags.HasTags(obj);
  69007. }
  69008. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69009. };
  69010. return Tags;
  69011. }());
  69012. BABYLON.Tags = Tags;
  69013. })(BABYLON || (BABYLON = {}));
  69014. //# sourceMappingURL=babylon.tags.js.map
  69015. var BABYLON;
  69016. (function (BABYLON) {
  69017. /**
  69018. * Class used to evalaute queries containing `and` and `or` operators
  69019. */
  69020. var AndOrNotEvaluator = /** @class */ (function () {
  69021. function AndOrNotEvaluator() {
  69022. }
  69023. /**
  69024. * Evaluate a query
  69025. * @param query defines the query to evaluate
  69026. * @param evaluateCallback defines the callback used to filter result
  69027. * @returns true if the query matches
  69028. */
  69029. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69030. if (!query.match(/\([^\(\)]*\)/g)) {
  69031. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69032. }
  69033. else {
  69034. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69035. // remove parenthesis
  69036. r = r.slice(1, r.length - 1);
  69037. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69038. });
  69039. }
  69040. if (query === "true") {
  69041. return true;
  69042. }
  69043. if (query === "false") {
  69044. return false;
  69045. }
  69046. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69047. };
  69048. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69049. evaluateCallback = evaluateCallback || (function (r) {
  69050. return r === "true" ? true : false;
  69051. });
  69052. var result;
  69053. var or = parenthesisContent.split("||");
  69054. for (var i in or) {
  69055. if (or.hasOwnProperty(i)) {
  69056. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69057. var and = ori.split("&&");
  69058. if (and.length > 1) {
  69059. for (var j = 0; j < and.length; ++j) {
  69060. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69061. if (andj !== "true" && andj !== "false") {
  69062. if (andj[0] === "!") {
  69063. result = !evaluateCallback(andj.substring(1));
  69064. }
  69065. else {
  69066. result = evaluateCallback(andj);
  69067. }
  69068. }
  69069. else {
  69070. result = andj === "true" ? true : false;
  69071. }
  69072. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69073. ori = "false";
  69074. break;
  69075. }
  69076. }
  69077. }
  69078. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69079. result = true;
  69080. break;
  69081. }
  69082. // result equals false (or undefined)
  69083. if (ori !== "true" && ori !== "false") {
  69084. if (ori[0] === "!") {
  69085. result = !evaluateCallback(ori.substring(1));
  69086. }
  69087. else {
  69088. result = evaluateCallback(ori);
  69089. }
  69090. }
  69091. else {
  69092. result = ori === "true" ? true : false;
  69093. }
  69094. }
  69095. }
  69096. // the whole parenthesis scope is replaced by 'true' or 'false'
  69097. return result ? "true" : "false";
  69098. };
  69099. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69100. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69101. // remove whitespaces
  69102. r = r.replace(/[\s]/g, function () { return ""; });
  69103. return r.length % 2 ? "!" : "";
  69104. });
  69105. booleanString = booleanString.trim();
  69106. if (booleanString === "!true") {
  69107. booleanString = "false";
  69108. }
  69109. else if (booleanString === "!false") {
  69110. booleanString = "true";
  69111. }
  69112. return booleanString;
  69113. };
  69114. return AndOrNotEvaluator;
  69115. }());
  69116. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69117. })(BABYLON || (BABYLON = {}));
  69118. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69119. var BABYLON;
  69120. (function (BABYLON) {
  69121. /**
  69122. * Class used to enable access to IndexedDB
  69123. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69124. */
  69125. var Database = /** @class */ (function () {
  69126. /**
  69127. * Creates a new Database
  69128. * @param urlToScene defines the url to load the scene
  69129. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69130. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69131. */
  69132. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69133. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69134. var _this = this;
  69135. // Handling various flavors of prefixed version of IndexedDB
  69136. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69137. this.callbackManifestChecked = callbackManifestChecked;
  69138. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69139. this.db = null;
  69140. this._enableSceneOffline = false;
  69141. this._enableTexturesOffline = false;
  69142. this.manifestVersionFound = 0;
  69143. this.mustUpdateRessources = false;
  69144. this.hasReachedQuota = false;
  69145. if (!Database.IDBStorageEnabled) {
  69146. this.callbackManifestChecked(true);
  69147. }
  69148. else {
  69149. if (disableManifestCheck) {
  69150. this._enableSceneOffline = true;
  69151. this._enableTexturesOffline = true;
  69152. this.manifestVersionFound = 1;
  69153. BABYLON.Tools.SetImmediate(function () {
  69154. _this.callbackManifestChecked(true);
  69155. });
  69156. }
  69157. else {
  69158. this._checkManifestFile();
  69159. }
  69160. }
  69161. }
  69162. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69163. /**
  69164. * Gets a boolean indicating if scene must be saved in the database
  69165. */
  69166. get: function () {
  69167. return this._enableSceneOffline;
  69168. },
  69169. enumerable: true,
  69170. configurable: true
  69171. });
  69172. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69173. /**
  69174. * Gets a boolean indicating if textures must be saved in the database
  69175. */
  69176. get: function () {
  69177. return this._enableTexturesOffline;
  69178. },
  69179. enumerable: true,
  69180. configurable: true
  69181. });
  69182. Database.prototype._checkManifestFile = function () {
  69183. var _this = this;
  69184. var noManifestFile = function () {
  69185. _this._enableSceneOffline = false;
  69186. _this._enableTexturesOffline = false;
  69187. _this.callbackManifestChecked(false);
  69188. };
  69189. var timeStampUsed = false;
  69190. var manifestURL = this.currentSceneUrl + ".manifest";
  69191. var xhr = new XMLHttpRequest();
  69192. if (navigator.onLine) {
  69193. // Adding a timestamp to by-pass browsers' cache
  69194. timeStampUsed = true;
  69195. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69196. }
  69197. xhr.open("GET", manifestURL, true);
  69198. xhr.addEventListener("load", function () {
  69199. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69200. try {
  69201. var manifestFile = JSON.parse(xhr.response);
  69202. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69203. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69204. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69205. _this.manifestVersionFound = manifestFile.version;
  69206. }
  69207. if (_this.callbackManifestChecked) {
  69208. _this.callbackManifestChecked(true);
  69209. }
  69210. }
  69211. catch (ex) {
  69212. noManifestFile();
  69213. }
  69214. }
  69215. else {
  69216. noManifestFile();
  69217. }
  69218. }, false);
  69219. xhr.addEventListener("error", function (event) {
  69220. if (timeStampUsed) {
  69221. timeStampUsed = false;
  69222. // Let's retry without the timeStamp
  69223. // It could fail when coupled with HTML5 Offline API
  69224. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69225. xhr.open("GET", retryManifestURL, true);
  69226. xhr.send();
  69227. }
  69228. else {
  69229. noManifestFile();
  69230. }
  69231. }, false);
  69232. try {
  69233. xhr.send();
  69234. }
  69235. catch (ex) {
  69236. BABYLON.Tools.Error("Error on XHR send request.");
  69237. this.callbackManifestChecked(false);
  69238. }
  69239. };
  69240. /**
  69241. * Open the database and make it available
  69242. * @param successCallback defines the callback to call on success
  69243. * @param errorCallback defines the callback to call on error
  69244. */
  69245. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69246. var _this = this;
  69247. var handleError = function () {
  69248. _this.isSupported = false;
  69249. if (errorCallback)
  69250. errorCallback();
  69251. };
  69252. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69253. // Your browser doesn't support IndexedDB
  69254. this.isSupported = false;
  69255. if (errorCallback)
  69256. errorCallback();
  69257. }
  69258. else {
  69259. // If the DB hasn't been opened or created yet
  69260. if (!this.db) {
  69261. this.hasReachedQuota = false;
  69262. this.isSupported = true;
  69263. var request = this.idbFactory.open("babylonjs", 1);
  69264. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69265. request.onerror = function (event) {
  69266. handleError();
  69267. };
  69268. // executes when a version change transaction cannot complete due to other active transactions
  69269. request.onblocked = function (event) {
  69270. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69271. handleError();
  69272. };
  69273. // DB has been opened successfully
  69274. request.onsuccess = function (event) {
  69275. _this.db = request.result;
  69276. successCallback();
  69277. };
  69278. // Initialization of the DB. Creating Scenes & Textures stores
  69279. request.onupgradeneeded = function (event) {
  69280. _this.db = (event.target).result;
  69281. if (_this.db) {
  69282. try {
  69283. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69284. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69285. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69286. }
  69287. catch (ex) {
  69288. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69289. handleError();
  69290. }
  69291. }
  69292. };
  69293. }
  69294. // DB has already been created and opened
  69295. else {
  69296. if (successCallback)
  69297. successCallback();
  69298. }
  69299. }
  69300. };
  69301. /**
  69302. * Loads an image from the database
  69303. * @param url defines the url to load from
  69304. * @param image defines the target DOM image
  69305. */
  69306. Database.prototype.loadImageFromDB = function (url, image) {
  69307. var _this = this;
  69308. var completeURL = Database._ReturnFullUrlLocation(url);
  69309. var saveAndLoadImage = function () {
  69310. if (!_this.hasReachedQuota && _this.db !== null) {
  69311. // the texture is not yet in the DB, let's try to save it
  69312. _this._saveImageIntoDBAsync(completeURL, image);
  69313. }
  69314. // If the texture is not in the DB and we've reached the DB quota limit
  69315. // let's load it directly from the web
  69316. else {
  69317. image.src = url;
  69318. }
  69319. };
  69320. if (!this.mustUpdateRessources) {
  69321. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69322. }
  69323. // First time we're download the images or update requested in the manifest file by a version change
  69324. else {
  69325. saveAndLoadImage();
  69326. }
  69327. };
  69328. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69329. if (this.isSupported && this.db !== null) {
  69330. var texture;
  69331. var transaction = this.db.transaction(["textures"]);
  69332. transaction.onabort = function (event) {
  69333. image.src = url;
  69334. };
  69335. transaction.oncomplete = function (event) {
  69336. var blobTextureURL;
  69337. if (texture) {
  69338. var URL = window.URL || window.webkitURL;
  69339. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69340. image.onerror = function () {
  69341. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69342. image.src = url;
  69343. };
  69344. image.src = blobTextureURL;
  69345. }
  69346. else {
  69347. notInDBCallback();
  69348. }
  69349. };
  69350. var getRequest = transaction.objectStore("textures").get(url);
  69351. getRequest.onsuccess = function (event) {
  69352. texture = (event.target).result;
  69353. };
  69354. getRequest.onerror = function (event) {
  69355. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69356. image.src = url;
  69357. };
  69358. }
  69359. else {
  69360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69361. image.src = url;
  69362. }
  69363. };
  69364. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69365. var _this = this;
  69366. if (this.isSupported) {
  69367. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69368. var generateBlobUrl = function () {
  69369. var blobTextureURL;
  69370. if (blob) {
  69371. var URL = window.URL || window.webkitURL;
  69372. try {
  69373. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69374. }
  69375. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69376. catch (ex) {
  69377. blobTextureURL = URL.createObjectURL(blob);
  69378. }
  69379. }
  69380. if (blobTextureURL) {
  69381. image.src = blobTextureURL;
  69382. }
  69383. };
  69384. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69385. var xhr = new XMLHttpRequest(), blob;
  69386. xhr.open("GET", url, true);
  69387. xhr.responseType = "blob";
  69388. xhr.addEventListener("load", function () {
  69389. if (xhr.status === 200 && _this.db) {
  69390. // Blob as response (XHR2)
  69391. blob = xhr.response;
  69392. var transaction = _this.db.transaction(["textures"], "readwrite");
  69393. // the transaction could abort because of a QuotaExceededError error
  69394. transaction.onabort = function (event) {
  69395. try {
  69396. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69397. var srcElement = (event.srcElement || event.target);
  69398. var error = srcElement.error;
  69399. if (error && error.name === "QuotaExceededError") {
  69400. _this.hasReachedQuota = true;
  69401. }
  69402. }
  69403. catch (ex) { }
  69404. generateBlobUrl();
  69405. };
  69406. transaction.oncomplete = function (event) {
  69407. generateBlobUrl();
  69408. };
  69409. var newTexture = { textureUrl: url, data: blob };
  69410. try {
  69411. // Put the blob into the dabase
  69412. var addRequest = transaction.objectStore("textures").put(newTexture);
  69413. addRequest.onsuccess = function (event) {
  69414. };
  69415. addRequest.onerror = function (event) {
  69416. generateBlobUrl();
  69417. };
  69418. }
  69419. catch (ex) {
  69420. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69421. if (ex.code === 25) {
  69422. Database.IsUASupportingBlobStorage = false;
  69423. }
  69424. image.src = url;
  69425. }
  69426. }
  69427. else {
  69428. image.src = url;
  69429. }
  69430. }, false);
  69431. xhr.addEventListener("error", function (event) {
  69432. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69433. image.src = url;
  69434. }, false);
  69435. xhr.send();
  69436. }
  69437. else {
  69438. image.src = url;
  69439. }
  69440. }
  69441. else {
  69442. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69443. image.src = url;
  69444. }
  69445. };
  69446. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69447. var _this = this;
  69448. var updateVersion = function () {
  69449. // the version is not yet in the DB or we need to update it
  69450. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69451. };
  69452. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69453. };
  69454. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69455. var _this = this;
  69456. if (this.isSupported && this.db) {
  69457. var version;
  69458. try {
  69459. var transaction = this.db.transaction(["versions"]);
  69460. transaction.oncomplete = function (event) {
  69461. if (version) {
  69462. // If the version in the JSON file is different from the version in DB
  69463. if (_this.manifestVersionFound !== version.data) {
  69464. _this.mustUpdateRessources = true;
  69465. updateInDBCallback();
  69466. }
  69467. else {
  69468. callback(version.data);
  69469. }
  69470. }
  69471. // version was not found in DB
  69472. else {
  69473. _this.mustUpdateRessources = true;
  69474. updateInDBCallback();
  69475. }
  69476. };
  69477. transaction.onabort = function (event) {
  69478. callback(-1);
  69479. };
  69480. var getRequest = transaction.objectStore("versions").get(url);
  69481. getRequest.onsuccess = function (event) {
  69482. version = (event.target).result;
  69483. };
  69484. getRequest.onerror = function (event) {
  69485. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69486. callback(-1);
  69487. };
  69488. }
  69489. catch (ex) {
  69490. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69491. callback(-1);
  69492. }
  69493. }
  69494. else {
  69495. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69496. callback(-1);
  69497. }
  69498. };
  69499. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69500. var _this = this;
  69501. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69502. try {
  69503. // Open a transaction to the database
  69504. var transaction = this.db.transaction(["versions"], "readwrite");
  69505. // the transaction could abort because of a QuotaExceededError error
  69506. transaction.onabort = function (event) {
  69507. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69508. var error = event.srcElement['error'];
  69509. if (error && error.name === "QuotaExceededError") {
  69510. _this.hasReachedQuota = true;
  69511. }
  69512. }
  69513. catch (ex) { }
  69514. callback(-1);
  69515. };
  69516. transaction.oncomplete = function (event) {
  69517. callback(_this.manifestVersionFound);
  69518. };
  69519. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69520. // Put the scene into the database
  69521. var addRequest = transaction.objectStore("versions").put(newVersion);
  69522. addRequest.onsuccess = function (event) {
  69523. };
  69524. addRequest.onerror = function (event) {
  69525. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69526. };
  69527. }
  69528. catch (ex) {
  69529. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69530. callback(-1);
  69531. }
  69532. }
  69533. else {
  69534. callback(-1);
  69535. }
  69536. };
  69537. /**
  69538. * Loads a file from database
  69539. * @param url defines the URL to load from
  69540. * @param sceneLoaded defines a callback to call on success
  69541. * @param progressCallBack defines a callback to call when progress changed
  69542. * @param errorCallback defines a callback to call on error
  69543. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69544. */
  69545. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69546. var _this = this;
  69547. var completeUrl = Database._ReturnFullUrlLocation(url);
  69548. var saveAndLoadFile = function () {
  69549. // the scene is not yet in the DB, let's try to save it
  69550. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69551. };
  69552. this._checkVersionFromDB(completeUrl, function (version) {
  69553. if (version !== -1) {
  69554. if (!_this.mustUpdateRessources) {
  69555. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69556. }
  69557. else {
  69558. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69559. }
  69560. }
  69561. else {
  69562. if (errorCallback) {
  69563. errorCallback();
  69564. }
  69565. }
  69566. });
  69567. };
  69568. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69569. if (this.isSupported && this.db) {
  69570. var targetStore;
  69571. if (url.indexOf(".babylon") !== -1) {
  69572. targetStore = "scenes";
  69573. }
  69574. else {
  69575. targetStore = "textures";
  69576. }
  69577. var file;
  69578. var transaction = this.db.transaction([targetStore]);
  69579. transaction.oncomplete = function (event) {
  69580. if (file) {
  69581. callback(file.data);
  69582. }
  69583. // file was not found in DB
  69584. else {
  69585. notInDBCallback();
  69586. }
  69587. };
  69588. transaction.onabort = function (event) {
  69589. notInDBCallback();
  69590. };
  69591. var getRequest = transaction.objectStore(targetStore).get(url);
  69592. getRequest.onsuccess = function (event) {
  69593. file = (event.target).result;
  69594. };
  69595. getRequest.onerror = function (event) {
  69596. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69597. notInDBCallback();
  69598. };
  69599. }
  69600. else {
  69601. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69602. callback();
  69603. }
  69604. };
  69605. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69606. var _this = this;
  69607. if (this.isSupported) {
  69608. var targetStore;
  69609. if (url.indexOf(".babylon") !== -1) {
  69610. targetStore = "scenes";
  69611. }
  69612. else {
  69613. targetStore = "textures";
  69614. }
  69615. // Create XHR
  69616. var xhr = new XMLHttpRequest();
  69617. var fileData;
  69618. xhr.open("GET", url, true);
  69619. if (useArrayBuffer) {
  69620. xhr.responseType = "arraybuffer";
  69621. }
  69622. if (progressCallback) {
  69623. xhr.onprogress = progressCallback;
  69624. }
  69625. xhr.addEventListener("load", function () {
  69626. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69627. // Blob as response (XHR2)
  69628. //fileData = xhr.responseText;
  69629. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69630. if (!_this.hasReachedQuota && _this.db) {
  69631. // Open a transaction to the database
  69632. var transaction = _this.db.transaction([targetStore], "readwrite");
  69633. // the transaction could abort because of a QuotaExceededError error
  69634. transaction.onabort = function (event) {
  69635. try {
  69636. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69637. var error = event.srcElement['error'];
  69638. if (error && error.name === "QuotaExceededError") {
  69639. _this.hasReachedQuota = true;
  69640. }
  69641. }
  69642. catch (ex) { }
  69643. callback(fileData);
  69644. };
  69645. transaction.oncomplete = function (event) {
  69646. callback(fileData);
  69647. };
  69648. var newFile;
  69649. if (targetStore === "scenes") {
  69650. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69651. }
  69652. else {
  69653. newFile = { textureUrl: url, data: fileData };
  69654. }
  69655. try {
  69656. // Put the scene into the database
  69657. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69658. addRequest.onsuccess = function (event) {
  69659. };
  69660. addRequest.onerror = function (event) {
  69661. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69662. };
  69663. }
  69664. catch (ex) {
  69665. callback(fileData);
  69666. }
  69667. }
  69668. else {
  69669. callback(fileData);
  69670. }
  69671. }
  69672. else {
  69673. callback();
  69674. }
  69675. }, false);
  69676. xhr.addEventListener("error", function (event) {
  69677. BABYLON.Tools.Error("error on XHR request.");
  69678. callback();
  69679. }, false);
  69680. xhr.send();
  69681. }
  69682. else {
  69683. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69684. callback();
  69685. }
  69686. };
  69687. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69688. Database.IsUASupportingBlobStorage = true;
  69689. /** Gets a boolean indicating if Database storate is enabled */
  69690. Database.IDBStorageEnabled = true;
  69691. Database._ParseURL = function (url) {
  69692. var a = document.createElement('a');
  69693. a.href = url;
  69694. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69695. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69696. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69697. return absLocation;
  69698. };
  69699. Database._ReturnFullUrlLocation = function (url) {
  69700. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69701. return (Database._ParseURL(window.location.href) + url);
  69702. }
  69703. else {
  69704. return url;
  69705. }
  69706. };
  69707. return Database;
  69708. }());
  69709. BABYLON.Database = Database;
  69710. })(BABYLON || (BABYLON = {}));
  69711. //# sourceMappingURL=babylon.database.js.map
  69712. var BABYLON;
  69713. (function (BABYLON) {
  69714. var FresnelParameters = /** @class */ (function () {
  69715. function FresnelParameters() {
  69716. this._isEnabled = true;
  69717. this.leftColor = BABYLON.Color3.White();
  69718. this.rightColor = BABYLON.Color3.Black();
  69719. this.bias = 0;
  69720. this.power = 1;
  69721. }
  69722. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69723. get: function () {
  69724. return this._isEnabled;
  69725. },
  69726. set: function (value) {
  69727. if (this._isEnabled === value) {
  69728. return;
  69729. }
  69730. this._isEnabled = value;
  69731. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69732. },
  69733. enumerable: true,
  69734. configurable: true
  69735. });
  69736. FresnelParameters.prototype.clone = function () {
  69737. var newFresnelParameters = new FresnelParameters();
  69738. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69739. return newFresnelParameters;
  69740. };
  69741. FresnelParameters.prototype.serialize = function () {
  69742. var serializationObject = {};
  69743. serializationObject.isEnabled = this.isEnabled;
  69744. serializationObject.leftColor = this.leftColor.asArray();
  69745. serializationObject.rightColor = this.rightColor.asArray();
  69746. serializationObject.bias = this.bias;
  69747. serializationObject.power = this.power;
  69748. return serializationObject;
  69749. };
  69750. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69751. var fresnelParameters = new FresnelParameters();
  69752. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69753. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69754. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69755. fresnelParameters.bias = parsedFresnelParameters.bias;
  69756. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69757. return fresnelParameters;
  69758. };
  69759. return FresnelParameters;
  69760. }());
  69761. BABYLON.FresnelParameters = FresnelParameters;
  69762. })(BABYLON || (BABYLON = {}));
  69763. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69764. var BABYLON;
  69765. (function (BABYLON) {
  69766. var MultiMaterial = /** @class */ (function (_super) {
  69767. __extends(MultiMaterial, _super);
  69768. function MultiMaterial(name, scene) {
  69769. var _this = _super.call(this, name, scene, true) || this;
  69770. scene.multiMaterials.push(_this);
  69771. _this.subMaterials = new Array();
  69772. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69773. return _this;
  69774. }
  69775. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69776. get: function () {
  69777. return this._subMaterials;
  69778. },
  69779. set: function (value) {
  69780. this._subMaterials = value;
  69781. this._hookArray(value);
  69782. },
  69783. enumerable: true,
  69784. configurable: true
  69785. });
  69786. MultiMaterial.prototype._hookArray = function (array) {
  69787. var _this = this;
  69788. var oldPush = array.push;
  69789. array.push = function () {
  69790. var items = [];
  69791. for (var _i = 0; _i < arguments.length; _i++) {
  69792. items[_i] = arguments[_i];
  69793. }
  69794. var result = oldPush.apply(array, items);
  69795. _this._markAllSubMeshesAsTexturesDirty();
  69796. return result;
  69797. };
  69798. var oldSplice = array.splice;
  69799. array.splice = function (index, deleteCount) {
  69800. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69801. _this._markAllSubMeshesAsTexturesDirty();
  69802. return deleted;
  69803. };
  69804. };
  69805. // Properties
  69806. MultiMaterial.prototype.getSubMaterial = function (index) {
  69807. if (index < 0 || index >= this.subMaterials.length) {
  69808. return this.getScene().defaultMaterial;
  69809. }
  69810. return this.subMaterials[index];
  69811. };
  69812. MultiMaterial.prototype.getActiveTextures = function () {
  69813. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69814. if (subMaterial) {
  69815. return subMaterial.getActiveTextures();
  69816. }
  69817. else {
  69818. return [];
  69819. }
  69820. }));
  69821. var _a;
  69822. };
  69823. // Methods
  69824. MultiMaterial.prototype.getClassName = function () {
  69825. return "MultiMaterial";
  69826. };
  69827. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69828. for (var index = 0; index < this.subMaterials.length; index++) {
  69829. var subMaterial = this.subMaterials[index];
  69830. if (subMaterial) {
  69831. if (subMaterial.storeEffectOnSubMeshes) {
  69832. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69833. return false;
  69834. }
  69835. continue;
  69836. }
  69837. if (!subMaterial.isReady(mesh)) {
  69838. return false;
  69839. }
  69840. }
  69841. }
  69842. return true;
  69843. };
  69844. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69845. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69846. for (var index = 0; index < this.subMaterials.length; index++) {
  69847. var subMaterial = null;
  69848. var current = this.subMaterials[index];
  69849. if (cloneChildren && current) {
  69850. subMaterial = current.clone(name + "-" + current.name);
  69851. }
  69852. else {
  69853. subMaterial = this.subMaterials[index];
  69854. }
  69855. newMultiMaterial.subMaterials.push(subMaterial);
  69856. }
  69857. return newMultiMaterial;
  69858. };
  69859. MultiMaterial.prototype.serialize = function () {
  69860. var serializationObject = {};
  69861. serializationObject.name = this.name;
  69862. serializationObject.id = this.id;
  69863. if (BABYLON.Tags) {
  69864. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69865. }
  69866. serializationObject.materials = [];
  69867. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69868. var subMat = this.subMaterials[matIndex];
  69869. if (subMat) {
  69870. serializationObject.materials.push(subMat.id);
  69871. }
  69872. else {
  69873. serializationObject.materials.push(null);
  69874. }
  69875. }
  69876. return serializationObject;
  69877. };
  69878. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69879. var scene = this.getScene();
  69880. if (!scene) {
  69881. return;
  69882. }
  69883. var index = scene.multiMaterials.indexOf(this);
  69884. if (index >= 0) {
  69885. scene.multiMaterials.splice(index, 1);
  69886. }
  69887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69888. };
  69889. return MultiMaterial;
  69890. }(BABYLON.Material));
  69891. BABYLON.MultiMaterial = MultiMaterial;
  69892. })(BABYLON || (BABYLON = {}));
  69893. //# sourceMappingURL=babylon.multiMaterial.js.map
  69894. var BABYLON;
  69895. (function (BABYLON) {
  69896. var FreeCameraTouchInput = /** @class */ (function () {
  69897. function FreeCameraTouchInput() {
  69898. this._offsetX = null;
  69899. this._offsetY = null;
  69900. this._pointerPressed = new Array();
  69901. this.touchAngularSensibility = 200000.0;
  69902. this.touchMoveSensibility = 250.0;
  69903. }
  69904. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69905. var _this = this;
  69906. var previousPosition = null;
  69907. if (this._pointerInput === undefined) {
  69908. this._onLostFocus = function (evt) {
  69909. _this._offsetX = null;
  69910. _this._offsetY = null;
  69911. };
  69912. this._pointerInput = function (p, s) {
  69913. var evt = p.event;
  69914. if (evt.pointerType === "mouse") {
  69915. return;
  69916. }
  69917. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69918. if (!noPreventDefault) {
  69919. evt.preventDefault();
  69920. }
  69921. _this._pointerPressed.push(evt.pointerId);
  69922. if (_this._pointerPressed.length !== 1) {
  69923. return;
  69924. }
  69925. previousPosition = {
  69926. x: evt.clientX,
  69927. y: evt.clientY
  69928. };
  69929. }
  69930. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69931. if (!noPreventDefault) {
  69932. evt.preventDefault();
  69933. }
  69934. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69935. if (index === -1) {
  69936. return;
  69937. }
  69938. _this._pointerPressed.splice(index, 1);
  69939. if (index != 0) {
  69940. return;
  69941. }
  69942. previousPosition = null;
  69943. _this._offsetX = null;
  69944. _this._offsetY = null;
  69945. }
  69946. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69947. if (!noPreventDefault) {
  69948. evt.preventDefault();
  69949. }
  69950. if (!previousPosition) {
  69951. return;
  69952. }
  69953. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69954. if (index != 0) {
  69955. return;
  69956. }
  69957. _this._offsetX = evt.clientX - previousPosition.x;
  69958. _this._offsetY = -(evt.clientY - previousPosition.y);
  69959. }
  69960. };
  69961. }
  69962. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69963. if (this._onLostFocus) {
  69964. element.addEventListener("blur", this._onLostFocus);
  69965. }
  69966. };
  69967. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69968. if (this._pointerInput && element) {
  69969. if (this._observer) {
  69970. this.camera.getScene().onPointerObservable.remove(this._observer);
  69971. this._observer = null;
  69972. }
  69973. if (this._onLostFocus) {
  69974. element.removeEventListener("blur", this._onLostFocus);
  69975. this._onLostFocus = null;
  69976. }
  69977. this._pointerPressed = [];
  69978. this._offsetX = null;
  69979. this._offsetY = null;
  69980. }
  69981. };
  69982. FreeCameraTouchInput.prototype.checkInputs = function () {
  69983. if (this._offsetX && this._offsetY) {
  69984. var camera = this.camera;
  69985. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69986. if (this._pointerPressed.length > 1) {
  69987. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69988. }
  69989. else {
  69990. var speed = camera._computeLocalCameraSpeed();
  69991. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69992. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69993. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69994. }
  69995. }
  69996. };
  69997. FreeCameraTouchInput.prototype.getClassName = function () {
  69998. return "FreeCameraTouchInput";
  69999. };
  70000. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70001. return "touch";
  70002. };
  70003. __decorate([
  70004. BABYLON.serialize()
  70005. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70006. __decorate([
  70007. BABYLON.serialize()
  70008. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70009. return FreeCameraTouchInput;
  70010. }());
  70011. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70012. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70013. })(BABYLON || (BABYLON = {}));
  70014. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70015. var BABYLON;
  70016. (function (BABYLON) {
  70017. // We're mainly based on the logic defined into the FreeCamera code
  70018. var TouchCamera = /** @class */ (function (_super) {
  70019. __extends(TouchCamera, _super);
  70020. //-- end properties for backward compatibility for inputs
  70021. function TouchCamera(name, position, scene) {
  70022. var _this = _super.call(this, name, position, scene) || this;
  70023. _this.inputs.addTouch();
  70024. _this._setupInputs();
  70025. return _this;
  70026. }
  70027. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70028. //-- Begin properties for backward compatibility for inputs
  70029. get: function () {
  70030. var touch = this.inputs.attached["touch"];
  70031. if (touch)
  70032. return touch.touchAngularSensibility;
  70033. return 0;
  70034. },
  70035. set: function (value) {
  70036. var touch = this.inputs.attached["touch"];
  70037. if (touch)
  70038. touch.touchAngularSensibility = value;
  70039. },
  70040. enumerable: true,
  70041. configurable: true
  70042. });
  70043. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70044. get: function () {
  70045. var touch = this.inputs.attached["touch"];
  70046. if (touch)
  70047. return touch.touchMoveSensibility;
  70048. return 0;
  70049. },
  70050. set: function (value) {
  70051. var touch = this.inputs.attached["touch"];
  70052. if (touch)
  70053. touch.touchMoveSensibility = value;
  70054. },
  70055. enumerable: true,
  70056. configurable: true
  70057. });
  70058. TouchCamera.prototype.getClassName = function () {
  70059. return "TouchCamera";
  70060. };
  70061. TouchCamera.prototype._setupInputs = function () {
  70062. var mouse = this.inputs.attached["mouse"];
  70063. if (mouse) {
  70064. mouse.touchEnabled = false;
  70065. }
  70066. };
  70067. return TouchCamera;
  70068. }(BABYLON.FreeCamera));
  70069. BABYLON.TouchCamera = TouchCamera;
  70070. })(BABYLON || (BABYLON = {}));
  70071. //# sourceMappingURL=babylon.touchCamera.js.map
  70072. var BABYLON;
  70073. (function (BABYLON) {
  70074. var ProceduralTexture = /** @class */ (function (_super) {
  70075. __extends(ProceduralTexture, _super);
  70076. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70077. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70078. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70079. if (isCube === void 0) { isCube = false; }
  70080. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70081. _this.isCube = isCube;
  70082. _this.isEnabled = true;
  70083. _this._currentRefreshId = -1;
  70084. _this._refreshRate = 1;
  70085. _this._vertexBuffers = {};
  70086. _this._uniforms = new Array();
  70087. _this._samplers = new Array();
  70088. _this._textures = {};
  70089. _this._floats = {};
  70090. _this._floatsArrays = {};
  70091. _this._colors3 = {};
  70092. _this._colors4 = {};
  70093. _this._vectors2 = {};
  70094. _this._vectors3 = {};
  70095. _this._matrices = {};
  70096. _this._fallbackTextureUsed = false;
  70097. scene.proceduralTextures.push(_this);
  70098. _this._engine = scene.getEngine();
  70099. _this.name = name;
  70100. _this.isRenderTarget = true;
  70101. _this._size = size;
  70102. _this._generateMipMaps = generateMipMaps;
  70103. _this.setFragment(fragment);
  70104. _this._fallbackTexture = fallbackTexture;
  70105. if (isCube) {
  70106. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70107. _this.setFloat("face", 0);
  70108. }
  70109. else {
  70110. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70111. }
  70112. // VBO
  70113. var vertices = [];
  70114. vertices.push(1, 1);
  70115. vertices.push(-1, 1);
  70116. vertices.push(-1, -1);
  70117. vertices.push(1, -1);
  70118. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70119. _this._createIndexBuffer();
  70120. return _this;
  70121. }
  70122. ProceduralTexture.prototype._createIndexBuffer = function () {
  70123. var engine = this._engine;
  70124. // Indices
  70125. var indices = [];
  70126. indices.push(0);
  70127. indices.push(1);
  70128. indices.push(2);
  70129. indices.push(0);
  70130. indices.push(2);
  70131. indices.push(3);
  70132. this._indexBuffer = engine.createIndexBuffer(indices);
  70133. };
  70134. ProceduralTexture.prototype._rebuild = function () {
  70135. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70136. if (vb) {
  70137. vb._rebuild();
  70138. }
  70139. this._createIndexBuffer();
  70140. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70141. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70142. }
  70143. };
  70144. ProceduralTexture.prototype.reset = function () {
  70145. if (this._effect === undefined) {
  70146. return;
  70147. }
  70148. var engine = this._engine;
  70149. engine._releaseEffect(this._effect);
  70150. };
  70151. ProceduralTexture.prototype.isReady = function () {
  70152. var _this = this;
  70153. var engine = this._engine;
  70154. var shaders;
  70155. if (!this._fragment) {
  70156. return false;
  70157. }
  70158. if (this._fallbackTextureUsed) {
  70159. return true;
  70160. }
  70161. if (this._fragment.fragmentElement !== undefined) {
  70162. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70163. }
  70164. else {
  70165. shaders = { vertex: "procedural", fragment: this._fragment };
  70166. }
  70167. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70168. _this.releaseInternalTexture();
  70169. if (_this._fallbackTexture) {
  70170. _this._texture = _this._fallbackTexture._texture;
  70171. if (_this._texture) {
  70172. _this._texture.incrementReferences();
  70173. }
  70174. }
  70175. _this._fallbackTextureUsed = true;
  70176. });
  70177. return this._effect.isReady();
  70178. };
  70179. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70180. this._currentRefreshId = -1;
  70181. };
  70182. ProceduralTexture.prototype.setFragment = function (fragment) {
  70183. this._fragment = fragment;
  70184. };
  70185. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70186. get: function () {
  70187. return this._refreshRate;
  70188. },
  70189. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70190. set: function (value) {
  70191. this._refreshRate = value;
  70192. this.resetRefreshCounter();
  70193. },
  70194. enumerable: true,
  70195. configurable: true
  70196. });
  70197. ProceduralTexture.prototype._shouldRender = function () {
  70198. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70199. return false;
  70200. }
  70201. if (this._fallbackTextureUsed) {
  70202. return false;
  70203. }
  70204. if (this._currentRefreshId === -1) { // At least render once
  70205. this._currentRefreshId = 1;
  70206. return true;
  70207. }
  70208. if (this.refreshRate === this._currentRefreshId) {
  70209. this._currentRefreshId = 1;
  70210. return true;
  70211. }
  70212. this._currentRefreshId++;
  70213. return false;
  70214. };
  70215. ProceduralTexture.prototype.getRenderSize = function () {
  70216. return this._size;
  70217. };
  70218. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70219. if (this._fallbackTextureUsed) {
  70220. return;
  70221. }
  70222. this.releaseInternalTexture();
  70223. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70224. // Update properties
  70225. this._size = size;
  70226. this._generateMipMaps = generateMipMaps;
  70227. };
  70228. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70229. if (this._uniforms.indexOf(uniformName) === -1) {
  70230. this._uniforms.push(uniformName);
  70231. }
  70232. };
  70233. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70234. if (this._samplers.indexOf(name) === -1) {
  70235. this._samplers.push(name);
  70236. }
  70237. this._textures[name] = texture;
  70238. return this;
  70239. };
  70240. ProceduralTexture.prototype.setFloat = function (name, value) {
  70241. this._checkUniform(name);
  70242. this._floats[name] = value;
  70243. return this;
  70244. };
  70245. ProceduralTexture.prototype.setFloats = function (name, value) {
  70246. this._checkUniform(name);
  70247. this._floatsArrays[name] = value;
  70248. return this;
  70249. };
  70250. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70251. this._checkUniform(name);
  70252. this._colors3[name] = value;
  70253. return this;
  70254. };
  70255. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70256. this._checkUniform(name);
  70257. this._colors4[name] = value;
  70258. return this;
  70259. };
  70260. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70261. this._checkUniform(name);
  70262. this._vectors2[name] = value;
  70263. return this;
  70264. };
  70265. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70266. this._checkUniform(name);
  70267. this._vectors3[name] = value;
  70268. return this;
  70269. };
  70270. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70271. this._checkUniform(name);
  70272. this._matrices[name] = value;
  70273. return this;
  70274. };
  70275. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70276. var scene = this.getScene();
  70277. if (!scene) {
  70278. return;
  70279. }
  70280. var engine = this._engine;
  70281. // Render
  70282. engine.enableEffect(this._effect);
  70283. engine.setState(false);
  70284. // Texture
  70285. for (var name in this._textures) {
  70286. this._effect.setTexture(name, this._textures[name]);
  70287. }
  70288. // Float
  70289. for (name in this._floats) {
  70290. this._effect.setFloat(name, this._floats[name]);
  70291. }
  70292. // Floats
  70293. for (name in this._floatsArrays) {
  70294. this._effect.setArray(name, this._floatsArrays[name]);
  70295. }
  70296. // Color3
  70297. for (name in this._colors3) {
  70298. this._effect.setColor3(name, this._colors3[name]);
  70299. }
  70300. // Color4
  70301. for (name in this._colors4) {
  70302. var color = this._colors4[name];
  70303. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70304. }
  70305. // Vector2
  70306. for (name in this._vectors2) {
  70307. this._effect.setVector2(name, this._vectors2[name]);
  70308. }
  70309. // Vector3
  70310. for (name in this._vectors3) {
  70311. this._effect.setVector3(name, this._vectors3[name]);
  70312. }
  70313. // Matrix
  70314. for (name in this._matrices) {
  70315. this._effect.setMatrix(name, this._matrices[name]);
  70316. }
  70317. if (!this._texture) {
  70318. return;
  70319. }
  70320. if (this.isCube) {
  70321. for (var face = 0; face < 6; face++) {
  70322. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70323. // VBOs
  70324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70325. this._effect.setFloat("face", face);
  70326. // Clear
  70327. engine.clear(scene.clearColor, true, true, true);
  70328. // Draw order
  70329. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70330. // Mipmaps
  70331. if (face === 5) {
  70332. engine.generateMipMapsForCubemap(this._texture);
  70333. }
  70334. }
  70335. }
  70336. else {
  70337. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70338. // VBOs
  70339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70340. // Clear
  70341. engine.clear(scene.clearColor, true, true, true);
  70342. // Draw order
  70343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70344. }
  70345. // Unbind
  70346. engine.unBindFramebuffer(this._texture, this.isCube);
  70347. if (this.onGenerated) {
  70348. this.onGenerated();
  70349. }
  70350. };
  70351. ProceduralTexture.prototype.clone = function () {
  70352. var textureSize = this.getSize();
  70353. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70354. // Base texture
  70355. newTexture.hasAlpha = this.hasAlpha;
  70356. newTexture.level = this.level;
  70357. // RenderTarget Texture
  70358. newTexture.coordinatesMode = this.coordinatesMode;
  70359. return newTexture;
  70360. };
  70361. ProceduralTexture.prototype.dispose = function () {
  70362. var scene = this.getScene();
  70363. if (!scene) {
  70364. return;
  70365. }
  70366. var index = scene.proceduralTextures.indexOf(this);
  70367. if (index >= 0) {
  70368. scene.proceduralTextures.splice(index, 1);
  70369. }
  70370. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70371. if (vertexBuffer) {
  70372. vertexBuffer.dispose();
  70373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70374. }
  70375. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70376. this._indexBuffer = null;
  70377. }
  70378. _super.prototype.dispose.call(this);
  70379. };
  70380. __decorate([
  70381. BABYLON.serialize()
  70382. ], ProceduralTexture.prototype, "_size", void 0);
  70383. __decorate([
  70384. BABYLON.serialize()
  70385. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70386. __decorate([
  70387. BABYLON.serialize()
  70388. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70389. __decorate([
  70390. BABYLON.serialize()
  70391. ], ProceduralTexture.prototype, "refreshRate", null);
  70392. return ProceduralTexture;
  70393. }(BABYLON.Texture));
  70394. BABYLON.ProceduralTexture = ProceduralTexture;
  70395. })(BABYLON || (BABYLON = {}));
  70396. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70397. var BABYLON;
  70398. (function (BABYLON) {
  70399. var CustomProceduralTexture = /** @class */ (function (_super) {
  70400. __extends(CustomProceduralTexture, _super);
  70401. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70402. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70403. _this._animate = true;
  70404. _this._time = 0;
  70405. _this._texturePath = texturePath;
  70406. //Try to load json
  70407. _this.loadJson(texturePath);
  70408. _this.refreshRate = 1;
  70409. return _this;
  70410. }
  70411. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70412. var _this = this;
  70413. var noConfigFile = function () {
  70414. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70415. try {
  70416. _this.setFragment(_this._texturePath);
  70417. }
  70418. catch (ex) {
  70419. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70420. }
  70421. };
  70422. var configFileUrl = jsonUrl + "/config.json";
  70423. var xhr = new XMLHttpRequest();
  70424. xhr.open("GET", configFileUrl, true);
  70425. xhr.addEventListener("load", function () {
  70426. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70427. try {
  70428. _this._config = JSON.parse(xhr.response);
  70429. _this.updateShaderUniforms();
  70430. _this.updateTextures();
  70431. _this.setFragment(_this._texturePath + "/custom");
  70432. _this._animate = _this._config.animate;
  70433. _this.refreshRate = _this._config.refreshrate;
  70434. }
  70435. catch (ex) {
  70436. noConfigFile();
  70437. }
  70438. }
  70439. else {
  70440. noConfigFile();
  70441. }
  70442. }, false);
  70443. xhr.addEventListener("error", function () {
  70444. noConfigFile();
  70445. }, false);
  70446. try {
  70447. xhr.send();
  70448. }
  70449. catch (ex) {
  70450. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70451. }
  70452. };
  70453. CustomProceduralTexture.prototype.isReady = function () {
  70454. if (!_super.prototype.isReady.call(this)) {
  70455. return false;
  70456. }
  70457. for (var name in this._textures) {
  70458. var texture = this._textures[name];
  70459. if (!texture.isReady()) {
  70460. return false;
  70461. }
  70462. }
  70463. return true;
  70464. };
  70465. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70466. var scene = this.getScene();
  70467. if (this._animate && scene) {
  70468. this._time += scene.getAnimationRatio() * 0.03;
  70469. this.updateShaderUniforms();
  70470. }
  70471. _super.prototype.render.call(this, useCameraPostProcess);
  70472. };
  70473. CustomProceduralTexture.prototype.updateTextures = function () {
  70474. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70475. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70476. }
  70477. };
  70478. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70479. if (this._config) {
  70480. for (var j = 0; j < this._config.uniforms.length; j++) {
  70481. var uniform = this._config.uniforms[j];
  70482. switch (uniform.type) {
  70483. case "float":
  70484. this.setFloat(uniform.name, uniform.value);
  70485. break;
  70486. case "color3":
  70487. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70488. break;
  70489. case "color4":
  70490. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70491. break;
  70492. case "vector2":
  70493. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70494. break;
  70495. case "vector3":
  70496. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70497. break;
  70498. }
  70499. }
  70500. }
  70501. this.setFloat("time", this._time);
  70502. };
  70503. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70504. get: function () {
  70505. return this._animate;
  70506. },
  70507. set: function (value) {
  70508. this._animate = value;
  70509. },
  70510. enumerable: true,
  70511. configurable: true
  70512. });
  70513. return CustomProceduralTexture;
  70514. }(BABYLON.ProceduralTexture));
  70515. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70516. })(BABYLON || (BABYLON = {}));
  70517. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70518. var BABYLON;
  70519. (function (BABYLON) {
  70520. var FreeCameraGamepadInput = /** @class */ (function () {
  70521. function FreeCameraGamepadInput() {
  70522. this.gamepadAngularSensibility = 200;
  70523. this.gamepadMoveSensibility = 40;
  70524. // private members
  70525. this._cameraTransform = BABYLON.Matrix.Identity();
  70526. this._deltaTransform = BABYLON.Vector3.Zero();
  70527. this._vector3 = BABYLON.Vector3.Zero();
  70528. this._vector2 = BABYLON.Vector2.Zero();
  70529. }
  70530. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70531. var _this = this;
  70532. var manager = this.camera.getScene().gamepadManager;
  70533. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70534. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70535. // prioritize XBOX gamepads.
  70536. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70537. _this.gamepad = gamepad;
  70538. }
  70539. }
  70540. });
  70541. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70542. if (_this.gamepad === gamepad) {
  70543. _this.gamepad = null;
  70544. }
  70545. });
  70546. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70547. };
  70548. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70549. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70550. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70551. this.gamepad = null;
  70552. };
  70553. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70554. if (this.gamepad && this.gamepad.leftStick) {
  70555. var camera = this.camera;
  70556. var LSValues = this.gamepad.leftStick;
  70557. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70558. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70559. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70560. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70561. var RSValues = this.gamepad.rightStick;
  70562. if (RSValues) {
  70563. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70564. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70565. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70566. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70567. }
  70568. else {
  70569. RSValues = { x: 0, y: 0 };
  70570. }
  70571. if (!camera.rotationQuaternion) {
  70572. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70573. }
  70574. else {
  70575. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70576. }
  70577. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70578. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70579. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70580. camera.cameraDirection.addInPlace(this._deltaTransform);
  70581. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70582. camera.cameraRotation.addInPlace(this._vector2);
  70583. }
  70584. };
  70585. FreeCameraGamepadInput.prototype.getClassName = function () {
  70586. return "FreeCameraGamepadInput";
  70587. };
  70588. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70589. return "gamepad";
  70590. };
  70591. __decorate([
  70592. BABYLON.serialize()
  70593. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70594. __decorate([
  70595. BABYLON.serialize()
  70596. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70597. return FreeCameraGamepadInput;
  70598. }());
  70599. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70600. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70601. })(BABYLON || (BABYLON = {}));
  70602. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70603. var BABYLON;
  70604. (function (BABYLON) {
  70605. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70606. function ArcRotateCameraGamepadInput() {
  70607. this.gamepadRotationSensibility = 80;
  70608. this.gamepadMoveSensibility = 40;
  70609. }
  70610. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70611. var _this = this;
  70612. var manager = this.camera.getScene().gamepadManager;
  70613. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70614. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70615. // prioritize XBOX gamepads.
  70616. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70617. _this.gamepad = gamepad;
  70618. }
  70619. }
  70620. });
  70621. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70622. if (_this.gamepad === gamepad) {
  70623. _this.gamepad = null;
  70624. }
  70625. });
  70626. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70627. };
  70628. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70629. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70630. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70631. this.gamepad = null;
  70632. };
  70633. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70634. if (this.gamepad) {
  70635. var camera = this.camera;
  70636. var RSValues = this.gamepad.rightStick;
  70637. if (RSValues) {
  70638. if (RSValues.x != 0) {
  70639. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70640. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70641. camera.inertialAlphaOffset += normalizedRX;
  70642. }
  70643. }
  70644. if (RSValues.y != 0) {
  70645. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70646. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70647. camera.inertialBetaOffset += normalizedRY;
  70648. }
  70649. }
  70650. }
  70651. var LSValues = this.gamepad.leftStick;
  70652. if (LSValues && LSValues.y != 0) {
  70653. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70654. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70655. this.camera.inertialRadiusOffset -= normalizedLY;
  70656. }
  70657. }
  70658. }
  70659. };
  70660. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70661. return "ArcRotateCameraGamepadInput";
  70662. };
  70663. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70664. return "gamepad";
  70665. };
  70666. __decorate([
  70667. BABYLON.serialize()
  70668. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70669. __decorate([
  70670. BABYLON.serialize()
  70671. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70672. return ArcRotateCameraGamepadInput;
  70673. }());
  70674. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70675. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70676. })(BABYLON || (BABYLON = {}));
  70677. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70678. var BABYLON;
  70679. (function (BABYLON) {
  70680. var GamepadManager = /** @class */ (function () {
  70681. function GamepadManager(_scene) {
  70682. var _this = this;
  70683. this._scene = _scene;
  70684. this._babylonGamepads = [];
  70685. this._oneGamepadConnected = false;
  70686. this._isMonitoring = false;
  70687. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70688. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70689. this._gamepadEventSupported = false;
  70690. }
  70691. else {
  70692. this._gamepadEventSupported = 'GamepadEvent' in window;
  70693. this._gamepadSupport = (navigator.getGamepads ||
  70694. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70695. }
  70696. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70697. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70698. for (var i in _this._babylonGamepads) {
  70699. var gamepad = _this._babylonGamepads[i];
  70700. if (gamepad && gamepad._isConnected) {
  70701. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70702. }
  70703. }
  70704. });
  70705. this._onGamepadConnectedEvent = function (evt) {
  70706. var gamepad = evt.gamepad;
  70707. if (gamepad.index in _this._babylonGamepads) {
  70708. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70709. return;
  70710. }
  70711. }
  70712. var newGamepad;
  70713. if (_this._babylonGamepads[gamepad.index]) {
  70714. newGamepad = _this._babylonGamepads[gamepad.index];
  70715. newGamepad.browserGamepad = gamepad;
  70716. newGamepad._isConnected = true;
  70717. }
  70718. else {
  70719. newGamepad = _this._addNewGamepad(gamepad);
  70720. }
  70721. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70722. _this._startMonitoringGamepads();
  70723. };
  70724. this._onGamepadDisconnectedEvent = function (evt) {
  70725. var gamepad = evt.gamepad;
  70726. // Remove the gamepad from the list of gamepads to monitor.
  70727. for (var i in _this._babylonGamepads) {
  70728. if (_this._babylonGamepads[i].index === gamepad.index) {
  70729. var disconnectedGamepad = _this._babylonGamepads[i];
  70730. disconnectedGamepad._isConnected = false;
  70731. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70732. break;
  70733. }
  70734. }
  70735. };
  70736. if (this._gamepadSupport) {
  70737. //first add already-connected gamepads
  70738. this._updateGamepadObjects();
  70739. if (this._babylonGamepads.length) {
  70740. this._startMonitoringGamepads();
  70741. }
  70742. // Checking if the gamepad connected event is supported (like in Firefox)
  70743. if (this._gamepadEventSupported) {
  70744. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70745. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70746. }
  70747. else {
  70748. this._startMonitoringGamepads();
  70749. }
  70750. }
  70751. }
  70752. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70753. get: function () {
  70754. return this._babylonGamepads;
  70755. },
  70756. enumerable: true,
  70757. configurable: true
  70758. });
  70759. GamepadManager.prototype.getGamepadByType = function (type) {
  70760. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70761. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70762. var gamepad = _a[_i];
  70763. if (gamepad && gamepad.type === type) {
  70764. return gamepad;
  70765. }
  70766. }
  70767. return null;
  70768. };
  70769. GamepadManager.prototype.dispose = function () {
  70770. if (this._gamepadEventSupported) {
  70771. if (this._onGamepadConnectedEvent) {
  70772. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70773. }
  70774. if (this._onGamepadDisconnectedEvent) {
  70775. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70776. }
  70777. this._onGamepadConnectedEvent = null;
  70778. this._onGamepadDisconnectedEvent = null;
  70779. }
  70780. this._babylonGamepads.forEach(function (gamepad) {
  70781. gamepad.dispose();
  70782. });
  70783. this.onGamepadConnectedObservable.clear();
  70784. this.onGamepadDisconnectedObservable.clear();
  70785. this._oneGamepadConnected = false;
  70786. this._stopMonitoringGamepads();
  70787. this._babylonGamepads = [];
  70788. };
  70789. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70790. if (!this._oneGamepadConnected) {
  70791. this._oneGamepadConnected = true;
  70792. }
  70793. var newGamepad;
  70794. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70795. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70796. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70797. }
  70798. // if pose is supported, use the (WebVR) pose enabled controller
  70799. else if (gamepad.pose) {
  70800. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70801. }
  70802. else {
  70803. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70804. }
  70805. this._babylonGamepads[newGamepad.index] = newGamepad;
  70806. return newGamepad;
  70807. };
  70808. GamepadManager.prototype._startMonitoringGamepads = function () {
  70809. if (!this._isMonitoring) {
  70810. this._isMonitoring = true;
  70811. //back-comp
  70812. if (!this._scene) {
  70813. this._checkGamepadsStatus();
  70814. }
  70815. }
  70816. };
  70817. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70818. this._isMonitoring = false;
  70819. };
  70820. GamepadManager.prototype._checkGamepadsStatus = function () {
  70821. var _this = this;
  70822. // Hack to be compatible Chrome
  70823. this._updateGamepadObjects();
  70824. for (var i in this._babylonGamepads) {
  70825. var gamepad = this._babylonGamepads[i];
  70826. if (!gamepad || !gamepad.isConnected) {
  70827. continue;
  70828. }
  70829. gamepad.update();
  70830. }
  70831. if (this._isMonitoring && !this._scene) {
  70832. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70833. }
  70834. };
  70835. // This function is called only on Chrome, which does not properly support
  70836. // connection/disconnection events and forces you to recopy again the gamepad object
  70837. GamepadManager.prototype._updateGamepadObjects = function () {
  70838. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70839. for (var i = 0; i < gamepads.length; i++) {
  70840. var gamepad = gamepads[i];
  70841. if (gamepad) {
  70842. if (!this._babylonGamepads[gamepad.index]) {
  70843. var newGamepad = this._addNewGamepad(gamepad);
  70844. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70845. }
  70846. else {
  70847. // Forced to copy again this object for Chrome for unknown reason
  70848. this._babylonGamepads[i].browserGamepad = gamepad;
  70849. if (!this._babylonGamepads[i].isConnected) {
  70850. this._babylonGamepads[i]._isConnected = true;
  70851. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70852. }
  70853. }
  70854. }
  70855. }
  70856. };
  70857. return GamepadManager;
  70858. }());
  70859. BABYLON.GamepadManager = GamepadManager;
  70860. })(BABYLON || (BABYLON = {}));
  70861. //# sourceMappingURL=babylon.gamepadManager.js.map
  70862. var BABYLON;
  70863. (function (BABYLON) {
  70864. var StickValues = /** @class */ (function () {
  70865. function StickValues(x, y) {
  70866. this.x = x;
  70867. this.y = y;
  70868. }
  70869. return StickValues;
  70870. }());
  70871. BABYLON.StickValues = StickValues;
  70872. var Gamepad = /** @class */ (function () {
  70873. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70874. if (leftStickX === void 0) { leftStickX = 0; }
  70875. if (leftStickY === void 0) { leftStickY = 1; }
  70876. if (rightStickX === void 0) { rightStickX = 2; }
  70877. if (rightStickY === void 0) { rightStickY = 3; }
  70878. this.id = id;
  70879. this.index = index;
  70880. this.browserGamepad = browserGamepad;
  70881. this._isConnected = true;
  70882. this._invertLeftStickY = false;
  70883. this.type = Gamepad.GAMEPAD;
  70884. this._leftStickAxisX = leftStickX;
  70885. this._leftStickAxisY = leftStickY;
  70886. this._rightStickAxisX = rightStickX;
  70887. this._rightStickAxisY = rightStickY;
  70888. if (this.browserGamepad.axes.length >= 2) {
  70889. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70890. }
  70891. if (this.browserGamepad.axes.length >= 4) {
  70892. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70893. }
  70894. }
  70895. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70896. get: function () {
  70897. return this._isConnected;
  70898. },
  70899. enumerable: true,
  70900. configurable: true
  70901. });
  70902. Gamepad.prototype.onleftstickchanged = function (callback) {
  70903. this._onleftstickchanged = callback;
  70904. };
  70905. Gamepad.prototype.onrightstickchanged = function (callback) {
  70906. this._onrightstickchanged = callback;
  70907. };
  70908. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70909. get: function () {
  70910. return this._leftStick;
  70911. },
  70912. set: function (newValues) {
  70913. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70914. this._onleftstickchanged(newValues);
  70915. }
  70916. this._leftStick = newValues;
  70917. },
  70918. enumerable: true,
  70919. configurable: true
  70920. });
  70921. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70922. get: function () {
  70923. return this._rightStick;
  70924. },
  70925. set: function (newValues) {
  70926. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70927. this._onrightstickchanged(newValues);
  70928. }
  70929. this._rightStick = newValues;
  70930. },
  70931. enumerable: true,
  70932. configurable: true
  70933. });
  70934. Gamepad.prototype.update = function () {
  70935. if (this._leftStick) {
  70936. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70937. if (this._invertLeftStickY) {
  70938. this.leftStick.y *= -1;
  70939. }
  70940. }
  70941. if (this._rightStick) {
  70942. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70943. }
  70944. };
  70945. Gamepad.prototype.dispose = function () {
  70946. };
  70947. Gamepad.GAMEPAD = 0;
  70948. Gamepad.GENERIC = 1;
  70949. Gamepad.XBOX = 2;
  70950. Gamepad.POSE_ENABLED = 3;
  70951. return Gamepad;
  70952. }());
  70953. BABYLON.Gamepad = Gamepad;
  70954. var GenericPad = /** @class */ (function (_super) {
  70955. __extends(GenericPad, _super);
  70956. function GenericPad(id, index, browserGamepad) {
  70957. var _this = _super.call(this, id, index, browserGamepad) || this;
  70958. _this.onButtonDownObservable = new BABYLON.Observable();
  70959. _this.onButtonUpObservable = new BABYLON.Observable();
  70960. _this.type = Gamepad.GENERIC;
  70961. _this._buttons = new Array(browserGamepad.buttons.length);
  70962. return _this;
  70963. }
  70964. GenericPad.prototype.onbuttondown = function (callback) {
  70965. this._onbuttondown = callback;
  70966. };
  70967. GenericPad.prototype.onbuttonup = function (callback) {
  70968. this._onbuttonup = callback;
  70969. };
  70970. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70971. if (newValue !== currentValue) {
  70972. if (newValue === 1) {
  70973. if (this._onbuttondown) {
  70974. this._onbuttondown(buttonIndex);
  70975. }
  70976. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70977. }
  70978. if (newValue === 0) {
  70979. if (this._onbuttonup) {
  70980. this._onbuttonup(buttonIndex);
  70981. }
  70982. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70983. }
  70984. }
  70985. return newValue;
  70986. };
  70987. GenericPad.prototype.update = function () {
  70988. _super.prototype.update.call(this);
  70989. for (var index = 0; index < this._buttons.length; index++) {
  70990. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70991. }
  70992. };
  70993. GenericPad.prototype.dispose = function () {
  70994. _super.prototype.dispose.call(this);
  70995. this.onButtonDownObservable.clear();
  70996. this.onButtonUpObservable.clear();
  70997. };
  70998. return GenericPad;
  70999. }(Gamepad));
  71000. BABYLON.GenericPad = GenericPad;
  71001. })(BABYLON || (BABYLON = {}));
  71002. //# sourceMappingURL=babylon.gamepad.js.map
  71003. var BABYLON;
  71004. (function (BABYLON) {
  71005. /**
  71006. * Defines supported buttons for XBox360 compatible gamepads
  71007. */
  71008. var Xbox360Button;
  71009. (function (Xbox360Button) {
  71010. /** A */
  71011. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71012. /** B */
  71013. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71014. /** X */
  71015. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71016. /** Y */
  71017. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71018. /** Start */
  71019. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71020. /** Back */
  71021. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71022. /** Left button */
  71023. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71024. /** Right button */
  71025. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71026. /** Left stick */
  71027. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71028. /** Right stick */
  71029. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71030. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71031. /** Defines values for XBox360 DPad */
  71032. var Xbox360Dpad;
  71033. (function (Xbox360Dpad) {
  71034. /** Up */
  71035. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71036. /** Down */
  71037. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71038. /** Left */
  71039. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71040. /** Right */
  71041. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71042. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71043. /**
  71044. * Defines a XBox360 gamepad
  71045. */
  71046. var Xbox360Pad = /** @class */ (function (_super) {
  71047. __extends(Xbox360Pad, _super);
  71048. /**
  71049. * Creates a new XBox360 gamepad object
  71050. * @param id defines the id of this gamepad
  71051. * @param index defines its index
  71052. * @param gamepad defines the internal HTML gamepad object
  71053. * @param xboxOne defines if it is a XBox One gamepad
  71054. */
  71055. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71056. if (xboxOne === void 0) { xboxOne = false; }
  71057. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71058. _this._leftTrigger = 0;
  71059. _this._rightTrigger = 0;
  71060. /** Observable raised when a button is pressed */
  71061. _this.onButtonDownObservable = new BABYLON.Observable();
  71062. /** Observable raised when a button is released */
  71063. _this.onButtonUpObservable = new BABYLON.Observable();
  71064. /** Observable raised when a pad is pressed */
  71065. _this.onPadDownObservable = new BABYLON.Observable();
  71066. /** Observable raised when a pad is released */
  71067. _this.onPadUpObservable = new BABYLON.Observable();
  71068. _this._buttonA = 0;
  71069. _this._buttonB = 0;
  71070. _this._buttonX = 0;
  71071. _this._buttonY = 0;
  71072. _this._buttonBack = 0;
  71073. _this._buttonStart = 0;
  71074. _this._buttonLB = 0;
  71075. _this._buttonRB = 0;
  71076. _this._buttonLeftStick = 0;
  71077. _this._buttonRightStick = 0;
  71078. _this._dPadUp = 0;
  71079. _this._dPadDown = 0;
  71080. _this._dPadLeft = 0;
  71081. _this._dPadRight = 0;
  71082. _this._isXboxOnePad = false;
  71083. _this.type = BABYLON.Gamepad.XBOX;
  71084. _this._isXboxOnePad = xboxOne;
  71085. return _this;
  71086. }
  71087. /**
  71088. * Defines the callback to call when left trigger is pressed
  71089. * @param callback defines the callback to use
  71090. */
  71091. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71092. this._onlefttriggerchanged = callback;
  71093. };
  71094. /**
  71095. * Defines the callback to call when right trigger is pressed
  71096. * @param callback defines the callback to use
  71097. */
  71098. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71099. this._onrighttriggerchanged = callback;
  71100. };
  71101. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71102. /**
  71103. * Gets or sets left trigger value
  71104. */
  71105. get: function () {
  71106. return this._leftTrigger;
  71107. },
  71108. set: function (newValue) {
  71109. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71110. this._onlefttriggerchanged(newValue);
  71111. }
  71112. this._leftTrigger = newValue;
  71113. },
  71114. enumerable: true,
  71115. configurable: true
  71116. });
  71117. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71118. /**
  71119. * Gets or sets right trigger value
  71120. */
  71121. get: function () {
  71122. return this._rightTrigger;
  71123. },
  71124. set: function (newValue) {
  71125. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71126. this._onrighttriggerchanged(newValue);
  71127. }
  71128. this._rightTrigger = newValue;
  71129. },
  71130. enumerable: true,
  71131. configurable: true
  71132. });
  71133. /**
  71134. * Defines the callback to call when a button is pressed
  71135. * @param callback defines the callback to use
  71136. */
  71137. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71138. this._onbuttondown = callback;
  71139. };
  71140. /**
  71141. * Defines the callback to call when a button is released
  71142. * @param callback defines the callback to use
  71143. */
  71144. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71145. this._onbuttonup = callback;
  71146. };
  71147. /**
  71148. * Defines the callback to call when a pad is pressed
  71149. * @param callback defines the callback to use
  71150. */
  71151. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71152. this._ondpaddown = callback;
  71153. };
  71154. /**
  71155. * Defines the callback to call when a pad is released
  71156. * @param callback defines the callback to use
  71157. */
  71158. Xbox360Pad.prototype.ondpadup = function (callback) {
  71159. this._ondpadup = callback;
  71160. };
  71161. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71162. if (newValue !== currentValue) {
  71163. if (newValue === 1) {
  71164. if (this._onbuttondown) {
  71165. this._onbuttondown(buttonType);
  71166. }
  71167. this.onButtonDownObservable.notifyObservers(buttonType);
  71168. }
  71169. if (newValue === 0) {
  71170. if (this._onbuttonup) {
  71171. this._onbuttonup(buttonType);
  71172. }
  71173. this.onButtonUpObservable.notifyObservers(buttonType);
  71174. }
  71175. }
  71176. return newValue;
  71177. };
  71178. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71179. if (newValue !== currentValue) {
  71180. if (newValue === 1) {
  71181. if (this._ondpaddown) {
  71182. this._ondpaddown(buttonType);
  71183. }
  71184. this.onPadDownObservable.notifyObservers(buttonType);
  71185. }
  71186. if (newValue === 0) {
  71187. if (this._ondpadup) {
  71188. this._ondpadup(buttonType);
  71189. }
  71190. this.onPadUpObservable.notifyObservers(buttonType);
  71191. }
  71192. }
  71193. return newValue;
  71194. };
  71195. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71196. /** Gets or sets value of A button */
  71197. get: function () {
  71198. return this._buttonA;
  71199. },
  71200. set: function (value) {
  71201. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71202. },
  71203. enumerable: true,
  71204. configurable: true
  71205. });
  71206. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71207. /** Gets or sets value of B button */
  71208. get: function () {
  71209. return this._buttonB;
  71210. },
  71211. set: function (value) {
  71212. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71213. },
  71214. enumerable: true,
  71215. configurable: true
  71216. });
  71217. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71218. /** Gets or sets value of X button */
  71219. get: function () {
  71220. return this._buttonX;
  71221. },
  71222. set: function (value) {
  71223. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71224. },
  71225. enumerable: true,
  71226. configurable: true
  71227. });
  71228. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71229. /** Gets or sets value of Y button */
  71230. get: function () {
  71231. return this._buttonY;
  71232. },
  71233. set: function (value) {
  71234. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71235. },
  71236. enumerable: true,
  71237. configurable: true
  71238. });
  71239. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71240. /** Gets or sets value of Start button */
  71241. get: function () {
  71242. return this._buttonStart;
  71243. },
  71244. set: function (value) {
  71245. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71246. },
  71247. enumerable: true,
  71248. configurable: true
  71249. });
  71250. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71251. /** Gets or sets value of Back button */
  71252. get: function () {
  71253. return this._buttonBack;
  71254. },
  71255. set: function (value) {
  71256. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71262. /** Gets or sets value of Left button */
  71263. get: function () {
  71264. return this._buttonLB;
  71265. },
  71266. set: function (value) {
  71267. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71273. /** Gets or sets value of Right button */
  71274. get: function () {
  71275. return this._buttonRB;
  71276. },
  71277. set: function (value) {
  71278. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71279. },
  71280. enumerable: true,
  71281. configurable: true
  71282. });
  71283. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71284. /** Gets or sets value of left stick */
  71285. get: function () {
  71286. return this._buttonLeftStick;
  71287. },
  71288. set: function (value) {
  71289. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71290. },
  71291. enumerable: true,
  71292. configurable: true
  71293. });
  71294. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71295. /** Gets or sets value of right stick */
  71296. get: function () {
  71297. return this._buttonRightStick;
  71298. },
  71299. set: function (value) {
  71300. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71301. },
  71302. enumerable: true,
  71303. configurable: true
  71304. });
  71305. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71306. /** Gets or sets value of DPad up */
  71307. get: function () {
  71308. return this._dPadUp;
  71309. },
  71310. set: function (value) {
  71311. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71312. },
  71313. enumerable: true,
  71314. configurable: true
  71315. });
  71316. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71317. /** Gets or sets value of DPad down */
  71318. get: function () {
  71319. return this._dPadDown;
  71320. },
  71321. set: function (value) {
  71322. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71328. /** Gets or sets value of DPad left */
  71329. get: function () {
  71330. return this._dPadLeft;
  71331. },
  71332. set: function (value) {
  71333. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71334. },
  71335. enumerable: true,
  71336. configurable: true
  71337. });
  71338. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71339. /** Gets or sets value of DPad right */
  71340. get: function () {
  71341. return this._dPadRight;
  71342. },
  71343. set: function (value) {
  71344. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71345. },
  71346. enumerable: true,
  71347. configurable: true
  71348. });
  71349. /**
  71350. * Force the gamepad to synchronize with device values
  71351. */
  71352. Xbox360Pad.prototype.update = function () {
  71353. _super.prototype.update.call(this);
  71354. if (this._isXboxOnePad) {
  71355. this.buttonA = this.browserGamepad.buttons[0].value;
  71356. this.buttonB = this.browserGamepad.buttons[1].value;
  71357. this.buttonX = this.browserGamepad.buttons[2].value;
  71358. this.buttonY = this.browserGamepad.buttons[3].value;
  71359. this.buttonLB = this.browserGamepad.buttons[4].value;
  71360. this.buttonRB = this.browserGamepad.buttons[5].value;
  71361. this.leftTrigger = this.browserGamepad.axes[2];
  71362. this.rightTrigger = this.browserGamepad.axes[5];
  71363. this.buttonBack = this.browserGamepad.buttons[9].value;
  71364. this.buttonStart = this.browserGamepad.buttons[8].value;
  71365. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71366. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71367. this.dPadUp = this.browserGamepad.buttons[11].value;
  71368. this.dPadDown = this.browserGamepad.buttons[12].value;
  71369. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71370. this.dPadRight = this.browserGamepad.buttons[14].value;
  71371. }
  71372. else {
  71373. this.buttonA = this.browserGamepad.buttons[0].value;
  71374. this.buttonB = this.browserGamepad.buttons[1].value;
  71375. this.buttonX = this.browserGamepad.buttons[2].value;
  71376. this.buttonY = this.browserGamepad.buttons[3].value;
  71377. this.buttonLB = this.browserGamepad.buttons[4].value;
  71378. this.buttonRB = this.browserGamepad.buttons[5].value;
  71379. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71380. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71381. this.buttonBack = this.browserGamepad.buttons[8].value;
  71382. this.buttonStart = this.browserGamepad.buttons[9].value;
  71383. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71384. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71385. this.dPadUp = this.browserGamepad.buttons[12].value;
  71386. this.dPadDown = this.browserGamepad.buttons[13].value;
  71387. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71388. this.dPadRight = this.browserGamepad.buttons[15].value;
  71389. }
  71390. };
  71391. Xbox360Pad.prototype.dispose = function () {
  71392. _super.prototype.dispose.call(this);
  71393. this.onButtonDownObservable.clear();
  71394. this.onButtonUpObservable.clear();
  71395. this.onPadDownObservable.clear();
  71396. this.onPadUpObservable.clear();
  71397. };
  71398. return Xbox360Pad;
  71399. }(BABYLON.Gamepad));
  71400. BABYLON.Xbox360Pad = Xbox360Pad;
  71401. })(BABYLON || (BABYLON = {}));
  71402. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71403. var BABYLON;
  71404. (function (BABYLON) {
  71405. /**
  71406. * Defines the types of pose enabled controllers that are supported
  71407. */
  71408. var PoseEnabledControllerType;
  71409. (function (PoseEnabledControllerType) {
  71410. /**
  71411. * HTC Vive
  71412. */
  71413. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71414. /**
  71415. * Oculus Rift
  71416. */
  71417. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71418. /**
  71419. * Windows mixed reality
  71420. */
  71421. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71422. /**
  71423. * Samsung gear VR
  71424. */
  71425. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71426. /**
  71427. * Google Daydream
  71428. */
  71429. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71430. /**
  71431. * Generic
  71432. */
  71433. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71434. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71435. /**
  71436. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71437. */
  71438. var PoseEnabledControllerHelper = /** @class */ (function () {
  71439. function PoseEnabledControllerHelper() {
  71440. }
  71441. /**
  71442. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71443. * @param vrGamepad the gamepad to initialized
  71444. * @returns a vr controller of the type the gamepad identified as
  71445. */
  71446. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71447. // Oculus Touch
  71448. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71449. return new BABYLON.OculusTouchController(vrGamepad);
  71450. }
  71451. // Windows Mixed Reality controllers
  71452. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71453. return new BABYLON.WindowsMotionController(vrGamepad);
  71454. }
  71455. // HTC Vive
  71456. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71457. return new BABYLON.ViveController(vrGamepad);
  71458. }
  71459. // Samsung/Oculus Gear VR or Oculus Go
  71460. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71461. return new BABYLON.GearVRController(vrGamepad);
  71462. }
  71463. // Google Daydream
  71464. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71465. return new BABYLON.DaydreamController(vrGamepad);
  71466. }
  71467. // Generic
  71468. else {
  71469. return new BABYLON.GenericController(vrGamepad);
  71470. }
  71471. };
  71472. return PoseEnabledControllerHelper;
  71473. }());
  71474. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71475. /**
  71476. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71477. */
  71478. var PoseEnabledController = /** @class */ (function (_super) {
  71479. __extends(PoseEnabledController, _super);
  71480. /**
  71481. * Creates a new PoseEnabledController from a gamepad
  71482. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71483. */
  71484. function PoseEnabledController(browserGamepad) {
  71485. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71486. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71487. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71488. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71489. /**
  71490. * The device position in babylon space
  71491. */
  71492. _this.devicePosition = BABYLON.Vector3.Zero();
  71493. /**
  71494. * The device rotation in babylon space
  71495. */
  71496. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71497. /**
  71498. * The scale factor of the device in babylon space
  71499. */
  71500. _this.deviceScaleFactor = 1;
  71501. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71502. /**
  71503. * Internal, matrix used to convert room space to babylon space
  71504. */
  71505. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71506. /**
  71507. * Node to be used when casting a ray from the controller
  71508. */
  71509. _this._pointingPoseNode = null;
  71510. _this._workingMatrix = BABYLON.Matrix.Identity();
  71511. /**
  71512. * @hidden
  71513. */
  71514. _this._meshAttachedObservable = new BABYLON.Observable();
  71515. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71516. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71517. _this.position = BABYLON.Vector3.Zero();
  71518. _this.rotationQuaternion = new BABYLON.Quaternion();
  71519. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71520. _this._calculatedRotation = new BABYLON.Quaternion();
  71521. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71522. return _this;
  71523. }
  71524. /**
  71525. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71526. */
  71527. PoseEnabledController.prototype.update = function () {
  71528. _super.prototype.update.call(this);
  71529. var pose = this.browserGamepad.pose;
  71530. this.updateFromDevice(pose);
  71531. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71532. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71533. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71534. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71535. if (this._mesh) {
  71536. this._mesh.position.copyFrom(this.devicePosition);
  71537. if (this._mesh.rotationQuaternion) {
  71538. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71539. }
  71540. }
  71541. };
  71542. /**
  71543. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71544. * @param poseData raw pose fromthe device
  71545. */
  71546. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71547. if (poseData) {
  71548. this.rawPose = poseData;
  71549. if (poseData.position) {
  71550. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71551. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71552. this._deviceRoomPosition.z *= -1;
  71553. }
  71554. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71555. this._calculatedPosition.addInPlace(this.position);
  71556. }
  71557. var pose = this.rawPose;
  71558. if (poseData.orientation && pose.orientation) {
  71559. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71560. if (this._mesh) {
  71561. if (this._mesh.getScene().useRightHandedSystem) {
  71562. this._deviceRoomRotationQuaternion.z *= -1;
  71563. this._deviceRoomRotationQuaternion.w *= -1;
  71564. }
  71565. else {
  71566. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71567. }
  71568. }
  71569. // if the camera is set, rotate to the camera's rotation
  71570. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71571. }
  71572. }
  71573. };
  71574. /**
  71575. * Attaches a mesh to the controller
  71576. * @param mesh the mesh to be attached
  71577. */
  71578. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71579. if (this._mesh) {
  71580. this._mesh.parent = null;
  71581. }
  71582. this._mesh = mesh;
  71583. if (this._poseControlledCamera) {
  71584. this._mesh.parent = this._poseControlledCamera;
  71585. }
  71586. if (!this._mesh.rotationQuaternion) {
  71587. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71588. }
  71589. // Sync controller mesh and pointing pose node's state with controller
  71590. this.update();
  71591. if (this._pointingPoseNode) {
  71592. var parents = [];
  71593. var obj = this._pointingPoseNode;
  71594. while (obj.parent) {
  71595. parents.push(obj.parent);
  71596. obj = obj.parent;
  71597. }
  71598. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71599. }
  71600. this._meshAttachedObservable.notifyObservers(mesh);
  71601. };
  71602. /**
  71603. * Attaches the controllers mesh to a camera
  71604. * @param camera the camera the mesh should be attached to
  71605. */
  71606. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71607. this._poseControlledCamera = camera;
  71608. if (this._mesh) {
  71609. this._mesh.parent = this._poseControlledCamera;
  71610. }
  71611. };
  71612. /**
  71613. * Disposes of the controller
  71614. */
  71615. PoseEnabledController.prototype.dispose = function () {
  71616. if (this._mesh) {
  71617. this._mesh.dispose();
  71618. }
  71619. this._mesh = null;
  71620. _super.prototype.dispose.call(this);
  71621. };
  71622. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71623. /**
  71624. * The mesh that is attached to the controller
  71625. */
  71626. get: function () {
  71627. return this._mesh;
  71628. },
  71629. enumerable: true,
  71630. configurable: true
  71631. });
  71632. /**
  71633. * Gets the ray of the controller in the direction the controller is pointing
  71634. * @param length the length the resulting ray should be
  71635. * @returns a ray in the direction the controller is pointing
  71636. */
  71637. PoseEnabledController.prototype.getForwardRay = function (length) {
  71638. if (length === void 0) { length = 100; }
  71639. if (!this.mesh) {
  71640. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71641. }
  71642. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71643. var origin = m.getTranslation();
  71644. var forward = new BABYLON.Vector3(0, 0, -1);
  71645. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71646. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71647. return new BABYLON.Ray(origin, direction, length);
  71648. };
  71649. /**
  71650. * Name of the child mesh that can be used to cast a ray from the controller
  71651. */
  71652. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71653. return PoseEnabledController;
  71654. }(BABYLON.Gamepad));
  71655. BABYLON.PoseEnabledController = PoseEnabledController;
  71656. })(BABYLON || (BABYLON = {}));
  71657. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71658. var BABYLON;
  71659. (function (BABYLON) {
  71660. /**
  71661. * Defines the WebVRController object that represents controllers tracked in 3D space
  71662. */
  71663. var WebVRController = /** @class */ (function (_super) {
  71664. __extends(WebVRController, _super);
  71665. /**
  71666. * Creates a new WebVRController from a gamepad
  71667. * @param vrGamepad the gamepad that the WebVRController should be created from
  71668. */
  71669. function WebVRController(vrGamepad) {
  71670. var _this = _super.call(this, vrGamepad) || this;
  71671. // Observables
  71672. /**
  71673. * Fired when the trigger state has changed
  71674. */
  71675. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71676. /**
  71677. * Fired when the main button state has changed
  71678. */
  71679. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71680. /**
  71681. * Fired when the secondary button state has changed
  71682. */
  71683. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71684. /**
  71685. * Fired when the pad state has changed
  71686. */
  71687. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71688. /**
  71689. * Fired when controllers stick values have changed
  71690. */
  71691. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71692. /**
  71693. * X and Y axis corrisponding to the controllers joystick
  71694. */
  71695. _this.pad = { x: 0, y: 0 };
  71696. // avoid GC, store state in a tmp object
  71697. _this._changes = {
  71698. pressChanged: false,
  71699. touchChanged: false,
  71700. valueChanged: false,
  71701. changed: false
  71702. };
  71703. _this._buttons = new Array(vrGamepad.buttons.length);
  71704. _this.hand = vrGamepad.hand;
  71705. return _this;
  71706. }
  71707. /**
  71708. * Fired when a controller button's state has changed
  71709. * @param callback the callback containing the button that was modified
  71710. */
  71711. WebVRController.prototype.onButtonStateChange = function (callback) {
  71712. this._onButtonStateChange = callback;
  71713. };
  71714. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71715. /**
  71716. * The default controller model for the controller
  71717. */
  71718. get: function () {
  71719. return this._defaultModel;
  71720. },
  71721. enumerable: true,
  71722. configurable: true
  71723. });
  71724. /**
  71725. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71726. */
  71727. WebVRController.prototype.update = function () {
  71728. _super.prototype.update.call(this);
  71729. for (var index = 0; index < this._buttons.length; index++) {
  71730. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71731. }
  71732. ;
  71733. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71734. this.pad.x = this.leftStick.x;
  71735. this.pad.y = this.leftStick.y;
  71736. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71737. }
  71738. };
  71739. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71740. if (!newState) {
  71741. newState = {
  71742. pressed: false,
  71743. touched: false,
  71744. value: 0
  71745. };
  71746. }
  71747. if (!currentState) {
  71748. this._buttons[buttonIndex] = {
  71749. pressed: newState.pressed,
  71750. touched: newState.touched,
  71751. value: newState.value
  71752. };
  71753. return;
  71754. }
  71755. this._checkChanges(newState, currentState);
  71756. if (this._changes.changed) {
  71757. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71758. this._handleButtonChange(buttonIndex, newState, this._changes);
  71759. }
  71760. this._buttons[buttonIndex].pressed = newState.pressed;
  71761. this._buttons[buttonIndex].touched = newState.touched;
  71762. // oculus triggers are never 0, thou not touched.
  71763. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71764. };
  71765. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71766. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71767. this._changes.touchChanged = newState.touched !== currentState.touched;
  71768. this._changes.valueChanged = newState.value !== currentState.value;
  71769. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71770. return this._changes;
  71771. };
  71772. /**
  71773. * Disposes of th webVRCOntroller
  71774. */
  71775. WebVRController.prototype.dispose = function () {
  71776. _super.prototype.dispose.call(this);
  71777. this.onTriggerStateChangedObservable.clear();
  71778. this.onMainButtonStateChangedObservable.clear();
  71779. this.onSecondaryButtonStateChangedObservable.clear();
  71780. this.onPadStateChangedObservable.clear();
  71781. this.onPadValuesChangedObservable.clear();
  71782. };
  71783. return WebVRController;
  71784. }(BABYLON.PoseEnabledController));
  71785. BABYLON.WebVRController = WebVRController;
  71786. })(BABYLON || (BABYLON = {}));
  71787. //# sourceMappingURL=babylon.webVRController.js.map
  71788. var BABYLON;
  71789. (function (BABYLON) {
  71790. /**
  71791. * Oculus Touch Controller
  71792. */
  71793. var OculusTouchController = /** @class */ (function (_super) {
  71794. __extends(OculusTouchController, _super);
  71795. /**
  71796. * Creates a new OculusTouchController from a gamepad
  71797. * @param vrGamepad the gamepad that the controller should be created from
  71798. */
  71799. function OculusTouchController(vrGamepad) {
  71800. var _this = _super.call(this, vrGamepad) || this;
  71801. /**
  71802. * Fired when the secondary trigger on this controller is modified
  71803. */
  71804. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71805. /**
  71806. * Fired when the thumb rest on this controller is modified
  71807. */
  71808. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71809. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71810. return _this;
  71811. }
  71812. /**
  71813. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71814. * @param scene scene in which to add meshes
  71815. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71816. */
  71817. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71818. var _this = this;
  71819. var meshName;
  71820. // Hand
  71821. if (this.hand === 'left') {
  71822. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71823. }
  71824. else { // Right is the default if no hand is specified
  71825. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71826. }
  71827. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71828. /*
  71829. Parent Mesh name: oculus_touch_left
  71830. - body
  71831. - trigger
  71832. - thumbstick
  71833. - grip
  71834. - button_y
  71835. - button_x
  71836. - button_enter
  71837. */
  71838. _this._defaultModel = newMeshes[1];
  71839. _this.attachToMesh(_this._defaultModel);
  71840. if (meshLoaded) {
  71841. meshLoaded(_this._defaultModel);
  71842. }
  71843. });
  71844. };
  71845. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71846. /**
  71847. * Fired when the A button on this controller is modified
  71848. */
  71849. get: function () {
  71850. if (this.hand === 'right') {
  71851. return this.onMainButtonStateChangedObservable;
  71852. }
  71853. else {
  71854. throw new Error('No A button on left hand');
  71855. }
  71856. },
  71857. enumerable: true,
  71858. configurable: true
  71859. });
  71860. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71861. /**
  71862. * Fired when the B button on this controller is modified
  71863. */
  71864. get: function () {
  71865. if (this.hand === 'right') {
  71866. return this.onSecondaryButtonStateChangedObservable;
  71867. }
  71868. else {
  71869. throw new Error('No B button on left hand');
  71870. }
  71871. },
  71872. enumerable: true,
  71873. configurable: true
  71874. });
  71875. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71876. /**
  71877. * Fired when the X button on this controller is modified
  71878. */
  71879. get: function () {
  71880. if (this.hand === 'left') {
  71881. return this.onMainButtonStateChangedObservable;
  71882. }
  71883. else {
  71884. throw new Error('No X button on right hand');
  71885. }
  71886. },
  71887. enumerable: true,
  71888. configurable: true
  71889. });
  71890. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71891. /**
  71892. * Fired when the Y button on this controller is modified
  71893. */
  71894. get: function () {
  71895. if (this.hand === 'left') {
  71896. return this.onSecondaryButtonStateChangedObservable;
  71897. }
  71898. else {
  71899. throw new Error('No Y button on right hand');
  71900. }
  71901. },
  71902. enumerable: true,
  71903. configurable: true
  71904. });
  71905. /**
  71906. * Called once for each button that changed state since the last frame
  71907. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71908. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71909. * 2) secondary trigger (same)
  71910. * 3) A (right) X (left), touch, pressed = value
  71911. * 4) B / Y
  71912. * 5) thumb rest
  71913. * @param buttonIdx Which button index changed
  71914. * @param state New state of the button
  71915. * @param changes Which properties on the state changed since last frame
  71916. */
  71917. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71918. var notifyObject = state; //{ state: state, changes: changes };
  71919. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71920. switch (buttonIdx) {
  71921. case 0:
  71922. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71923. return;
  71924. case 1: // index trigger
  71925. if (this._defaultModel) {
  71926. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71927. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71928. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71929. }
  71930. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71931. return;
  71932. case 2: // secondary trigger
  71933. if (this._defaultModel) {
  71934. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71935. }
  71936. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71937. return;
  71938. case 3:
  71939. if (this._defaultModel) {
  71940. if (notifyObject.pressed) {
  71941. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71942. }
  71943. else {
  71944. (this._defaultModel.getChildren()[1]).position.y = 0;
  71945. }
  71946. }
  71947. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71948. return;
  71949. case 4:
  71950. if (this._defaultModel) {
  71951. if (notifyObject.pressed) {
  71952. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71953. }
  71954. else {
  71955. (this._defaultModel.getChildren()[2]).position.y = 0;
  71956. }
  71957. }
  71958. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71959. return;
  71960. case 5:
  71961. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71962. return;
  71963. }
  71964. };
  71965. /**
  71966. * Base Url for the controller model.
  71967. */
  71968. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71969. /**
  71970. * File name for the left controller model.
  71971. */
  71972. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71973. /**
  71974. * File name for the right controller model.
  71975. */
  71976. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71977. return OculusTouchController;
  71978. }(BABYLON.WebVRController));
  71979. BABYLON.OculusTouchController = OculusTouchController;
  71980. })(BABYLON || (BABYLON = {}));
  71981. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71982. var BABYLON;
  71983. (function (BABYLON) {
  71984. /**
  71985. * Vive Controller
  71986. */
  71987. var ViveController = /** @class */ (function (_super) {
  71988. __extends(ViveController, _super);
  71989. /**
  71990. * Creates a new ViveController from a gamepad
  71991. * @param vrGamepad the gamepad that the controller should be created from
  71992. */
  71993. function ViveController(vrGamepad) {
  71994. var _this = _super.call(this, vrGamepad) || this;
  71995. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71996. _this._invertLeftStickY = true;
  71997. return _this;
  71998. }
  71999. /**
  72000. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72001. * @param scene scene in which to add meshes
  72002. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72003. */
  72004. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72005. var _this = this;
  72006. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72007. /*
  72008. Parent Mesh name: ViveWand
  72009. - body
  72010. - r_gripper
  72011. - l_gripper
  72012. - menu_button
  72013. - system_button
  72014. - trackpad
  72015. - trigger
  72016. - LED
  72017. */
  72018. _this._defaultModel = newMeshes[1];
  72019. _this.attachToMesh(_this._defaultModel);
  72020. if (meshLoaded) {
  72021. meshLoaded(_this._defaultModel);
  72022. }
  72023. });
  72024. };
  72025. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72026. /**
  72027. * Fired when the left button on this controller is modified
  72028. */
  72029. get: function () {
  72030. return this.onMainButtonStateChangedObservable;
  72031. },
  72032. enumerable: true,
  72033. configurable: true
  72034. });
  72035. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72036. /**
  72037. * Fired when the right button on this controller is modified
  72038. */
  72039. get: function () {
  72040. return this.onMainButtonStateChangedObservable;
  72041. },
  72042. enumerable: true,
  72043. configurable: true
  72044. });
  72045. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72046. /**
  72047. * Fired when the menu button on this controller is modified
  72048. */
  72049. get: function () {
  72050. return this.onSecondaryButtonStateChangedObservable;
  72051. },
  72052. enumerable: true,
  72053. configurable: true
  72054. });
  72055. /**
  72056. * Called once for each button that changed state since the last frame
  72057. * Vive mapping:
  72058. * 0: touchpad
  72059. * 1: trigger
  72060. * 2: left AND right buttons
  72061. * 3: menu button
  72062. * @param buttonIdx Which button index changed
  72063. * @param state New state of the button
  72064. * @param changes Which properties on the state changed since last frame
  72065. */
  72066. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72067. var notifyObject = state; //{ state: state, changes: changes };
  72068. switch (buttonIdx) {
  72069. case 0:
  72070. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72071. return;
  72072. case 1: // index trigger
  72073. if (this._defaultModel) {
  72074. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72075. }
  72076. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72077. return;
  72078. case 2: // left AND right button
  72079. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72080. return;
  72081. case 3:
  72082. if (this._defaultModel) {
  72083. if (notifyObject.pressed) {
  72084. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72085. }
  72086. else {
  72087. (this._defaultModel.getChildren()[2]).position.y = 0;
  72088. }
  72089. }
  72090. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72091. return;
  72092. }
  72093. };
  72094. /**
  72095. * Base Url for the controller model.
  72096. */
  72097. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72098. /**
  72099. * File name for the controller model.
  72100. */
  72101. ViveController.MODEL_FILENAME = 'wand.babylon';
  72102. return ViveController;
  72103. }(BABYLON.WebVRController));
  72104. BABYLON.ViveController = ViveController;
  72105. })(BABYLON || (BABYLON = {}));
  72106. //# sourceMappingURL=babylon.viveController.js.map
  72107. var BABYLON;
  72108. (function (BABYLON) {
  72109. /**
  72110. * Generic Controller
  72111. */
  72112. var GenericController = /** @class */ (function (_super) {
  72113. __extends(GenericController, _super);
  72114. /**
  72115. * Creates a new GenericController from a gamepad
  72116. * @param vrGamepad the gamepad that the controller should be created from
  72117. */
  72118. function GenericController(vrGamepad) {
  72119. return _super.call(this, vrGamepad) || this;
  72120. }
  72121. /**
  72122. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72123. * @param scene scene in which to add meshes
  72124. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72125. */
  72126. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72127. var _this = this;
  72128. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72129. _this._defaultModel = newMeshes[1];
  72130. _this.attachToMesh(_this._defaultModel);
  72131. if (meshLoaded) {
  72132. meshLoaded(_this._defaultModel);
  72133. }
  72134. });
  72135. };
  72136. /**
  72137. * Called once for each button that changed state since the last frame
  72138. * @param buttonIdx Which button index changed
  72139. * @param state New state of the button
  72140. * @param changes Which properties on the state changed since last frame
  72141. */
  72142. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72143. console.log("Button id: " + buttonIdx + "state: ");
  72144. console.dir(state);
  72145. };
  72146. /**
  72147. * Base Url for the controller model.
  72148. */
  72149. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72150. /**
  72151. * File name for the controller model.
  72152. */
  72153. GenericController.MODEL_FILENAME = 'generic.babylon';
  72154. return GenericController;
  72155. }(BABYLON.WebVRController));
  72156. BABYLON.GenericController = GenericController;
  72157. })(BABYLON || (BABYLON = {}));
  72158. //# sourceMappingURL=babylon.genericController.js.map
  72159. var BABYLON;
  72160. (function (BABYLON) {
  72161. /**
  72162. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72163. */
  72164. var LoadedMeshInfo = /** @class */ (function () {
  72165. function LoadedMeshInfo() {
  72166. /**
  72167. * Map of the button meshes contained in the controller
  72168. */
  72169. this.buttonMeshes = {};
  72170. /**
  72171. * Map of the axis meshes contained in the controller
  72172. */
  72173. this.axisMeshes = {};
  72174. }
  72175. return LoadedMeshInfo;
  72176. }());
  72177. /**
  72178. * Defines the WindowsMotionController object that the state of the windows motion controller
  72179. */
  72180. var WindowsMotionController = /** @class */ (function (_super) {
  72181. __extends(WindowsMotionController, _super);
  72182. /**
  72183. * Creates a new WindowsMotionController from a gamepad
  72184. * @param vrGamepad the gamepad that the controller should be created from
  72185. */
  72186. function WindowsMotionController(vrGamepad) {
  72187. var _this = _super.call(this, vrGamepad) || this;
  72188. _this._mapping = {
  72189. // Semantic button names
  72190. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72191. // A mapping of the button name to glTF model node name
  72192. // that should be transformed by button value.
  72193. buttonMeshNames: {
  72194. 'trigger': 'SELECT',
  72195. 'menu': 'MENU',
  72196. 'grip': 'GRASP',
  72197. 'thumbstick': 'THUMBSTICK_PRESS',
  72198. 'trackpad': 'TOUCHPAD_PRESS'
  72199. },
  72200. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72201. buttonObservableNames: {
  72202. 'trigger': 'onTriggerStateChangedObservable',
  72203. 'menu': 'onSecondaryButtonStateChangedObservable',
  72204. 'grip': 'onMainButtonStateChangedObservable',
  72205. 'thumbstick': 'onPadStateChangedObservable',
  72206. 'trackpad': 'onTrackpadChangedObservable'
  72207. },
  72208. // A mapping of the axis name to glTF model node name
  72209. // that should be transformed by axis value.
  72210. // This array mirrors the browserGamepad.axes array, such that
  72211. // the mesh corresponding to axis 0 is in this array index 0.
  72212. axisMeshNames: [
  72213. 'THUMBSTICK_X',
  72214. 'THUMBSTICK_Y',
  72215. 'TOUCHPAD_TOUCH_X',
  72216. 'TOUCHPAD_TOUCH_Y'
  72217. ],
  72218. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72219. };
  72220. /**
  72221. * Fired when the trackpad on this controller is clicked
  72222. */
  72223. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72224. /**
  72225. * Fired when the trackpad on this controller is modified
  72226. */
  72227. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72228. /**
  72229. * The current x and y values of this controller's trackpad
  72230. */
  72231. _this.trackpad = { x: 0, y: 0 };
  72232. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72233. _this._loadedMeshInfo = null;
  72234. return _this;
  72235. }
  72236. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72237. /**
  72238. * Fired when the trigger on this controller is modified
  72239. */
  72240. get: function () {
  72241. return this.onTriggerStateChangedObservable;
  72242. },
  72243. enumerable: true,
  72244. configurable: true
  72245. });
  72246. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72247. /**
  72248. * Fired when the menu button on this controller is modified
  72249. */
  72250. get: function () {
  72251. return this.onSecondaryButtonStateChangedObservable;
  72252. },
  72253. enumerable: true,
  72254. configurable: true
  72255. });
  72256. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72257. /**
  72258. * Fired when the grip button on this controller is modified
  72259. */
  72260. get: function () {
  72261. return this.onMainButtonStateChangedObservable;
  72262. },
  72263. enumerable: true,
  72264. configurable: true
  72265. });
  72266. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72267. /**
  72268. * Fired when the thumbstick button on this controller is modified
  72269. */
  72270. get: function () {
  72271. return this.onPadStateChangedObservable;
  72272. },
  72273. enumerable: true,
  72274. configurable: true
  72275. });
  72276. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72277. /**
  72278. * Fired when the touchpad button on this controller is modified
  72279. */
  72280. get: function () {
  72281. return this.onTrackpadChangedObservable;
  72282. },
  72283. enumerable: true,
  72284. configurable: true
  72285. });
  72286. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72287. /**
  72288. * Fired when the touchpad values on this controller are modified
  72289. */
  72290. get: function () {
  72291. return this.onTrackpadValuesChangedObservable;
  72292. },
  72293. enumerable: true,
  72294. configurable: true
  72295. });
  72296. WindowsMotionController.prototype._updateTrackpad = function () {
  72297. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72298. this.trackpad.x = this.browserGamepad["axes"][2];
  72299. this.trackpad.y = this.browserGamepad["axes"][3];
  72300. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72301. }
  72302. };
  72303. /**
  72304. * Called once per frame by the engine.
  72305. */
  72306. WindowsMotionController.prototype.update = function () {
  72307. _super.prototype.update.call(this);
  72308. if (this.browserGamepad.axes) {
  72309. this._updateTrackpad();
  72310. // Only need to animate axes if there is a loaded mesh
  72311. if (this._loadedMeshInfo) {
  72312. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72313. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72314. }
  72315. }
  72316. }
  72317. };
  72318. /**
  72319. * Called once for each button that changed state since the last frame
  72320. * @param buttonIdx Which button index changed
  72321. * @param state New state of the button
  72322. * @param changes Which properties on the state changed since last frame
  72323. */
  72324. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72325. var buttonName = this._mapping.buttons[buttonIdx];
  72326. if (!buttonName) {
  72327. return;
  72328. }
  72329. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72330. this._updateTrackpad();
  72331. // Only emit events for buttons that we know how to map from index to name
  72332. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72333. if (observable) {
  72334. observable.notifyObservers(state);
  72335. }
  72336. this._lerpButtonTransform(buttonName, state.value);
  72337. };
  72338. /**
  72339. * Moves the buttons on the controller mesh based on their current state
  72340. * @param buttonName the name of the button to move
  72341. * @param buttonValue the value of the button which determines the buttons new position
  72342. */
  72343. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72344. // If there is no loaded mesh, there is nothing to transform.
  72345. if (!this._loadedMeshInfo) {
  72346. return;
  72347. }
  72348. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72349. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72350. return;
  72351. }
  72352. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72353. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72354. };
  72355. /**
  72356. * Moves the axis on the controller mesh based on its current state
  72357. * @param axis the index of the axis
  72358. * @param axisValue the value of the axis which determines the meshes new position
  72359. * @hidden
  72360. */
  72361. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72362. if (!this._loadedMeshInfo) {
  72363. return;
  72364. }
  72365. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72366. if (!meshInfo) {
  72367. return;
  72368. }
  72369. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72370. return;
  72371. }
  72372. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72373. var lerpValue = axisValue * 0.5 + 0.5;
  72374. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72375. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72376. };
  72377. /**
  72378. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72379. * @param scene scene in which to add meshes
  72380. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72381. */
  72382. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72383. var _this = this;
  72384. if (forceDefault === void 0) { forceDefault = false; }
  72385. var path;
  72386. var filename;
  72387. // Checking if GLB loader is present
  72388. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72389. // Determine the device specific folder based on the ID suffix
  72390. var device = 'default';
  72391. if (this.id && !forceDefault) {
  72392. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72393. device = ((match && match[0]) || device);
  72394. }
  72395. // Hand
  72396. if (this.hand === 'left') {
  72397. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72398. }
  72399. else { // Right is the default if no hand is specified
  72400. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72401. }
  72402. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72403. }
  72404. else {
  72405. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72406. path = BABYLON.GenericController.MODEL_BASE_URL;
  72407. filename = BABYLON.GenericController.MODEL_FILENAME;
  72408. }
  72409. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72410. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72411. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72412. if (!_this._loadedMeshInfo) {
  72413. return;
  72414. }
  72415. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72416. _this.attachToMesh(_this._defaultModel);
  72417. if (meshLoaded) {
  72418. meshLoaded(_this._defaultModel);
  72419. }
  72420. }, null, function (scene, message) {
  72421. BABYLON.Tools.Log(message);
  72422. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72423. if (!forceDefault) {
  72424. _this.initControllerMesh(scene, meshLoaded, true);
  72425. }
  72426. });
  72427. };
  72428. /**
  72429. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72430. * can be transformed by button presses and axes values, based on this._mapping.
  72431. *
  72432. * @param scene scene in which the meshes exist
  72433. * @param meshes list of meshes that make up the controller model to process
  72434. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72435. */
  72436. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72437. var loadedMeshInfo = null;
  72438. // Create a new mesh to contain the glTF hierarchy
  72439. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72440. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72441. var childMesh = null;
  72442. for (var i = 0; i < meshes.length; i++) {
  72443. var mesh = meshes[i];
  72444. if (!mesh.parent) {
  72445. // Exclude controller meshes from picking results
  72446. mesh.isPickable = false;
  72447. // Handle root node, attach to the new parentMesh
  72448. childMesh = mesh;
  72449. break;
  72450. }
  72451. }
  72452. if (childMesh) {
  72453. childMesh.setParent(parentMesh);
  72454. // Create our mesh info. Note that this method will always return non-null.
  72455. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72456. }
  72457. else {
  72458. BABYLON.Tools.Warn('Could not find root node in model file.');
  72459. }
  72460. return loadedMeshInfo;
  72461. };
  72462. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72463. var loadedMeshInfo = new LoadedMeshInfo();
  72464. var i;
  72465. loadedMeshInfo.rootNode = rootNode;
  72466. // Reset the caches
  72467. loadedMeshInfo.buttonMeshes = {};
  72468. loadedMeshInfo.axisMeshes = {};
  72469. // Button Meshes
  72470. for (i = 0; i < this._mapping.buttons.length; i++) {
  72471. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72472. if (!buttonMeshName) {
  72473. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72474. continue;
  72475. }
  72476. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72477. if (!buttonMesh) {
  72478. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72479. continue;
  72480. }
  72481. var buttonMeshInfo = {
  72482. index: i,
  72483. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72484. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72485. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72486. };
  72487. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72488. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72489. }
  72490. else {
  72491. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72492. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72493. '(VALUE: ' + !!buttonMeshInfo.value +
  72494. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72495. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72496. ')');
  72497. }
  72498. }
  72499. // Axis Meshes
  72500. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72501. var axisMeshName = this._mapping.axisMeshNames[i];
  72502. if (!axisMeshName) {
  72503. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72504. continue;
  72505. }
  72506. var axisMesh = getChildByName(rootNode, axisMeshName);
  72507. if (!axisMesh) {
  72508. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72509. continue;
  72510. }
  72511. var axisMeshInfo = {
  72512. index: i,
  72513. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72514. min: getImmediateChildByName(axisMesh, 'MIN'),
  72515. max: getImmediateChildByName(axisMesh, 'MAX')
  72516. };
  72517. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72518. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72519. }
  72520. else {
  72521. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72522. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72523. '(VALUE: ' + !!axisMeshInfo.value +
  72524. ', MIN: ' + !!axisMeshInfo.min +
  72525. ', MAX:' + !!axisMeshInfo.max +
  72526. ')');
  72527. }
  72528. }
  72529. // Pointing Ray
  72530. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72531. if (!loadedMeshInfo.pointingPoseNode) {
  72532. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72533. }
  72534. else {
  72535. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72536. }
  72537. return loadedMeshInfo;
  72538. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72539. function getChildByName(node, name) {
  72540. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72541. }
  72542. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72543. function getImmediateChildByName(node, name) {
  72544. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72545. }
  72546. };
  72547. /**
  72548. * Gets the ray of the controller in the direction the controller is pointing
  72549. * @param length the length the resulting ray should be
  72550. * @returns a ray in the direction the controller is pointing
  72551. */
  72552. WindowsMotionController.prototype.getForwardRay = function (length) {
  72553. if (length === void 0) { length = 100; }
  72554. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72555. return _super.prototype.getForwardRay.call(this, length);
  72556. }
  72557. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72558. var origin = m.getTranslation();
  72559. var forward = new BABYLON.Vector3(0, 0, -1);
  72560. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72561. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72562. return new BABYLON.Ray(origin, direction, length);
  72563. };
  72564. /**
  72565. * Disposes of the controller
  72566. */
  72567. WindowsMotionController.prototype.dispose = function () {
  72568. _super.prototype.dispose.call(this);
  72569. this.onTrackpadChangedObservable.clear();
  72570. };
  72571. /**
  72572. * The base url used to load the left and right controller models
  72573. */
  72574. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72575. /**
  72576. * The name of the left controller model file
  72577. */
  72578. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72579. /**
  72580. * The name of the right controller model file
  72581. */
  72582. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72583. /**
  72584. * The controller name prefix for this controller type
  72585. */
  72586. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72587. /**
  72588. * The controller id pattern for this controller type
  72589. */
  72590. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72591. return WindowsMotionController;
  72592. }(BABYLON.WebVRController));
  72593. BABYLON.WindowsMotionController = WindowsMotionController;
  72594. })(BABYLON || (BABYLON = {}));
  72595. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72596. var BABYLON;
  72597. (function (BABYLON) {
  72598. /**
  72599. * Gear VR Controller
  72600. */
  72601. var GearVRController = /** @class */ (function (_super) {
  72602. __extends(GearVRController, _super);
  72603. /**
  72604. * Creates a new GearVRController from a gamepad
  72605. * @param vrGamepad the gamepad that the controller should be created from
  72606. */
  72607. function GearVRController(vrGamepad) {
  72608. var _this = _super.call(this, vrGamepad) || this;
  72609. _this._buttonIndexToObservableNameMap = [
  72610. 'onTrackpadChangedObservable',
  72611. 'onTriggerStateChangedObservable' // Trigger
  72612. ];
  72613. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72614. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72615. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72616. return _this;
  72617. }
  72618. /**
  72619. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72620. * @param scene scene in which to add meshes
  72621. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72622. */
  72623. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72624. var _this = this;
  72625. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72626. _this._defaultModel = newMeshes[1];
  72627. _this.attachToMesh(_this._defaultModel);
  72628. if (meshLoaded) {
  72629. meshLoaded(_this._defaultModel);
  72630. }
  72631. });
  72632. };
  72633. /**
  72634. * Called once for each button that changed state since the last frame
  72635. * @param buttonIdx Which button index changed
  72636. * @param state New state of the button
  72637. * @param changes Which properties on the state changed since last frame
  72638. */
  72639. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72640. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72641. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72642. // Only emit events for buttons that we know how to map from index to observable
  72643. var observable = this[observableName];
  72644. if (observable) {
  72645. observable.notifyObservers(state);
  72646. }
  72647. }
  72648. };
  72649. /**
  72650. * Base Url for the controller model.
  72651. */
  72652. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72653. /**
  72654. * File name for the controller model.
  72655. */
  72656. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72657. /**
  72658. * Gamepad Id prefix used to identify this controller.
  72659. */
  72660. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72661. return GearVRController;
  72662. }(BABYLON.WebVRController));
  72663. BABYLON.GearVRController = GearVRController;
  72664. })(BABYLON || (BABYLON = {}));
  72665. //# sourceMappingURL=babylon.gearVRController.js.map
  72666. var BABYLON;
  72667. (function (BABYLON) {
  72668. /**
  72669. * Google Daydream controller
  72670. */
  72671. var DaydreamController = /** @class */ (function (_super) {
  72672. __extends(DaydreamController, _super);
  72673. /**
  72674. * Creates a new DaydreamController from a gamepad
  72675. * @param vrGamepad the gamepad that the controller should be created from
  72676. */
  72677. function DaydreamController(vrGamepad) {
  72678. var _this = _super.call(this, vrGamepad) || this;
  72679. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72680. return _this;
  72681. }
  72682. /**
  72683. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72684. * @param scene scene in which to add meshes
  72685. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72686. */
  72687. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72688. var _this = this;
  72689. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72690. _this._defaultModel = newMeshes[1];
  72691. _this.attachToMesh(_this._defaultModel);
  72692. if (meshLoaded) {
  72693. meshLoaded(_this._defaultModel);
  72694. }
  72695. });
  72696. };
  72697. /**
  72698. * Called once for each button that changed state since the last frame
  72699. * @param buttonIdx Which button index changed
  72700. * @param state New state of the button
  72701. * @param changes Which properties on the state changed since last frame
  72702. */
  72703. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72704. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72705. if (buttonIdx === 0) {
  72706. var observable = this.onTriggerStateChangedObservable;
  72707. if (observable) {
  72708. observable.notifyObservers(state);
  72709. }
  72710. }
  72711. else {
  72712. // If the app or home buttons are ever made available
  72713. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72714. }
  72715. };
  72716. /**
  72717. * Base Url for the controller model.
  72718. */
  72719. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72720. /**
  72721. * File name for the controller model.
  72722. */
  72723. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72724. /**
  72725. * Gamepad Id prefix used to identify Daydream Controller.
  72726. */
  72727. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72728. return DaydreamController;
  72729. }(BABYLON.WebVRController));
  72730. BABYLON.DaydreamController = DaydreamController;
  72731. })(BABYLON || (BABYLON = {}));
  72732. //# sourceMappingURL=babylon.daydreamController.js.map
  72733. var BABYLON;
  72734. (function (BABYLON) {
  72735. var FollowCamera = /** @class */ (function (_super) {
  72736. __extends(FollowCamera, _super);
  72737. function FollowCamera(name, position, scene, lockedTarget) {
  72738. if (lockedTarget === void 0) { lockedTarget = null; }
  72739. var _this = _super.call(this, name, position, scene) || this;
  72740. _this.radius = 12;
  72741. _this.rotationOffset = 0;
  72742. _this.heightOffset = 4;
  72743. _this.cameraAcceleration = 0.05;
  72744. _this.maxCameraSpeed = 20;
  72745. _this.lockedTarget = lockedTarget;
  72746. return _this;
  72747. }
  72748. FollowCamera.prototype.getRadians = function (degrees) {
  72749. return degrees * Math.PI / 180;
  72750. };
  72751. FollowCamera.prototype.follow = function (cameraTarget) {
  72752. if (!cameraTarget)
  72753. return;
  72754. var yRotation;
  72755. if (cameraTarget.rotationQuaternion) {
  72756. var rotMatrix = new BABYLON.Matrix();
  72757. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72758. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72759. }
  72760. else {
  72761. yRotation = cameraTarget.rotation.y;
  72762. }
  72763. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72764. var targetPosition = cameraTarget.getAbsolutePosition();
  72765. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72766. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72767. var dx = targetX - this.position.x;
  72768. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72769. var dz = (targetZ) - this.position.z;
  72770. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72771. var vy = dy * this.cameraAcceleration;
  72772. var vz = dz * this.cameraAcceleration * 2;
  72773. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72774. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72775. }
  72776. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72777. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72778. }
  72779. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72780. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72781. }
  72782. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72783. this.setTarget(targetPosition);
  72784. };
  72785. FollowCamera.prototype._checkInputs = function () {
  72786. _super.prototype._checkInputs.call(this);
  72787. if (this.lockedTarget) {
  72788. this.follow(this.lockedTarget);
  72789. }
  72790. };
  72791. FollowCamera.prototype.getClassName = function () {
  72792. return "FollowCamera";
  72793. };
  72794. __decorate([
  72795. BABYLON.serialize()
  72796. ], FollowCamera.prototype, "radius", void 0);
  72797. __decorate([
  72798. BABYLON.serialize()
  72799. ], FollowCamera.prototype, "rotationOffset", void 0);
  72800. __decorate([
  72801. BABYLON.serialize()
  72802. ], FollowCamera.prototype, "heightOffset", void 0);
  72803. __decorate([
  72804. BABYLON.serialize()
  72805. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72806. __decorate([
  72807. BABYLON.serialize()
  72808. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72809. __decorate([
  72810. BABYLON.serializeAsMeshReference("lockedTargetId")
  72811. ], FollowCamera.prototype, "lockedTarget", void 0);
  72812. return FollowCamera;
  72813. }(BABYLON.TargetCamera));
  72814. BABYLON.FollowCamera = FollowCamera;
  72815. var ArcFollowCamera = /** @class */ (function (_super) {
  72816. __extends(ArcFollowCamera, _super);
  72817. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72818. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72819. _this.alpha = alpha;
  72820. _this.beta = beta;
  72821. _this.radius = radius;
  72822. _this.target = target;
  72823. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72824. _this.follow();
  72825. return _this;
  72826. }
  72827. ArcFollowCamera.prototype.follow = function () {
  72828. if (!this.target) {
  72829. return;
  72830. }
  72831. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72832. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72833. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72834. var targetPosition = this.target.getAbsolutePosition();
  72835. this.position = targetPosition.add(this._cartesianCoordinates);
  72836. this.setTarget(targetPosition);
  72837. };
  72838. ArcFollowCamera.prototype._checkInputs = function () {
  72839. _super.prototype._checkInputs.call(this);
  72840. this.follow();
  72841. };
  72842. ArcFollowCamera.prototype.getClassName = function () {
  72843. return "ArcFollowCamera";
  72844. };
  72845. return ArcFollowCamera;
  72846. }(BABYLON.TargetCamera));
  72847. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72848. })(BABYLON || (BABYLON = {}));
  72849. //# sourceMappingURL=babylon.followCamera.js.map
  72850. var BABYLON;
  72851. (function (BABYLON) {
  72852. // We're mainly based on the logic defined into the FreeCamera code
  72853. var UniversalCamera = /** @class */ (function (_super) {
  72854. __extends(UniversalCamera, _super);
  72855. //-- end properties for backward compatibility for inputs
  72856. function UniversalCamera(name, position, scene) {
  72857. var _this = _super.call(this, name, position, scene) || this;
  72858. _this.inputs.addGamepad();
  72859. return _this;
  72860. }
  72861. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72862. //-- Begin properties for backward compatibility for inputs
  72863. get: function () {
  72864. var gamepad = this.inputs.attached["gamepad"];
  72865. if (gamepad)
  72866. return gamepad.gamepadAngularSensibility;
  72867. return 0;
  72868. },
  72869. set: function (value) {
  72870. var gamepad = this.inputs.attached["gamepad"];
  72871. if (gamepad)
  72872. gamepad.gamepadAngularSensibility = value;
  72873. },
  72874. enumerable: true,
  72875. configurable: true
  72876. });
  72877. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72878. get: function () {
  72879. var gamepad = this.inputs.attached["gamepad"];
  72880. if (gamepad)
  72881. return gamepad.gamepadMoveSensibility;
  72882. return 0;
  72883. },
  72884. set: function (value) {
  72885. var gamepad = this.inputs.attached["gamepad"];
  72886. if (gamepad)
  72887. gamepad.gamepadMoveSensibility = value;
  72888. },
  72889. enumerable: true,
  72890. configurable: true
  72891. });
  72892. UniversalCamera.prototype.getClassName = function () {
  72893. return "UniversalCamera";
  72894. };
  72895. return UniversalCamera;
  72896. }(BABYLON.TouchCamera));
  72897. BABYLON.UniversalCamera = UniversalCamera;
  72898. })(BABYLON || (BABYLON = {}));
  72899. //# sourceMappingURL=babylon.universalCamera.js.map
  72900. var BABYLON;
  72901. (function (BABYLON) {
  72902. // We're mainly based on the logic defined into the FreeCamera code
  72903. var GamepadCamera = /** @class */ (function (_super) {
  72904. __extends(GamepadCamera, _super);
  72905. //-- end properties for backward compatibility for inputs
  72906. function GamepadCamera(name, position, scene) {
  72907. return _super.call(this, name, position, scene) || this;
  72908. }
  72909. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72910. //-- Begin properties for backward compatibility for inputs
  72911. get: function () {
  72912. var gamepad = this.inputs.attached["gamepad"];
  72913. if (gamepad)
  72914. return gamepad.gamepadAngularSensibility;
  72915. return 0;
  72916. },
  72917. set: function (value) {
  72918. var gamepad = this.inputs.attached["gamepad"];
  72919. if (gamepad)
  72920. gamepad.gamepadAngularSensibility = value;
  72921. },
  72922. enumerable: true,
  72923. configurable: true
  72924. });
  72925. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72926. get: function () {
  72927. var gamepad = this.inputs.attached["gamepad"];
  72928. if (gamepad)
  72929. return gamepad.gamepadMoveSensibility;
  72930. return 0;
  72931. },
  72932. set: function (value) {
  72933. var gamepad = this.inputs.attached["gamepad"];
  72934. if (gamepad)
  72935. gamepad.gamepadMoveSensibility = value;
  72936. },
  72937. enumerable: true,
  72938. configurable: true
  72939. });
  72940. GamepadCamera.prototype.getClassName = function () {
  72941. return "GamepadCamera";
  72942. };
  72943. return GamepadCamera;
  72944. }(BABYLON.UniversalCamera));
  72945. BABYLON.GamepadCamera = GamepadCamera;
  72946. })(BABYLON || (BABYLON = {}));
  72947. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72948. var BABYLON;
  72949. (function (BABYLON) {
  72950. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72951. function PostProcessRenderPipelineManager() {
  72952. this._renderPipelines = {};
  72953. }
  72954. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72955. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72956. };
  72957. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72958. if (unique === void 0) { unique = false; }
  72959. var renderPipeline = this._renderPipelines[renderPipelineName];
  72960. if (!renderPipeline) {
  72961. return;
  72962. }
  72963. renderPipeline._attachCameras(cameras, unique);
  72964. };
  72965. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72966. var renderPipeline = this._renderPipelines[renderPipelineName];
  72967. if (!renderPipeline) {
  72968. return;
  72969. }
  72970. renderPipeline._detachCameras(cameras);
  72971. };
  72972. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72973. var renderPipeline = this._renderPipelines[renderPipelineName];
  72974. if (!renderPipeline) {
  72975. return;
  72976. }
  72977. renderPipeline._enableEffect(renderEffectName, cameras);
  72978. };
  72979. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72980. var renderPipeline = this._renderPipelines[renderPipelineName];
  72981. if (!renderPipeline) {
  72982. return;
  72983. }
  72984. renderPipeline._disableEffect(renderEffectName, cameras);
  72985. };
  72986. PostProcessRenderPipelineManager.prototype.update = function () {
  72987. for (var renderPipelineName in this._renderPipelines) {
  72988. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72989. var pipeline = this._renderPipelines[renderPipelineName];
  72990. if (!pipeline.isSupported) {
  72991. pipeline.dispose();
  72992. delete this._renderPipelines[renderPipelineName];
  72993. }
  72994. else {
  72995. pipeline._update();
  72996. }
  72997. }
  72998. }
  72999. };
  73000. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73001. for (var renderPipelineName in this._renderPipelines) {
  73002. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73003. var pipeline = this._renderPipelines[renderPipelineName];
  73004. pipeline._rebuild();
  73005. }
  73006. }
  73007. };
  73008. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73009. for (var renderPipelineName in this._renderPipelines) {
  73010. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73011. var pipeline = this._renderPipelines[renderPipelineName];
  73012. pipeline.dispose();
  73013. }
  73014. }
  73015. };
  73016. return PostProcessRenderPipelineManager;
  73017. }());
  73018. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73019. })(BABYLON || (BABYLON = {}));
  73020. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73021. var BABYLON;
  73022. (function (BABYLON) {
  73023. /**
  73024. * This represents a set of one or more post processes in Babylon.
  73025. * A post process can be used to apply a shader to a texture after it is rendered.
  73026. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73027. */
  73028. var PostProcessRenderEffect = /** @class */ (function () {
  73029. /**
  73030. * Instantiates a post process render effect.
  73031. * A post process can be used to apply a shader to a texture after it is rendered.
  73032. * @param engine The engine the effect is tied to
  73033. * @param name The name of the effect
  73034. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73035. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73036. */
  73037. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73038. this._name = name;
  73039. this._singleInstance = singleInstance || true;
  73040. this._getPostProcesses = getPostProcesses;
  73041. this._cameras = {};
  73042. this._indicesForCamera = {};
  73043. this._postProcesses = {};
  73044. }
  73045. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73046. /**
  73047. * Checks if all the post processes in the effect are supported.
  73048. */
  73049. get: function () {
  73050. for (var index in this._postProcesses) {
  73051. if (this._postProcesses.hasOwnProperty(index)) {
  73052. var pps = this._postProcesses[index];
  73053. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73054. if (!pps[ppIndex].isSupported) {
  73055. return false;
  73056. }
  73057. }
  73058. }
  73059. }
  73060. return true;
  73061. },
  73062. enumerable: true,
  73063. configurable: true
  73064. });
  73065. /**
  73066. * Updates the current state of the effect
  73067. */
  73068. PostProcessRenderEffect.prototype._update = function () {
  73069. };
  73070. /**
  73071. * Attaches the effect on cameras
  73072. * @param cameras The camera to attach to.
  73073. */
  73074. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73075. var _this = this;
  73076. var cameraKey;
  73077. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73078. if (!cams) {
  73079. return;
  73080. }
  73081. for (var i = 0; i < cams.length; i++) {
  73082. var camera = cams[i];
  73083. var cameraName = camera.name;
  73084. if (this._singleInstance) {
  73085. cameraKey = 0;
  73086. }
  73087. else {
  73088. cameraKey = cameraName;
  73089. }
  73090. if (!this._postProcesses[cameraKey]) {
  73091. var postProcess = this._getPostProcesses();
  73092. if (postProcess) {
  73093. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73094. }
  73095. }
  73096. if (!this._indicesForCamera[cameraName]) {
  73097. this._indicesForCamera[cameraName] = [];
  73098. }
  73099. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73100. var index = camera.attachPostProcess(postProcess);
  73101. _this._indicesForCamera[cameraName].push(index);
  73102. });
  73103. if (!this._cameras[cameraName]) {
  73104. this._cameras[cameraName] = camera;
  73105. }
  73106. }
  73107. };
  73108. /**
  73109. * Detatches the effect on cameras
  73110. * @param cameras The camera to detatch from.
  73111. */
  73112. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73113. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73114. if (!cams) {
  73115. return;
  73116. }
  73117. for (var i = 0; i < cams.length; i++) {
  73118. var camera = cams[i];
  73119. var cameraName = camera.name;
  73120. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73121. camera.detachPostProcess(postProcess);
  73122. });
  73123. if (this._cameras[cameraName]) {
  73124. //this._indicesForCamera.splice(index, 1);
  73125. this._cameras[cameraName] = null;
  73126. }
  73127. }
  73128. };
  73129. /**
  73130. * Enables the effect on given cameras
  73131. * @param cameras The camera to enable.
  73132. */
  73133. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73134. var _this = this;
  73135. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73136. if (!cams) {
  73137. return;
  73138. }
  73139. for (var i = 0; i < cams.length; i++) {
  73140. var camera = cams[i];
  73141. var cameraName = camera.name;
  73142. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73143. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73144. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73145. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73146. });
  73147. }
  73148. }
  73149. }
  73150. };
  73151. /**
  73152. * Disables the effect on the given cameras
  73153. * @param cameras The camera to disable.
  73154. */
  73155. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73156. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73157. if (!cams) {
  73158. return;
  73159. }
  73160. for (var i = 0; i < cams.length; i++) {
  73161. var camera = cams[i];
  73162. var cameraName = camera.name;
  73163. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73164. camera.detachPostProcess(postProcess);
  73165. });
  73166. }
  73167. };
  73168. /**
  73169. * Gets a list of the post processes contained in the effect.
  73170. * @param camera The camera to get the post processes on.
  73171. * @returns The list of the post processes in the effect.
  73172. */
  73173. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73174. if (this._singleInstance) {
  73175. return this._postProcesses[0];
  73176. }
  73177. else {
  73178. if (!camera) {
  73179. return null;
  73180. }
  73181. return this._postProcesses[camera.name];
  73182. }
  73183. };
  73184. return PostProcessRenderEffect;
  73185. }());
  73186. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73187. })(BABYLON || (BABYLON = {}));
  73188. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73189. var BABYLON;
  73190. (function (BABYLON) {
  73191. var PostProcessRenderPipeline = /** @class */ (function () {
  73192. function PostProcessRenderPipeline(engine, name) {
  73193. this.engine = engine;
  73194. this._name = name;
  73195. this._renderEffects = {};
  73196. this._renderEffectsForIsolatedPass = new Array();
  73197. this._cameras = [];
  73198. }
  73199. PostProcessRenderPipeline.prototype.getClassName = function () {
  73200. return "PostProcessRenderPipeline";
  73201. };
  73202. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73203. get: function () {
  73204. for (var renderEffectName in this._renderEffects) {
  73205. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73206. if (!this._renderEffects[renderEffectName].isSupported) {
  73207. return false;
  73208. }
  73209. }
  73210. }
  73211. return true;
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73217. this._renderEffects[renderEffect._name] = renderEffect;
  73218. };
  73219. // private
  73220. PostProcessRenderPipeline.prototype._rebuild = function () {
  73221. };
  73222. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73223. var renderEffects = this._renderEffects[renderEffectName];
  73224. if (!renderEffects) {
  73225. return;
  73226. }
  73227. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73228. };
  73229. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73230. var renderEffects = this._renderEffects[renderEffectName];
  73231. if (!renderEffects) {
  73232. return;
  73233. }
  73234. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73235. };
  73236. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73237. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73238. if (!cams) {
  73239. return;
  73240. }
  73241. var indicesToDelete = [];
  73242. var i;
  73243. for (i = 0; i < cams.length; i++) {
  73244. var camera = cams[i];
  73245. var cameraName = camera.name;
  73246. if (this._cameras.indexOf(camera) === -1) {
  73247. this._cameras[cameraName] = camera;
  73248. }
  73249. else if (unique) {
  73250. indicesToDelete.push(i);
  73251. }
  73252. }
  73253. for (i = 0; i < indicesToDelete.length; i++) {
  73254. cameras.splice(indicesToDelete[i], 1);
  73255. }
  73256. for (var renderEffectName in this._renderEffects) {
  73257. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73258. this._renderEffects[renderEffectName]._attachCameras(cams);
  73259. }
  73260. }
  73261. };
  73262. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73263. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73264. if (!cams) {
  73265. return;
  73266. }
  73267. for (var renderEffectName in this._renderEffects) {
  73268. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73269. this._renderEffects[renderEffectName]._detachCameras(cams);
  73270. }
  73271. }
  73272. for (var i = 0; i < cams.length; i++) {
  73273. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73274. }
  73275. };
  73276. PostProcessRenderPipeline.prototype._update = function () {
  73277. for (var renderEffectName in this._renderEffects) {
  73278. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73279. this._renderEffects[renderEffectName]._update();
  73280. }
  73281. }
  73282. for (var i = 0; i < this._cameras.length; i++) {
  73283. var cameraName = this._cameras[i].name;
  73284. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73285. this._renderEffectsForIsolatedPass[cameraName]._update();
  73286. }
  73287. }
  73288. };
  73289. PostProcessRenderPipeline.prototype._reset = function () {
  73290. this._renderEffects = {};
  73291. this._renderEffectsForIsolatedPass = new Array();
  73292. };
  73293. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73294. // 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)
  73295. var effectKeys = Object.keys(this._renderEffects);
  73296. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73297. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73298. if (postProcesses) {
  73299. postProcesses[0].samples = sampleCount;
  73300. return true;
  73301. }
  73302. }
  73303. return false;
  73304. };
  73305. PostProcessRenderPipeline.prototype.dispose = function () {
  73306. // Must be implemented by children
  73307. };
  73308. __decorate([
  73309. BABYLON.serialize()
  73310. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73311. return PostProcessRenderPipeline;
  73312. }());
  73313. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73314. })(BABYLON || (BABYLON = {}));
  73315. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73316. var BABYLON;
  73317. (function (BABYLON) {
  73318. /**
  73319. * This represents a depth renderer in Babylon.
  73320. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73321. */
  73322. var DepthRenderer = /** @class */ (function () {
  73323. /**
  73324. * Instantiates a depth renderer
  73325. * @param scene The scene the renderer belongs to
  73326. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73327. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73328. */
  73329. function DepthRenderer(scene, type, camera) {
  73330. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73331. if (camera === void 0) { camera = null; }
  73332. var _this = this;
  73333. this._scene = scene;
  73334. this._camera = camera;
  73335. var engine = scene.getEngine();
  73336. // Render target
  73337. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73338. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73339. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73340. this._depthMap.refreshRate = 1;
  73341. this._depthMap.renderParticles = false;
  73342. this._depthMap.renderList = null;
  73343. // Camera to get depth map from to support multiple concurrent cameras
  73344. this._depthMap.activeCamera = this._camera;
  73345. this._depthMap.ignoreCameraViewport = true;
  73346. this._depthMap.useCameraPostProcesses = false;
  73347. // set default depth value to 1.0 (far away)
  73348. this._depthMap.onClearObservable.add(function (engine) {
  73349. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73350. });
  73351. // Custom render function
  73352. var renderSubMesh = function (subMesh) {
  73353. var mesh = subMesh.getRenderingMesh();
  73354. var scene = _this._scene;
  73355. var engine = scene.getEngine();
  73356. var material = subMesh.getMaterial();
  73357. if (!material) {
  73358. return;
  73359. }
  73360. // Culling and reverse (right handed system)
  73361. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73362. // Managing instances
  73363. var batch = mesh._getInstancesRenderList(subMesh._id);
  73364. if (batch.mustReturn) {
  73365. return;
  73366. }
  73367. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73368. var camera = _this._camera || scene.activeCamera;
  73369. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73370. engine.enableEffect(_this._effect);
  73371. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73372. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73373. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73374. // Alpha test
  73375. if (material && material.needAlphaTesting()) {
  73376. var alphaTexture = material.getAlphaTestTexture();
  73377. if (alphaTexture) {
  73378. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73379. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73380. }
  73381. }
  73382. // Bones
  73383. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73384. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73385. }
  73386. // Draw
  73387. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73388. }
  73389. };
  73390. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73391. var index;
  73392. if (depthOnlySubMeshes.length) {
  73393. engine.setColorWrite(false);
  73394. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73395. renderSubMesh(depthOnlySubMeshes.data[index]);
  73396. }
  73397. engine.setColorWrite(true);
  73398. }
  73399. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73400. renderSubMesh(opaqueSubMeshes.data[index]);
  73401. }
  73402. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73403. renderSubMesh(alphaTestSubMeshes.data[index]);
  73404. }
  73405. };
  73406. }
  73407. /**
  73408. * Creates the depth rendering effect and checks if the effect is ready.
  73409. * @param subMesh The submesh to be used to render the depth map of
  73410. * @param useInstances If multiple world instances should be used
  73411. * @returns if the depth renderer is ready to render the depth map
  73412. */
  73413. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73414. var material = subMesh.getMaterial();
  73415. if (material.disableDepthWrite) {
  73416. return false;
  73417. }
  73418. var defines = [];
  73419. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73420. var mesh = subMesh.getMesh();
  73421. // Alpha test
  73422. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73423. defines.push("#define ALPHATEST");
  73424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73425. attribs.push(BABYLON.VertexBuffer.UVKind);
  73426. defines.push("#define UV1");
  73427. }
  73428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73429. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73430. defines.push("#define UV2");
  73431. }
  73432. }
  73433. // Bones
  73434. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73437. if (mesh.numBoneInfluencers > 4) {
  73438. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73439. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73440. }
  73441. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73442. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73443. }
  73444. else {
  73445. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73446. }
  73447. // Instances
  73448. if (useInstances) {
  73449. defines.push("#define INSTANCES");
  73450. attribs.push("world0");
  73451. attribs.push("world1");
  73452. attribs.push("world2");
  73453. attribs.push("world3");
  73454. }
  73455. // Get correct effect
  73456. var join = defines.join("\n");
  73457. if (this._cachedDefines !== join) {
  73458. this._cachedDefines = join;
  73459. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73460. }
  73461. return this._effect.isReady();
  73462. };
  73463. /**
  73464. * Gets the texture which the depth map will be written to.
  73465. * @returns The depth map texture
  73466. */
  73467. DepthRenderer.prototype.getDepthMap = function () {
  73468. return this._depthMap;
  73469. };
  73470. /**
  73471. * Disposes of the depth renderer.
  73472. */
  73473. DepthRenderer.prototype.dispose = function () {
  73474. this._depthMap.dispose();
  73475. };
  73476. return DepthRenderer;
  73477. }());
  73478. BABYLON.DepthRenderer = DepthRenderer;
  73479. })(BABYLON || (BABYLON = {}));
  73480. //# sourceMappingURL=babylon.depthRenderer.js.map
  73481. var BABYLON;
  73482. (function (BABYLON) {
  73483. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73484. __extends(SSAORenderingPipeline, _super);
  73485. /**
  73486. * @constructor
  73487. * @param {string} name - The rendering pipeline name
  73488. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73489. * @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 }
  73490. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73491. */
  73492. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73493. var _this = _super.call(this, scene.getEngine(), name) || this;
  73494. // Members
  73495. /**
  73496. * The PassPostProcess id in the pipeline that contains the original scene color
  73497. */
  73498. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73499. /**
  73500. * The SSAO PostProcess id in the pipeline
  73501. */
  73502. _this.SSAORenderEffect = "SSAORenderEffect";
  73503. /**
  73504. * The horizontal blur PostProcess id in the pipeline
  73505. */
  73506. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73507. /**
  73508. * The vertical blur PostProcess id in the pipeline
  73509. */
  73510. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73511. /**
  73512. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73513. */
  73514. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73515. /**
  73516. * The output strength of the SSAO post-process. Default value is 1.0.
  73517. */
  73518. _this.totalStrength = 1.0;
  73519. /**
  73520. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73521. */
  73522. _this.radius = 0.0001;
  73523. /**
  73524. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73525. * Must not be equal to fallOff and superior to fallOff.
  73526. * Default value is 0.975
  73527. */
  73528. _this.area = 0.0075;
  73529. /**
  73530. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73531. * Must not be equal to area and inferior to area.
  73532. * Default value is 0.0
  73533. */
  73534. _this.fallOff = 0.000001;
  73535. /**
  73536. * The base color of the SSAO post-process
  73537. * The final result is "base + ssao" between [0, 1]
  73538. */
  73539. _this.base = 0.5;
  73540. _this._firstUpdate = true;
  73541. _this._scene = scene;
  73542. // Set up assets
  73543. _this._createRandomTexture();
  73544. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73545. var ssaoRatio = ratio.ssaoRatio || ratio;
  73546. var combineRatio = ratio.combineRatio || ratio;
  73547. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73548. _this._createSSAOPostProcess(ssaoRatio);
  73549. _this._createBlurPostProcess(ssaoRatio);
  73550. _this._createSSAOCombinePostProcess(combineRatio);
  73551. // Set up pipeline
  73552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73555. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73556. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73557. // Finish
  73558. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73559. if (cameras)
  73560. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73561. return _this;
  73562. }
  73563. // Public Methods
  73564. /**
  73565. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73566. */
  73567. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73568. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73569. for (var i = 0; i < this._scene.cameras.length; i++) {
  73570. var camera = this._scene.cameras[i];
  73571. this._originalColorPostProcess.dispose(camera);
  73572. this._ssaoPostProcess.dispose(camera);
  73573. this._blurHPostProcess.dispose(camera);
  73574. this._blurVPostProcess.dispose(camera);
  73575. this._ssaoCombinePostProcess.dispose(camera);
  73576. }
  73577. this._randomTexture.dispose();
  73578. if (disableDepthRender)
  73579. this._scene.disableDepthRenderer();
  73580. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73581. _super.prototype.dispose.call(this);
  73582. };
  73583. // Private Methods
  73584. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73585. var _this = this;
  73586. var size = 16;
  73587. 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);
  73588. 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);
  73589. this._blurHPostProcess.onActivateObservable.add(function () {
  73590. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73591. _this._blurHPostProcess.kernel = size * dw;
  73592. });
  73593. this._blurVPostProcess.onActivateObservable.add(function () {
  73594. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73595. _this._blurVPostProcess.kernel = size * dw;
  73596. });
  73597. };
  73598. SSAORenderingPipeline.prototype._rebuild = function () {
  73599. this._firstUpdate = true;
  73600. _super.prototype._rebuild.call(this);
  73601. };
  73602. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73603. var _this = this;
  73604. var numSamples = 16;
  73605. var sampleSphere = [
  73606. 0.5381, 0.1856, -0.4319,
  73607. 0.1379, 0.2486, 0.4430,
  73608. 0.3371, 0.5679, -0.0057,
  73609. -0.6999, -0.0451, -0.0019,
  73610. 0.0689, -0.1598, -0.8547,
  73611. 0.0560, 0.0069, -0.1843,
  73612. -0.0146, 0.1402, 0.0762,
  73613. 0.0100, -0.1924, -0.0344,
  73614. -0.3577, -0.5301, -0.4358,
  73615. -0.3169, 0.1063, 0.0158,
  73616. 0.0103, -0.5869, 0.0046,
  73617. -0.0897, -0.4940, 0.3287,
  73618. 0.7119, -0.0154, -0.0918,
  73619. -0.0533, 0.0596, -0.5411,
  73620. 0.0352, -0.0631, 0.5460,
  73621. -0.4776, 0.2847, -0.0271
  73622. ];
  73623. var samplesFactor = 1.0 / numSamples;
  73624. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73625. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73626. "area", "fallOff", "base", "range", "viewport"
  73627. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73628. this._ssaoPostProcess.onApply = function (effect) {
  73629. if (_this._firstUpdate) {
  73630. effect.setArray3("sampleSphere", sampleSphere);
  73631. effect.setFloat("samplesFactor", samplesFactor);
  73632. effect.setFloat("randTextureTiles", 4.0);
  73633. }
  73634. effect.setFloat("totalStrength", _this.totalStrength);
  73635. effect.setFloat("radius", _this.radius);
  73636. effect.setFloat("area", _this.area);
  73637. effect.setFloat("fallOff", _this.fallOff);
  73638. effect.setFloat("base", _this.base);
  73639. effect.setTexture("textureSampler", _this._depthTexture);
  73640. effect.setTexture("randomSampler", _this._randomTexture);
  73641. };
  73642. };
  73643. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73644. var _this = this;
  73645. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73646. this._ssaoCombinePostProcess.onApply = function (effect) {
  73647. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73648. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73649. };
  73650. };
  73651. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73652. var size = 512;
  73653. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73654. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73655. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73656. var context = this._randomTexture.getContext();
  73657. var rand = function (min, max) {
  73658. return Math.random() * (max - min) + min;
  73659. };
  73660. var randVector = BABYLON.Vector3.Zero();
  73661. for (var x = 0; x < size; x++) {
  73662. for (var y = 0; y < size; y++) {
  73663. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73664. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73665. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73666. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73667. context.fillRect(x, y, 1, 1);
  73668. }
  73669. }
  73670. this._randomTexture.update(false);
  73671. };
  73672. __decorate([
  73673. BABYLON.serialize()
  73674. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73675. __decorate([
  73676. BABYLON.serialize()
  73677. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73678. __decorate([
  73679. BABYLON.serialize()
  73680. ], SSAORenderingPipeline.prototype, "area", void 0);
  73681. __decorate([
  73682. BABYLON.serialize()
  73683. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73684. __decorate([
  73685. BABYLON.serialize()
  73686. ], SSAORenderingPipeline.prototype, "base", void 0);
  73687. return SSAORenderingPipeline;
  73688. }(BABYLON.PostProcessRenderPipeline));
  73689. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73690. })(BABYLON || (BABYLON = {}));
  73691. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73692. var BABYLON;
  73693. (function (BABYLON) {
  73694. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73695. __extends(SSAO2RenderingPipeline, _super);
  73696. /**
  73697. * @constructor
  73698. * @param {string} name - The rendering pipeline name
  73699. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73700. * @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 }
  73701. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73702. */
  73703. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73704. var _this = _super.call(this, scene.getEngine(), name) || this;
  73705. // Members
  73706. /**
  73707. * The PassPostProcess id in the pipeline that contains the original scene color
  73708. */
  73709. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73710. /**
  73711. * The SSAO PostProcess id in the pipeline
  73712. */
  73713. _this.SSAORenderEffect = "SSAORenderEffect";
  73714. /**
  73715. * The horizontal blur PostProcess id in the pipeline
  73716. */
  73717. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73718. /**
  73719. * The vertical blur PostProcess id in the pipeline
  73720. */
  73721. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73722. /**
  73723. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73724. */
  73725. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73726. /**
  73727. * The output strength of the SSAO post-process. Default value is 1.0.
  73728. */
  73729. _this.totalStrength = 1.0;
  73730. /**
  73731. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73732. */
  73733. _this.maxZ = 100.0;
  73734. /**
  73735. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73736. */
  73737. _this.minZAspect = 0.2;
  73738. /**
  73739. * Number of samples used for the SSAO calculations. Default value is 8
  73740. */
  73741. _this._samples = 8;
  73742. /**
  73743. * Are we using bilateral blur ?
  73744. */
  73745. _this._expensiveBlur = true;
  73746. /**
  73747. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73748. */
  73749. _this.radius = 2.0;
  73750. /**
  73751. * The base color of the SSAO post-process
  73752. * The final result is "base + ssao" between [0, 1]
  73753. */
  73754. _this.base = 0.1;
  73755. _this._firstUpdate = true;
  73756. _this._scene = scene;
  73757. _this._ratio = ratio;
  73758. if (!_this.isSupported) {
  73759. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73760. return _this;
  73761. }
  73762. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73763. var blurRatio = _this._ratio.blurRatio || ratio;
  73764. // Set up assets
  73765. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73766. _this._createRandomTexture();
  73767. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73768. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73769. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73770. _this._createSSAOPostProcess(1.0);
  73771. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73772. _this._createSSAOCombinePostProcess(blurRatio);
  73773. // Set up pipeline
  73774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73775. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73776. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73777. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73778. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73779. // Finish
  73780. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73781. if (cameras)
  73782. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73783. return _this;
  73784. }
  73785. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73786. get: function () {
  73787. return this._samples;
  73788. },
  73789. set: function (n) {
  73790. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73791. this._samples = n;
  73792. this._sampleSphere = this._generateHemisphere();
  73793. this._firstUpdate = true;
  73794. },
  73795. enumerable: true,
  73796. configurable: true
  73797. });
  73798. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73799. get: function () {
  73800. return this._expensiveBlur;
  73801. },
  73802. set: function (b) {
  73803. 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"]);
  73804. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73805. this._expensiveBlur = b;
  73806. this._firstUpdate = true;
  73807. },
  73808. enumerable: true,
  73809. configurable: true
  73810. });
  73811. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73812. /**
  73813. * Support test.
  73814. */
  73815. get: function () {
  73816. var engine = BABYLON.Engine.LastCreatedEngine;
  73817. if (!engine) {
  73818. return false;
  73819. }
  73820. return engine.getCaps().drawBuffersExtension;
  73821. },
  73822. enumerable: true,
  73823. configurable: true
  73824. });
  73825. // Public Methods
  73826. /**
  73827. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73828. */
  73829. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73830. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73831. for (var i = 0; i < this._scene.cameras.length; i++) {
  73832. var camera = this._scene.cameras[i];
  73833. this._originalColorPostProcess.dispose(camera);
  73834. this._ssaoPostProcess.dispose(camera);
  73835. this._blurHPostProcess.dispose(camera);
  73836. this._blurVPostProcess.dispose(camera);
  73837. this._ssaoCombinePostProcess.dispose(camera);
  73838. }
  73839. this._randomTexture.dispose();
  73840. if (disableGeometryBufferRenderer)
  73841. this._scene.disableGeometryBufferRenderer();
  73842. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73843. _super.prototype.dispose.call(this);
  73844. };
  73845. // Private Methods
  73846. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73847. var _this = this;
  73848. this._samplerOffsets = [];
  73849. var expensive = this.expensiveBlur;
  73850. for (var i = -8; i < 8; i++) {
  73851. this._samplerOffsets.push(i * 2 + 0.5);
  73852. }
  73853. 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");
  73854. this._blurHPostProcess.onApply = function (effect) {
  73855. if (!_this._scene.activeCamera) {
  73856. return;
  73857. }
  73858. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73859. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73860. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73861. effect.setFloat("radius", _this.radius);
  73862. effect.setTexture("depthSampler", _this._depthTexture);
  73863. if (_this._firstUpdate) {
  73864. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73865. }
  73866. };
  73867. 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");
  73868. this._blurVPostProcess.onApply = function (effect) {
  73869. if (!_this._scene.activeCamera) {
  73870. return;
  73871. }
  73872. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73873. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73874. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73875. effect.setFloat("radius", _this.radius);
  73876. effect.setTexture("depthSampler", _this._depthTexture);
  73877. if (_this._firstUpdate) {
  73878. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73879. _this._firstUpdate = false;
  73880. }
  73881. };
  73882. };
  73883. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73884. this._firstUpdate = true;
  73885. _super.prototype._rebuild.call(this);
  73886. };
  73887. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73888. var numSamples = this.samples;
  73889. var result = [];
  73890. var vector, scale;
  73891. var rand = function (min, max) {
  73892. return Math.random() * (max - min) + min;
  73893. };
  73894. var i = 0;
  73895. while (i < numSamples) {
  73896. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73897. vector.normalize();
  73898. scale = i / numSamples;
  73899. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73900. vector.scaleInPlace(scale);
  73901. result.push(vector.x, vector.y, vector.z);
  73902. i++;
  73903. }
  73904. return result;
  73905. };
  73906. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73907. var _this = this;
  73908. var numSamples = this.samples;
  73909. this._sampleSphere = this._generateHemisphere();
  73910. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73911. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73912. "base", "range", "projection", "near", "far", "texelSize",
  73913. "xViewport", "yViewport", "maxZ", "minZAspect"
  73914. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73915. this._ssaoPostProcess.onApply = function (effect) {
  73916. if (_this._firstUpdate) {
  73917. effect.setArray3("sampleSphere", _this._sampleSphere);
  73918. effect.setFloat("randTextureTiles", 4.0);
  73919. }
  73920. if (!_this._scene.activeCamera) {
  73921. return;
  73922. }
  73923. effect.setFloat("samplesFactor", 1 / _this.samples);
  73924. effect.setFloat("totalStrength", _this.totalStrength);
  73925. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73926. effect.setFloat("radius", _this.radius);
  73927. effect.setFloat("maxZ", _this.maxZ);
  73928. effect.setFloat("minZAspect", _this.minZAspect);
  73929. effect.setFloat("base", _this.base);
  73930. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73931. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73932. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73933. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73934. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73935. effect.setTexture("textureSampler", _this._depthTexture);
  73936. effect.setTexture("normalSampler", _this._normalTexture);
  73937. effect.setTexture("randomSampler", _this._randomTexture);
  73938. };
  73939. };
  73940. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73941. var _this = this;
  73942. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73943. this._ssaoCombinePostProcess.onApply = function (effect) {
  73944. var viewport = _this._scene.activeCamera.viewport;
  73945. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73946. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73947. };
  73948. };
  73949. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73950. var size = 512;
  73951. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73952. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73953. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73954. var context = this._randomTexture.getContext();
  73955. var rand = function (min, max) {
  73956. return Math.random() * (max - min) + min;
  73957. };
  73958. var randVector = BABYLON.Vector3.Zero();
  73959. for (var x = 0; x < size; x++) {
  73960. for (var y = 0; y < size; y++) {
  73961. randVector.x = rand(0.0, 1.0);
  73962. randVector.y = rand(0.0, 1.0);
  73963. randVector.z = 0.0;
  73964. randVector.normalize();
  73965. randVector.scaleInPlace(255);
  73966. randVector.x = Math.floor(randVector.x);
  73967. randVector.y = Math.floor(randVector.y);
  73968. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73969. context.fillRect(x, y, 1, 1);
  73970. }
  73971. }
  73972. this._randomTexture.update(false);
  73973. };
  73974. /**
  73975. * Serialize the rendering pipeline (Used when exporting)
  73976. * @returns the serialized object
  73977. */
  73978. SSAO2RenderingPipeline.prototype.serialize = function () {
  73979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73980. serializationObject.customType = "SSAO2RenderingPipeline";
  73981. return serializationObject;
  73982. };
  73983. /**
  73984. * Parse the serialized pipeline
  73985. * @param source Source pipeline.
  73986. * @param scene The scene to load the pipeline to.
  73987. * @param rootUrl The URL of the serialized pipeline.
  73988. * @returns An instantiated pipeline from the serialized object.
  73989. */
  73990. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73991. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73992. };
  73993. __decorate([
  73994. BABYLON.serialize()
  73995. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73996. __decorate([
  73997. BABYLON.serialize()
  73998. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73999. __decorate([
  74000. BABYLON.serialize()
  74001. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74002. __decorate([
  74003. BABYLON.serialize("samples")
  74004. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74005. __decorate([
  74006. BABYLON.serialize()
  74007. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74008. __decorate([
  74009. BABYLON.serialize("expensiveBlur")
  74010. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74011. __decorate([
  74012. BABYLON.serialize()
  74013. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74014. __decorate([
  74015. BABYLON.serialize()
  74016. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74017. return SSAO2RenderingPipeline;
  74018. }(BABYLON.PostProcessRenderPipeline));
  74019. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74020. })(BABYLON || (BABYLON = {}));
  74021. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74022. // BABYLON.JS Chromatic Aberration GLSL Shader
  74023. // Author: Olivier Guyot
  74024. // Separates very slightly R, G and B colors on the edges of the screen
  74025. // Inspired by Francois Tarlier & Martins Upitis
  74026. var BABYLON;
  74027. (function (BABYLON) {
  74028. var LensRenderingPipeline = /** @class */ (function (_super) {
  74029. __extends(LensRenderingPipeline, _super);
  74030. /**
  74031. * @constructor
  74032. *
  74033. * Effect parameters are as follow:
  74034. * {
  74035. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74036. * edge_blur: number; // from 0 to x (1 for realism)
  74037. * distortion: number; // from 0 to x (1 for realism)
  74038. * grain_amount: number; // from 0 to 1
  74039. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74040. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74041. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74042. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74043. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74044. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74045. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74046. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74047. * }
  74048. * Note: if an effect parameter is unset, effect is disabled
  74049. *
  74050. * @param {string} name - The rendering pipeline name
  74051. * @param {object} parameters - An object containing all parameters (see above)
  74052. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74053. * @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)
  74054. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74055. */
  74056. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74057. if (ratio === void 0) { ratio = 1.0; }
  74058. var _this = _super.call(this, scene.getEngine(), name) || this;
  74059. // Lens effects can be of the following:
  74060. // - chromatic aberration (slight shift of RGB colors)
  74061. // - blur on the edge of the lens
  74062. // - lens distortion
  74063. // - depth-of-field blur & highlights enhancing
  74064. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74065. // - grain effect (noise or custom texture)
  74066. // Two additional texture samplers are needed:
  74067. // - depth map (for depth-of-field)
  74068. // - grain texture
  74069. /**
  74070. * The chromatic aberration PostProcess id in the pipeline
  74071. */
  74072. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74073. /**
  74074. * The highlights enhancing PostProcess id in the pipeline
  74075. */
  74076. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74077. /**
  74078. * The depth-of-field PostProcess id in the pipeline
  74079. */
  74080. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74081. _this._scene = scene;
  74082. // Fetch texture samplers
  74083. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74084. if (parameters.grain_texture) {
  74085. _this._grainTexture = parameters.grain_texture;
  74086. }
  74087. else {
  74088. _this._createGrainTexture();
  74089. }
  74090. // save parameters
  74091. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74092. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74093. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74094. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74095. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74096. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74097. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74098. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74099. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74100. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74101. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74102. // Create effects
  74103. _this._createChromaticAberrationPostProcess(ratio);
  74104. _this._createHighlightsPostProcess(ratio);
  74105. _this._createDepthOfFieldPostProcess(ratio / 4);
  74106. // Set up pipeline
  74107. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74108. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74110. if (_this._highlightsGain === -1) {
  74111. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74112. }
  74113. // Finish
  74114. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74115. if (cameras) {
  74116. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74117. }
  74118. return _this;
  74119. }
  74120. // public methods (self explanatory)
  74121. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74122. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74123. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74124. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74125. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74126. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74127. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74128. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74129. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74130. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74131. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74132. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74133. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74134. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74135. };
  74136. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74137. this._highlightsPostProcess.updateEffect();
  74138. };
  74139. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74140. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74141. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74142. this._highlightsGain = amount;
  74143. };
  74144. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74145. if (this._highlightsGain === -1) {
  74146. this._highlightsGain = 1.0;
  74147. }
  74148. this._highlightsThreshold = amount;
  74149. };
  74150. LensRenderingPipeline.prototype.disableHighlights = function () {
  74151. this._highlightsGain = -1;
  74152. };
  74153. /**
  74154. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74155. */
  74156. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74157. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74158. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74159. this._chromaticAberrationPostProcess = null;
  74160. this._highlightsPostProcess = null;
  74161. this._depthOfFieldPostProcess = null;
  74162. this._grainTexture.dispose();
  74163. if (disableDepthRender)
  74164. this._scene.disableDepthRenderer();
  74165. };
  74166. // colors shifting and distortion
  74167. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74168. var _this = this;
  74169. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74170. [], // samplers
  74171. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74172. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74173. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74174. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74175. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74176. effect.setFloat('radialIntensity', 1);
  74177. effect.setFloat2('direction', 17, 17);
  74178. effect.setFloat2('centerPosition', 0.5, 0.5);
  74179. };
  74180. };
  74181. // highlights enhancing
  74182. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74183. var _this = this;
  74184. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74185. [], // samplers
  74186. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74187. this._highlightsPostProcess.onApply = function (effect) {
  74188. effect.setFloat('gain', _this._highlightsGain);
  74189. effect.setFloat('threshold', _this._highlightsThreshold);
  74190. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74191. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74192. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74193. };
  74194. };
  74195. // colors shifting and distortion
  74196. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74197. var _this = this;
  74198. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74199. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74200. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74201. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74202. this._depthOfFieldPostProcess.onApply = function (effect) {
  74203. effect.setTexture("depthSampler", _this._depthTexture);
  74204. effect.setTexture("grainSampler", _this._grainTexture);
  74205. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74206. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74207. effect.setFloat('grain_amount', _this._grainAmount);
  74208. effect.setBool('blur_noise', _this._blurNoise);
  74209. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74210. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74211. effect.setFloat('distortion', _this._distortion);
  74212. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74213. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74214. effect.setFloat('aperture', _this._dofAperture);
  74215. effect.setFloat('darken', _this._dofDarken);
  74216. effect.setFloat('edge_blur', _this._edgeBlur);
  74217. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74218. if (_this._scene.activeCamera) {
  74219. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74220. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74221. }
  74222. };
  74223. };
  74224. // creates a black and white random noise texture, 512x512
  74225. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74226. var size = 512;
  74227. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74228. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74229. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74230. var context = this._grainTexture.getContext();
  74231. var rand = function (min, max) {
  74232. return Math.random() * (max - min) + min;
  74233. };
  74234. var value;
  74235. for (var x = 0; x < size; x++) {
  74236. for (var y = 0; y < size; y++) {
  74237. value = Math.floor(rand(0.42, 0.58) * 255);
  74238. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74239. context.fillRect(x, y, 1, 1);
  74240. }
  74241. }
  74242. this._grainTexture.update(false);
  74243. };
  74244. return LensRenderingPipeline;
  74245. }(BABYLON.PostProcessRenderPipeline));
  74246. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74247. })(BABYLON || (BABYLON = {}));
  74248. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74249. var BABYLON;
  74250. (function (BABYLON) {
  74251. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74252. __extends(StandardRenderingPipeline, _super);
  74253. /**
  74254. * @constructor
  74255. * @param {string} name - The rendering pipeline name
  74256. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74257. * @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)
  74258. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74259. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74260. */
  74261. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74262. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74263. var _this = _super.call(this, scene.getEngine(), name) || this;
  74264. _this.downSampleX4PostProcess = null;
  74265. _this.brightPassPostProcess = null;
  74266. _this.blurHPostProcesses = [];
  74267. _this.blurVPostProcesses = [];
  74268. _this.textureAdderPostProcess = null;
  74269. _this.volumetricLightPostProcess = null;
  74270. _this.volumetricLightSmoothXPostProcess = null;
  74271. _this.volumetricLightSmoothYPostProcess = null;
  74272. _this.volumetricLightMergePostProces = null;
  74273. _this.volumetricLightFinalPostProcess = null;
  74274. _this.luminancePostProcess = null;
  74275. _this.luminanceDownSamplePostProcesses = [];
  74276. _this.hdrPostProcess = null;
  74277. _this.textureAdderFinalPostProcess = null;
  74278. _this.lensFlareFinalPostProcess = null;
  74279. _this.hdrFinalPostProcess = null;
  74280. _this.lensFlarePostProcess = null;
  74281. _this.lensFlareComposePostProcess = null;
  74282. _this.motionBlurPostProcess = null;
  74283. _this.depthOfFieldPostProcess = null;
  74284. // Values
  74285. _this.brightThreshold = 1.0;
  74286. _this.blurWidth = 512.0;
  74287. _this.horizontalBlur = false;
  74288. _this.exposure = 1.0;
  74289. _this.lensTexture = null;
  74290. _this.volumetricLightCoefficient = 0.2;
  74291. _this.volumetricLightPower = 4.0;
  74292. _this.volumetricLightBlurScale = 64.0;
  74293. _this.sourceLight = null;
  74294. _this.hdrMinimumLuminance = 1.0;
  74295. _this.hdrDecreaseRate = 0.5;
  74296. _this.hdrIncreaseRate = 0.5;
  74297. _this.lensColorTexture = null;
  74298. _this.lensFlareStrength = 20.0;
  74299. _this.lensFlareGhostDispersal = 1.4;
  74300. _this.lensFlareHaloWidth = 0.7;
  74301. _this.lensFlareDistortionStrength = 16.0;
  74302. _this.lensStarTexture = null;
  74303. _this.lensFlareDirtTexture = null;
  74304. _this.depthOfFieldDistance = 10.0;
  74305. _this.depthOfFieldBlurWidth = 64.0;
  74306. _this.motionStrength = 1.0;
  74307. // IAnimatable
  74308. _this.animations = [];
  74309. _this._currentDepthOfFieldSource = null;
  74310. _this._hdrCurrentLuminance = 1.0;
  74311. // Getters and setters
  74312. _this._bloomEnabled = true;
  74313. _this._depthOfFieldEnabled = false;
  74314. _this._vlsEnabled = false;
  74315. _this._lensFlareEnabled = false;
  74316. _this._hdrEnabled = false;
  74317. _this._motionBlurEnabled = false;
  74318. _this._motionBlurSamples = 64.0;
  74319. _this._volumetricLightStepsCount = 50.0;
  74320. _this._cameras = cameras || [];
  74321. // Initialize
  74322. _this._scene = scene;
  74323. _this._basePostProcess = originalPostProcess;
  74324. _this._ratio = ratio;
  74325. // Misc
  74326. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74327. // Finish
  74328. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74329. _this._buildPipeline();
  74330. return _this;
  74331. }
  74332. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74333. get: function () {
  74334. return this._bloomEnabled;
  74335. },
  74336. set: function (enabled) {
  74337. if (this._bloomEnabled === enabled) {
  74338. return;
  74339. }
  74340. this._bloomEnabled = enabled;
  74341. this._buildPipeline();
  74342. },
  74343. enumerable: true,
  74344. configurable: true
  74345. });
  74346. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74347. get: function () {
  74348. return this._depthOfFieldEnabled;
  74349. },
  74350. set: function (enabled) {
  74351. if (this._depthOfFieldEnabled === enabled) {
  74352. return;
  74353. }
  74354. this._depthOfFieldEnabled = enabled;
  74355. this._buildPipeline();
  74356. },
  74357. enumerable: true,
  74358. configurable: true
  74359. });
  74360. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74361. get: function () {
  74362. return this._lensFlareEnabled;
  74363. },
  74364. set: function (enabled) {
  74365. if (this._lensFlareEnabled === enabled) {
  74366. return;
  74367. }
  74368. this._lensFlareEnabled = enabled;
  74369. this._buildPipeline();
  74370. },
  74371. enumerable: true,
  74372. configurable: true
  74373. });
  74374. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74375. get: function () {
  74376. return this._hdrEnabled;
  74377. },
  74378. set: function (enabled) {
  74379. if (this._hdrEnabled === enabled) {
  74380. return;
  74381. }
  74382. this._hdrEnabled = enabled;
  74383. this._buildPipeline();
  74384. },
  74385. enumerable: true,
  74386. configurable: true
  74387. });
  74388. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74389. get: function () {
  74390. return this._vlsEnabled;
  74391. },
  74392. set: function (enabled) {
  74393. if (this._vlsEnabled === enabled) {
  74394. return;
  74395. }
  74396. if (enabled) {
  74397. var geometry = this._scene.enableGeometryBufferRenderer();
  74398. if (!geometry) {
  74399. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74400. return;
  74401. }
  74402. }
  74403. this._vlsEnabled = enabled;
  74404. this._buildPipeline();
  74405. },
  74406. enumerable: true,
  74407. configurable: true
  74408. });
  74409. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74410. get: function () {
  74411. return this._motionBlurEnabled;
  74412. },
  74413. set: function (enabled) {
  74414. if (this._motionBlurEnabled === enabled) {
  74415. return;
  74416. }
  74417. this._motionBlurEnabled = enabled;
  74418. this._buildPipeline();
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74424. get: function () {
  74425. return this._volumetricLightStepsCount;
  74426. },
  74427. set: function (count) {
  74428. if (this.volumetricLightPostProcess) {
  74429. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74430. }
  74431. this._volumetricLightStepsCount = count;
  74432. },
  74433. enumerable: true,
  74434. configurable: true
  74435. });
  74436. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74437. get: function () {
  74438. return this._motionBlurSamples;
  74439. },
  74440. set: function (samples) {
  74441. if (this.motionBlurPostProcess) {
  74442. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74443. }
  74444. this._motionBlurSamples = samples;
  74445. },
  74446. enumerable: true,
  74447. configurable: true
  74448. });
  74449. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74450. var _this = this;
  74451. var ratio = this._ratio;
  74452. var scene = this._scene;
  74453. this._disposePostProcesses();
  74454. this._reset();
  74455. // Create pass post-process
  74456. if (!this._basePostProcess) {
  74457. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74458. this.originalPostProcess.onApply = function (effect) {
  74459. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74460. };
  74461. }
  74462. else {
  74463. this.originalPostProcess = this._basePostProcess;
  74464. }
  74465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74466. this._currentDepthOfFieldSource = this.originalPostProcess;
  74467. if (this._bloomEnabled) {
  74468. // Create down sample X4 post-process
  74469. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74470. // Create bright pass post-process
  74471. this._createBrightPassPostProcess(scene, ratio / 2);
  74472. // Create gaussian blur post-processes (down sampling blurs)
  74473. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74474. // Create texture adder post-process
  74475. this._createTextureAdderPostProcess(scene, ratio);
  74476. // Create depth-of-field source post-process
  74477. 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);
  74478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74479. }
  74480. if (this._vlsEnabled) {
  74481. // Create volumetric light
  74482. this._createVolumetricLightPostProcess(scene, ratio);
  74483. // Create volumetric light final post-process
  74484. 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);
  74485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74486. }
  74487. if (this._lensFlareEnabled) {
  74488. // Create lens flare post-process
  74489. this._createLensFlarePostProcess(scene, ratio);
  74490. // Create depth-of-field source post-process post lens-flare and disable it now
  74491. 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);
  74492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74493. }
  74494. if (this._hdrEnabled) {
  74495. // Create luminance
  74496. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74497. // Create HDR
  74498. this._createHdrPostProcess(scene, ratio);
  74499. // Create depth-of-field source post-process post hdr and disable it now
  74500. 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);
  74501. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74502. }
  74503. if (this._depthOfFieldEnabled) {
  74504. // Create gaussian blur used by depth-of-field
  74505. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74506. // Create depth-of-field post-process
  74507. this._createDepthOfFieldPostProcess(scene, ratio);
  74508. }
  74509. if (this._motionBlurEnabled) {
  74510. // Create motion blur post-process
  74511. this._createMotionBlurPostProcess(scene, ratio);
  74512. }
  74513. if (this._cameras !== null) {
  74514. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74515. }
  74516. };
  74517. // Down Sample X4 Post-Processs
  74518. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74519. var _this = this;
  74520. var downSampleX4Offsets = new Array(32);
  74521. 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);
  74522. this.downSampleX4PostProcess.onApply = function (effect) {
  74523. var id = 0;
  74524. var width = _this.downSampleX4PostProcess.width;
  74525. var height = _this.downSampleX4PostProcess.height;
  74526. for (var i = -2; i < 2; i++) {
  74527. for (var j = -2; j < 2; j++) {
  74528. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74529. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74530. id += 2;
  74531. }
  74532. }
  74533. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74534. };
  74535. // Add to pipeline
  74536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74537. };
  74538. // Brightpass Post-Process
  74539. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74540. var _this = this;
  74541. var brightOffsets = new Array(8);
  74542. 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);
  74543. this.brightPassPostProcess.onApply = function (effect) {
  74544. var sU = (1.0 / _this.brightPassPostProcess.width);
  74545. var sV = (1.0 / _this.brightPassPostProcess.height);
  74546. brightOffsets[0] = -0.5 * sU;
  74547. brightOffsets[1] = 0.5 * sV;
  74548. brightOffsets[2] = 0.5 * sU;
  74549. brightOffsets[3] = 0.5 * sV;
  74550. brightOffsets[4] = -0.5 * sU;
  74551. brightOffsets[5] = -0.5 * sV;
  74552. brightOffsets[6] = 0.5 * sU;
  74553. brightOffsets[7] = -0.5 * sV;
  74554. effect.setArray2("dsOffsets", brightOffsets);
  74555. effect.setFloat("brightThreshold", _this.brightThreshold);
  74556. };
  74557. // Add to pipeline
  74558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74559. };
  74560. // Create blur H&V post-processes
  74561. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74562. var _this = this;
  74563. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74564. var engine = scene.getEngine();
  74565. 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);
  74566. 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);
  74567. blurX.onActivateObservable.add(function () {
  74568. var dw = blurX.width / engine.getRenderWidth();
  74569. blurX.kernel = _this[blurWidthKey] * dw;
  74570. });
  74571. blurY.onActivateObservable.add(function () {
  74572. var dw = blurY.height / engine.getRenderHeight();
  74573. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74574. });
  74575. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74576. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74577. this.blurHPostProcesses.push(blurX);
  74578. this.blurVPostProcesses.push(blurY);
  74579. };
  74580. // Create texture adder post-process
  74581. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74582. var _this = this;
  74583. 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);
  74584. this.textureAdderPostProcess.onApply = function (effect) {
  74585. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74586. effect.setTexture("lensSampler", _this.lensTexture);
  74587. effect.setFloat("exposure", _this.exposure);
  74588. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74589. };
  74590. // Add to pipeline
  74591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74592. };
  74593. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74594. var _this = this;
  74595. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74596. geometryRenderer.enablePosition = true;
  74597. var geometry = geometryRenderer.getGBuffer();
  74598. // Base post-process
  74599. 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));
  74600. var depthValues = BABYLON.Vector2.Zero();
  74601. this.volumetricLightPostProcess.onApply = function (effect) {
  74602. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74603. var generator = _this.sourceLight.getShadowGenerator();
  74604. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74605. effect.setTexture("positionSampler", geometry.textures[2]);
  74606. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74607. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74608. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74609. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74610. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74611. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74612. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74613. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74614. effect.setVector2("depthValues", depthValues);
  74615. }
  74616. };
  74617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74618. // Smooth
  74619. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74620. // Merge
  74621. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74622. this.volumetricLightMergePostProces.onApply = function (effect) {
  74623. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74624. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74625. };
  74626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74627. };
  74628. // Create luminance
  74629. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74630. var _this = this;
  74631. // Create luminance
  74632. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74633. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74634. var offsets = [];
  74635. this.luminancePostProcess.onApply = function (effect) {
  74636. var sU = (1.0 / _this.luminancePostProcess.width);
  74637. var sV = (1.0 / _this.luminancePostProcess.height);
  74638. offsets[0] = -0.5 * sU;
  74639. offsets[1] = 0.5 * sV;
  74640. offsets[2] = 0.5 * sU;
  74641. offsets[3] = 0.5 * sV;
  74642. offsets[4] = -0.5 * sU;
  74643. offsets[5] = -0.5 * sV;
  74644. offsets[6] = 0.5 * sU;
  74645. offsets[7] = -0.5 * sV;
  74646. effect.setArray2("lumOffsets", offsets);
  74647. };
  74648. // Add to pipeline
  74649. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74650. // Create down sample luminance
  74651. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74652. var size = Math.pow(3, i);
  74653. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74654. if (i === 0) {
  74655. defines += "#define FINAL_DOWN_SAMPLER";
  74656. }
  74657. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74658. this.luminanceDownSamplePostProcesses.push(postProcess);
  74659. }
  74660. // Create callbacks and add effects
  74661. var lastLuminance = this.luminancePostProcess;
  74662. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74663. var downSampleOffsets = new Array(18);
  74664. pp.onApply = function (effect) {
  74665. if (!lastLuminance) {
  74666. return;
  74667. }
  74668. var id = 0;
  74669. for (var x = -1; x < 2; x++) {
  74670. for (var y = -1; y < 2; y++) {
  74671. downSampleOffsets[id] = x / lastLuminance.width;
  74672. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74673. id += 2;
  74674. }
  74675. }
  74676. effect.setArray2("dsOffsets", downSampleOffsets);
  74677. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74678. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74679. lastLuminance = _this.luminancePostProcess;
  74680. }
  74681. else {
  74682. lastLuminance = pp;
  74683. }
  74684. };
  74685. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74686. pp.onAfterRender = function (effect) {
  74687. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74688. 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);
  74689. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74690. };
  74691. }
  74692. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74693. });
  74694. };
  74695. // Create HDR post-process
  74696. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74697. var _this = this;
  74698. 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);
  74699. var outputLiminance = 1;
  74700. var time = 0;
  74701. var lastTime = 0;
  74702. this.hdrPostProcess.onApply = function (effect) {
  74703. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74704. time += scene.getEngine().getDeltaTime();
  74705. if (outputLiminance < 0) {
  74706. outputLiminance = _this._hdrCurrentLuminance;
  74707. }
  74708. else {
  74709. var dt = (lastTime - time) / 1000.0;
  74710. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74711. outputLiminance += _this.hdrDecreaseRate * dt;
  74712. }
  74713. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74714. outputLiminance -= _this.hdrIncreaseRate * dt;
  74715. }
  74716. else {
  74717. outputLiminance = _this._hdrCurrentLuminance;
  74718. }
  74719. }
  74720. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74721. effect.setFloat("averageLuminance", outputLiminance);
  74722. lastTime = time;
  74723. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74724. };
  74725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74726. };
  74727. // Create lens flare post-process
  74728. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74729. var _this = this;
  74730. 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);
  74731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74732. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74733. 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);
  74734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74735. var resolution = new BABYLON.Vector2(0, 0);
  74736. // Lens flare
  74737. this.lensFlarePostProcess.onApply = function (effect) {
  74738. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74739. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74740. effect.setFloat("strength", _this.lensFlareStrength);
  74741. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74742. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74743. // Shift
  74744. resolution.x = _this.lensFlarePostProcess.width;
  74745. resolution.y = _this.lensFlarePostProcess.height;
  74746. effect.setVector2("resolution", resolution);
  74747. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74748. };
  74749. // Compose
  74750. 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);
  74751. 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);
  74752. this.lensFlareComposePostProcess.onApply = function (effect) {
  74753. if (!_this._scene.activeCamera) {
  74754. return;
  74755. }
  74756. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74757. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74758. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74759. // Lens start rotation matrix
  74760. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74761. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74762. 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));
  74763. camRot *= 4.0;
  74764. 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);
  74765. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74766. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74767. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74768. };
  74769. };
  74770. // Create depth-of-field post-process
  74771. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74772. var _this = this;
  74773. 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);
  74774. this.depthOfFieldPostProcess.onApply = function (effect) {
  74775. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74776. effect.setTexture("depthSampler", _this._getDepthTexture());
  74777. effect.setFloat("distance", _this.depthOfFieldDistance);
  74778. };
  74779. // Add to pipeline
  74780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74781. };
  74782. // Create motion blur post-process
  74783. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74784. var _this = this;
  74785. 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);
  74786. var motionScale = 0;
  74787. var prevViewProjection = BABYLON.Matrix.Identity();
  74788. var invViewProjection = BABYLON.Matrix.Identity();
  74789. var viewProjection = BABYLON.Matrix.Identity();
  74790. var screenSize = BABYLON.Vector2.Zero();
  74791. this.motionBlurPostProcess.onApply = function (effect) {
  74792. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74793. viewProjection.invertToRef(invViewProjection);
  74794. effect.setMatrix("inverseViewProjection", invViewProjection);
  74795. effect.setMatrix("prevViewProjection", prevViewProjection);
  74796. prevViewProjection = viewProjection;
  74797. screenSize.x = _this.motionBlurPostProcess.width;
  74798. screenSize.y = _this.motionBlurPostProcess.height;
  74799. effect.setVector2("screenSize", screenSize);
  74800. motionScale = scene.getEngine().getFps() / 60.0;
  74801. effect.setFloat("motionScale", motionScale);
  74802. effect.setFloat("motionStrength", _this.motionStrength);
  74803. effect.setTexture("depthSampler", _this._getDepthTexture());
  74804. };
  74805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74806. };
  74807. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74808. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74809. var renderer = this._scene.enableGeometryBufferRenderer();
  74810. return renderer.getGBuffer().textures[0];
  74811. }
  74812. return this._scene.enableDepthRenderer().getDepthMap();
  74813. };
  74814. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74815. for (var i = 0; i < this._cameras.length; i++) {
  74816. var camera = this._cameras[i];
  74817. if (this.originalPostProcess) {
  74818. this.originalPostProcess.dispose(camera);
  74819. }
  74820. if (this.downSampleX4PostProcess) {
  74821. this.downSampleX4PostProcess.dispose(camera);
  74822. }
  74823. if (this.brightPassPostProcess) {
  74824. this.brightPassPostProcess.dispose(camera);
  74825. }
  74826. if (this.textureAdderPostProcess) {
  74827. this.textureAdderPostProcess.dispose(camera);
  74828. }
  74829. if (this.textureAdderFinalPostProcess) {
  74830. this.textureAdderFinalPostProcess.dispose(camera);
  74831. }
  74832. if (this.volumetricLightPostProcess) {
  74833. this.volumetricLightPostProcess.dispose(camera);
  74834. }
  74835. if (this.volumetricLightSmoothXPostProcess) {
  74836. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74837. }
  74838. if (this.volumetricLightSmoothYPostProcess) {
  74839. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74840. }
  74841. if (this.volumetricLightMergePostProces) {
  74842. this.volumetricLightMergePostProces.dispose(camera);
  74843. }
  74844. if (this.volumetricLightFinalPostProcess) {
  74845. this.volumetricLightFinalPostProcess.dispose(camera);
  74846. }
  74847. if (this.lensFlarePostProcess) {
  74848. this.lensFlarePostProcess.dispose(camera);
  74849. }
  74850. if (this.lensFlareComposePostProcess) {
  74851. this.lensFlareComposePostProcess.dispose(camera);
  74852. }
  74853. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74854. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74855. }
  74856. if (this.luminancePostProcess) {
  74857. this.luminancePostProcess.dispose(camera);
  74858. }
  74859. if (this.hdrPostProcess) {
  74860. this.hdrPostProcess.dispose(camera);
  74861. }
  74862. if (this.hdrFinalPostProcess) {
  74863. this.hdrFinalPostProcess.dispose(camera);
  74864. }
  74865. if (this.depthOfFieldPostProcess) {
  74866. this.depthOfFieldPostProcess.dispose(camera);
  74867. }
  74868. if (this.motionBlurPostProcess) {
  74869. this.motionBlurPostProcess.dispose(camera);
  74870. }
  74871. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74872. this.blurHPostProcesses[j].dispose(camera);
  74873. }
  74874. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74875. this.blurVPostProcesses[j].dispose(camera);
  74876. }
  74877. }
  74878. this.originalPostProcess = null;
  74879. this.downSampleX4PostProcess = null;
  74880. this.brightPassPostProcess = null;
  74881. this.textureAdderPostProcess = null;
  74882. this.textureAdderFinalPostProcess = null;
  74883. this.volumetricLightPostProcess = null;
  74884. this.volumetricLightSmoothXPostProcess = null;
  74885. this.volumetricLightSmoothYPostProcess = null;
  74886. this.volumetricLightMergePostProces = null;
  74887. this.volumetricLightFinalPostProcess = null;
  74888. this.lensFlarePostProcess = null;
  74889. this.lensFlareComposePostProcess = null;
  74890. this.luminancePostProcess = null;
  74891. this.hdrPostProcess = null;
  74892. this.hdrFinalPostProcess = null;
  74893. this.depthOfFieldPostProcess = null;
  74894. this.motionBlurPostProcess = null;
  74895. this.luminanceDownSamplePostProcesses = [];
  74896. this.blurHPostProcesses = [];
  74897. this.blurVPostProcesses = [];
  74898. };
  74899. /**
  74900. * Dispose of the pipeline and stop all post processes
  74901. */
  74902. StandardRenderingPipeline.prototype.dispose = function () {
  74903. this._disposePostProcesses();
  74904. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74905. _super.prototype.dispose.call(this);
  74906. };
  74907. /**
  74908. * Serialize the rendering pipeline (Used when exporting)
  74909. * @returns the serialized object
  74910. */
  74911. StandardRenderingPipeline.prototype.serialize = function () {
  74912. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74913. if (this.sourceLight) {
  74914. serializationObject.sourceLightId = this.sourceLight.id;
  74915. }
  74916. serializationObject.customType = "StandardRenderingPipeline";
  74917. return serializationObject;
  74918. };
  74919. /**
  74920. * Parse the serialized pipeline
  74921. * @param source Source pipeline.
  74922. * @param scene The scene to load the pipeline to.
  74923. * @param rootUrl The URL of the serialized pipeline.
  74924. * @returns An instantiated pipeline from the serialized object.
  74925. */
  74926. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74927. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74928. if (source.sourceLightId) {
  74929. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74930. }
  74931. return p;
  74932. };
  74933. // Luminance steps
  74934. StandardRenderingPipeline.LuminanceSteps = 6;
  74935. __decorate([
  74936. BABYLON.serialize()
  74937. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74938. __decorate([
  74939. BABYLON.serialize()
  74940. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74941. __decorate([
  74942. BABYLON.serialize()
  74943. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74944. __decorate([
  74945. BABYLON.serialize()
  74946. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74947. __decorate([
  74948. BABYLON.serializeAsTexture("lensTexture")
  74949. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74950. __decorate([
  74951. BABYLON.serialize()
  74952. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74953. __decorate([
  74954. BABYLON.serialize()
  74955. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74956. __decorate([
  74957. BABYLON.serialize()
  74958. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74959. __decorate([
  74960. BABYLON.serialize()
  74961. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74962. __decorate([
  74963. BABYLON.serialize()
  74964. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74965. __decorate([
  74966. BABYLON.serialize()
  74967. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74968. __decorate([
  74969. BABYLON.serializeAsTexture("lensColorTexture")
  74970. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74971. __decorate([
  74972. BABYLON.serialize()
  74973. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74974. __decorate([
  74975. BABYLON.serialize()
  74976. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74977. __decorate([
  74978. BABYLON.serialize()
  74979. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74980. __decorate([
  74981. BABYLON.serialize()
  74982. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74983. __decorate([
  74984. BABYLON.serializeAsTexture("lensStarTexture")
  74985. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74986. __decorate([
  74987. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74988. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74989. __decorate([
  74990. BABYLON.serialize()
  74991. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74992. __decorate([
  74993. BABYLON.serialize()
  74994. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74995. __decorate([
  74996. BABYLON.serialize()
  74997. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74998. __decorate([
  74999. BABYLON.serialize()
  75000. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75001. __decorate([
  75002. BABYLON.serialize()
  75003. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75004. __decorate([
  75005. BABYLON.serialize()
  75006. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75007. __decorate([
  75008. BABYLON.serialize()
  75009. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75010. __decorate([
  75011. BABYLON.serialize()
  75012. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75013. __decorate([
  75014. BABYLON.serialize()
  75015. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75016. __decorate([
  75017. BABYLON.serialize()
  75018. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75019. __decorate([
  75020. BABYLON.serialize()
  75021. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75022. __decorate([
  75023. BABYLON.serialize()
  75024. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75025. return StandardRenderingPipeline;
  75026. }(BABYLON.PostProcessRenderPipeline));
  75027. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75028. })(BABYLON || (BABYLON = {}));
  75029. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75030. var BABYLON;
  75031. (function (BABYLON) {
  75032. var FxaaPostProcess = /** @class */ (function (_super) {
  75033. __extends(FxaaPostProcess, _super);
  75034. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75035. if (camera === void 0) { camera = null; }
  75036. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75037. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75038. var defines = _this._getDefines();
  75039. _this.updateEffect(defines);
  75040. _this.onApplyObservable.add(function (effect) {
  75041. var texelSize = _this.texelSize;
  75042. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75043. });
  75044. return _this;
  75045. }
  75046. FxaaPostProcess.prototype._getDefines = function () {
  75047. var engine = this.getEngine();
  75048. if (!engine) {
  75049. return null;
  75050. }
  75051. var glInfo = engine.getGlInfo();
  75052. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75053. return "#define MALI 1\n";
  75054. }
  75055. return null;
  75056. };
  75057. return FxaaPostProcess;
  75058. }(BABYLON.PostProcess));
  75059. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75060. })(BABYLON || (BABYLON = {}));
  75061. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75062. var BABYLON;
  75063. (function (BABYLON) {
  75064. /**
  75065. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75066. */
  75067. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75068. __extends(ChromaticAberrationPostProcess, _super);
  75069. /**
  75070. * Creates a new instance ChromaticAberrationPostProcess
  75071. * @param name The name of the effect.
  75072. * @param screenWidth The width of the screen to apply the effect on.
  75073. * @param screenHeight The height of the screen to apply the effect on.
  75074. * @param options The required width/height ratio to downsize to before computing the render pass.
  75075. * @param camera The camera to apply the render pass to.
  75076. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75077. * @param engine The engine which the post process will be applied. (default: current engine)
  75078. * @param reusable If the post process can be reused on the same frame. (default: false)
  75079. * @param textureType Type of textures used when performing the post process. (default: 0)
  75080. * @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)
  75081. */
  75082. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75083. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75084. if (blockCompilation === void 0) { blockCompilation = false; }
  75085. 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;
  75086. /**
  75087. * The amount of seperation of rgb channels (default: 30)
  75088. */
  75089. _this.aberrationAmount = 30;
  75090. /**
  75091. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75092. */
  75093. _this.radialIntensity = 0;
  75094. /**
  75095. * 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))
  75096. */
  75097. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75098. /**
  75099. * 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))
  75100. */
  75101. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75102. _this.onApplyObservable.add(function (effect) {
  75103. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75104. effect.setFloat('screen_width', screenWidth);
  75105. effect.setFloat('screen_height', screenHeight);
  75106. effect.setFloat('radialIntensity', _this.radialIntensity);
  75107. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75108. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75109. });
  75110. return _this;
  75111. }
  75112. return ChromaticAberrationPostProcess;
  75113. }(BABYLON.PostProcess));
  75114. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75115. })(BABYLON || (BABYLON = {}));
  75116. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75117. var BABYLON;
  75118. (function (BABYLON) {
  75119. /**
  75120. * The GrainPostProcess adds noise to the image at mid luminance levels
  75121. */
  75122. var GrainPostProcess = /** @class */ (function (_super) {
  75123. __extends(GrainPostProcess, _super);
  75124. /**
  75125. * Creates a new instance of @see GrainPostProcess
  75126. * @param name The name of the effect.
  75127. * @param options The required width/height ratio to downsize to before computing the render pass.
  75128. * @param camera The camera to apply the render pass to.
  75129. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75130. * @param engine The engine which the post process will be applied. (default: current engine)
  75131. * @param reusable If the post process can be reused on the same frame. (default: false)
  75132. * @param textureType Type of textures used when performing the post process. (default: 0)
  75133. * @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)
  75134. */
  75135. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75137. if (blockCompilation === void 0) { blockCompilation = false; }
  75138. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75139. /**
  75140. * The intensity of the grain added (default: 30)
  75141. */
  75142. _this.intensity = 30;
  75143. /**
  75144. * If the grain should be randomized on every frame
  75145. */
  75146. _this.animated = false;
  75147. _this.onApplyObservable.add(function (effect) {
  75148. effect.setFloat('intensity', _this.intensity);
  75149. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75150. });
  75151. return _this;
  75152. }
  75153. return GrainPostProcess;
  75154. }(BABYLON.PostProcess));
  75155. BABYLON.GrainPostProcess = GrainPostProcess;
  75156. })(BABYLON || (BABYLON = {}));
  75157. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75158. var BABYLON;
  75159. (function (BABYLON) {
  75160. /**
  75161. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75162. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75163. */
  75164. var SharpenPostProcess = /** @class */ (function (_super) {
  75165. __extends(SharpenPostProcess, _super);
  75166. /**
  75167. * Creates a new instance ConvolutionPostProcess
  75168. * @param name The name of the effect.
  75169. * @param options The required width/height ratio to downsize to before computing the render pass.
  75170. * @param camera The camera to apply the render pass to.
  75171. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75172. * @param engine The engine which the post process will be applied. (default: current engine)
  75173. * @param reusable If the post process can be reused on the same frame. (default: false)
  75174. * @param textureType Type of textures used when performing the post process. (default: 0)
  75175. * @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)
  75176. */
  75177. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75178. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75179. if (blockCompilation === void 0) { blockCompilation = false; }
  75180. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75181. /**
  75182. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75183. */
  75184. _this.colorAmount = 1.0;
  75185. /**
  75186. * How much sharpness should be applied (default: 0.3)
  75187. */
  75188. _this.edgeAmount = 0.3;
  75189. _this.onApply = function (effect) {
  75190. effect.setFloat2("screenSize", _this.width, _this.height);
  75191. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75192. };
  75193. return _this;
  75194. }
  75195. return SharpenPostProcess;
  75196. }(BABYLON.PostProcess));
  75197. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75198. })(BABYLON || (BABYLON = {}));
  75199. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75200. var BABYLON;
  75201. (function (BABYLON) {
  75202. /**
  75203. * The Blur Post Process which blurs an image based on a kernel and direction.
  75204. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75205. */
  75206. var BlurPostProcess = /** @class */ (function (_super) {
  75207. __extends(BlurPostProcess, _super);
  75208. /**
  75209. * Creates a new instance BlurPostProcess
  75210. * @param name The name of the effect.
  75211. * @param direction The direction in which to blur the image.
  75212. * @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.
  75213. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75214. * @param camera The camera to apply the render pass to.
  75215. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75216. * @param engine The engine which the post process will be applied. (default: current engine)
  75217. * @param reusable If the post process can be reused on the same frame. (default: false)
  75218. * @param textureType Type of textures used when performing the post process. (default: 0)
  75219. * @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)
  75220. */
  75221. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75224. if (defines === void 0) { defines = ""; }
  75225. if (blockCompilation === void 0) { blockCompilation = false; }
  75226. 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;
  75227. _this.direction = direction;
  75228. _this.blockCompilation = blockCompilation;
  75229. _this._packedFloat = false;
  75230. _this._staticDefines = "";
  75231. _this._staticDefines = defines;
  75232. _this.onApplyObservable.add(function (effect) {
  75233. if (_this._outputTexture) {
  75234. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75235. }
  75236. else {
  75237. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75238. }
  75239. });
  75240. _this.kernel = kernel;
  75241. return _this;
  75242. }
  75243. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75244. /**
  75245. * Gets the length in pixels of the blur sample region
  75246. */
  75247. get: function () {
  75248. return this._idealKernel;
  75249. },
  75250. /**
  75251. * Sets the length in pixels of the blur sample region
  75252. */
  75253. set: function (v) {
  75254. if (this._idealKernel === v) {
  75255. return;
  75256. }
  75257. v = Math.max(v, 1);
  75258. this._idealKernel = v;
  75259. this._kernel = this._nearestBestKernel(v);
  75260. if (!this.blockCompilation) {
  75261. this._updateParameters();
  75262. }
  75263. },
  75264. enumerable: true,
  75265. configurable: true
  75266. });
  75267. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75268. /**
  75269. * Gets wether or not the blur is unpacking/repacking floats
  75270. */
  75271. get: function () {
  75272. return this._packedFloat;
  75273. },
  75274. /**
  75275. * Sets wether or not the blur needs to unpack/repack floats
  75276. */
  75277. set: function (v) {
  75278. if (this._packedFloat === v) {
  75279. return;
  75280. }
  75281. this._packedFloat = v;
  75282. if (!this.blockCompilation) {
  75283. this._updateParameters();
  75284. }
  75285. },
  75286. enumerable: true,
  75287. configurable: true
  75288. });
  75289. /**
  75290. * Updates the effect with the current post process compile time values and recompiles the shader.
  75291. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75292. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75293. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75294. * @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
  75295. * @param onCompiled Called when the shader has been compiled.
  75296. * @param onError Called if there is an error when compiling a shader.
  75297. */
  75298. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75299. if (defines === void 0) { defines = null; }
  75300. if (uniforms === void 0) { uniforms = null; }
  75301. if (samplers === void 0) { samplers = null; }
  75302. this._updateParameters(onCompiled, onError);
  75303. };
  75304. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75305. // Generate sampling offsets and weights
  75306. var N = this._kernel;
  75307. var centerIndex = (N - 1) / 2;
  75308. // Generate Gaussian sampling weights over kernel
  75309. var offsets = [];
  75310. var weights = [];
  75311. var totalWeight = 0;
  75312. for (var i = 0; i < N; i++) {
  75313. var u = i / (N - 1);
  75314. var w = this._gaussianWeight(u * 2.0 - 1);
  75315. offsets[i] = (i - centerIndex);
  75316. weights[i] = w;
  75317. totalWeight += w;
  75318. }
  75319. // Normalize weights
  75320. for (var i = 0; i < weights.length; i++) {
  75321. weights[i] /= totalWeight;
  75322. }
  75323. // Optimize: combine samples to take advantage of hardware linear sampling
  75324. // Walk from left to center, combining pairs (symmetrically)
  75325. var linearSamplingWeights = [];
  75326. var linearSamplingOffsets = [];
  75327. var linearSamplingMap = [];
  75328. for (var i = 0; i <= centerIndex; i += 2) {
  75329. var j = Math.min(i + 1, Math.floor(centerIndex));
  75330. var singleCenterSample = i === j;
  75331. if (singleCenterSample) {
  75332. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75333. }
  75334. else {
  75335. var sharedCell = j === centerIndex;
  75336. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75337. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75338. if (offsetLinear === 0) {
  75339. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75340. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75341. }
  75342. else {
  75343. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75344. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75345. }
  75346. }
  75347. }
  75348. for (var i = 0; i < linearSamplingMap.length; i++) {
  75349. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75350. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75351. }
  75352. // Replace with optimized
  75353. offsets = linearSamplingOffsets;
  75354. weights = linearSamplingWeights;
  75355. // Generate shaders
  75356. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75357. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75358. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75359. var defines = "";
  75360. defines += this._staticDefines;
  75361. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75362. if (this._staticDefines.indexOf("DOF") != -1) {
  75363. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75364. varyingCount--;
  75365. }
  75366. for (var i = 0; i < varyingCount; i++) {
  75367. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75368. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75369. }
  75370. var depCount = 0;
  75371. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75372. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75373. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75374. depCount++;
  75375. }
  75376. if (this.packedFloat) {
  75377. defines += "#define PACKEDFLOAT 1";
  75378. }
  75379. this.blockCompilation = false;
  75380. _super.prototype.updateEffect.call(this, defines, null, null, {
  75381. varyingCount: varyingCount,
  75382. depCount: depCount
  75383. }, onCompiled, onError);
  75384. };
  75385. /**
  75386. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75387. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75388. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75389. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75390. * The gaps between physical kernels are compensated for in the weighting of the samples
  75391. * @param idealKernel Ideal blur kernel.
  75392. * @return Nearest best kernel.
  75393. */
  75394. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75395. var v = Math.round(idealKernel);
  75396. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75397. var k = _a[_i];
  75398. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75399. return Math.max(k, 3);
  75400. }
  75401. }
  75402. return Math.max(v, 3);
  75403. };
  75404. /**
  75405. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75406. * @param x The point on the Gaussian distribution to sample.
  75407. * @return the value of the Gaussian function at x.
  75408. */
  75409. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75410. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75411. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75412. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75413. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75414. // truncated at around 1.3% of peak strength.
  75415. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75416. var sigma = (1 / 3);
  75417. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75418. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75419. var weight = (1.0 / denominator) * Math.exp(exponent);
  75420. return weight;
  75421. };
  75422. /**
  75423. * Generates a string that can be used as a floating point number in GLSL.
  75424. * @param x Value to print.
  75425. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75426. * @return GLSL float string.
  75427. */
  75428. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75429. if (decimalFigures === void 0) { decimalFigures = 8; }
  75430. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75431. };
  75432. return BlurPostProcess;
  75433. }(BABYLON.PostProcess));
  75434. BABYLON.BlurPostProcess = BlurPostProcess;
  75435. })(BABYLON || (BABYLON = {}));
  75436. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75437. var BABYLON;
  75438. (function (BABYLON) {
  75439. /**
  75440. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75441. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75442. * based on samples that have a large difference in distance than the center pixel.
  75443. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75444. */
  75445. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75446. __extends(DepthOfFieldBlurPostProcess, _super);
  75447. /**
  75448. * Creates a new instance CircleOfConfusionPostProcess
  75449. * @param name The name of the effect.
  75450. * @param scene The scene the effect belongs to.
  75451. * @param direction The direction the blur should be applied.
  75452. * @param kernel The size of the kernel used to blur.
  75453. * @param options The required width/height ratio to downsize to before computing the render pass.
  75454. * @param camera The camera to apply the render pass to.
  75455. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75456. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75457. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75458. * @param engine The engine which the post process will be applied. (default: current engine)
  75459. * @param reusable If the post process can be reused on the same frame. (default: false)
  75460. * @param textureType Type of textures used when performing the post process. (default: 0)
  75461. * @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)
  75462. */
  75463. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75464. if (imageToBlur === void 0) { imageToBlur = null; }
  75465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75466. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75467. if (blockCompilation === void 0) { blockCompilation = false; }
  75468. 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;
  75469. _this.direction = direction;
  75470. _this.onApplyObservable.add(function (effect) {
  75471. if (imageToBlur != null) {
  75472. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75473. }
  75474. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75475. if (scene.activeCamera) {
  75476. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75477. }
  75478. });
  75479. return _this;
  75480. }
  75481. return DepthOfFieldBlurPostProcess;
  75482. }(BABYLON.BlurPostProcess));
  75483. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75484. })(BABYLON || (BABYLON = {}));
  75485. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75486. var BABYLON;
  75487. (function (BABYLON) {
  75488. /**
  75489. * Options to be set when merging outputs from the default pipeline.
  75490. */
  75491. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75492. function DepthOfFieldMergePostProcessOptions() {
  75493. }
  75494. return DepthOfFieldMergePostProcessOptions;
  75495. }());
  75496. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75497. /**
  75498. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75499. */
  75500. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75501. __extends(DepthOfFieldMergePostProcess, _super);
  75502. /**
  75503. * Creates a new instance of DepthOfFieldMergePostProcess
  75504. * @param name The name of the effect.
  75505. * @param originalFromInput Post process which's input will be used for the merge.
  75506. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75507. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75508. * @param options The required width/height ratio to downsize to before computing the render pass.
  75509. * @param camera The camera to apply the render pass to.
  75510. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75511. * @param engine The engine which the post process will be applied. (default: current engine)
  75512. * @param reusable If the post process can be reused on the same frame. (default: false)
  75513. * @param textureType Type of textures used when performing the post process. (default: 0)
  75514. * @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)
  75515. */
  75516. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75517. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75518. if (blockCompilation === void 0) { blockCompilation = false; }
  75519. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75520. _this.blurSteps = blurSteps;
  75521. _this.onApplyObservable.add(function (effect) {
  75522. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75523. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75524. blurSteps.forEach(function (step, index) {
  75525. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75526. });
  75527. });
  75528. if (!blockCompilation) {
  75529. _this.updateEffect();
  75530. }
  75531. return _this;
  75532. }
  75533. /**
  75534. * Updates the effect with the current post process compile time values and recompiles the shader.
  75535. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75536. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75537. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75538. * @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
  75539. * @param onCompiled Called when the shader has been compiled.
  75540. * @param onError Called if there is an error when compiling a shader.
  75541. */
  75542. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75543. if (defines === void 0) { defines = null; }
  75544. if (uniforms === void 0) { uniforms = null; }
  75545. if (samplers === void 0) { samplers = null; }
  75546. if (!defines) {
  75547. defines = "";
  75548. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75549. }
  75550. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75551. };
  75552. return DepthOfFieldMergePostProcess;
  75553. }(BABYLON.PostProcess));
  75554. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75555. })(BABYLON || (BABYLON = {}));
  75556. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75557. var BABYLON;
  75558. (function (BABYLON) {
  75559. /**
  75560. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75561. */
  75562. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75563. __extends(CircleOfConfusionPostProcess, _super);
  75564. /**
  75565. * Creates a new instance CircleOfConfusionPostProcess
  75566. * @param name The name of the effect.
  75567. * @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.
  75568. * @param options The required width/height ratio to downsize to before computing the render pass.
  75569. * @param camera The camera to apply the render pass to.
  75570. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75571. * @param engine The engine which the post process will be applied. (default: current engine)
  75572. * @param reusable If the post process can be reused on the same frame. (default: false)
  75573. * @param textureType Type of textures used when performing the post process. (default: 0)
  75574. * @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)
  75575. */
  75576. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75577. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75578. if (blockCompilation === void 0) { blockCompilation = false; }
  75579. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75580. /**
  75581. * 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.
  75582. */
  75583. _this.lensSize = 50;
  75584. /**
  75585. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75586. */
  75587. _this.fStop = 1.4;
  75588. /**
  75589. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75590. */
  75591. _this.focusDistance = 2000;
  75592. /**
  75593. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75594. */
  75595. _this.focalLength = 50;
  75596. _this._depthTexture = null;
  75597. _this._depthTexture = depthTexture;
  75598. _this.onApplyObservable.add(function (effect) {
  75599. if (!_this._depthTexture) {
  75600. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75601. return;
  75602. }
  75603. effect.setTexture("depthSampler", _this._depthTexture);
  75604. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75605. var aperture = _this.lensSize / _this.fStop;
  75606. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75607. effect.setFloat('focusDistance', _this.focusDistance);
  75608. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75609. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75610. });
  75611. return _this;
  75612. }
  75613. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75614. /**
  75615. * 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.
  75616. */
  75617. set: function (value) {
  75618. this._depthTexture = value;
  75619. },
  75620. enumerable: true,
  75621. configurable: true
  75622. });
  75623. return CircleOfConfusionPostProcess;
  75624. }(BABYLON.PostProcess));
  75625. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75626. })(BABYLON || (BABYLON = {}));
  75627. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75628. var BABYLON;
  75629. (function (BABYLON) {
  75630. /**
  75631. * Specifies the level of max blur that should be applied when using the depth of field effect
  75632. */
  75633. var DepthOfFieldEffectBlurLevel;
  75634. (function (DepthOfFieldEffectBlurLevel) {
  75635. /**
  75636. * Subtle blur
  75637. */
  75638. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75639. /**
  75640. * Medium blur
  75641. */
  75642. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75643. /**
  75644. * Large blur
  75645. */
  75646. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75647. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75648. ;
  75649. /**
  75650. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75651. */
  75652. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75653. __extends(DepthOfFieldEffect, _super);
  75654. /**
  75655. * Creates a new instance DepthOfFieldEffect
  75656. * @param scene The scene the effect belongs to.
  75657. * @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.
  75658. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75659. * @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)
  75660. */
  75661. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75662. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75663. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75664. if (blockCompilation === void 0) { blockCompilation = false; }
  75665. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75666. return _this._effects;
  75667. }, true) || this;
  75668. /**
  75669. * Internal post processes in depth of field effect
  75670. */
  75671. _this._effects = [];
  75672. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75673. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75674. // 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)
  75675. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75676. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75677. _this._depthOfFieldBlurY = [];
  75678. _this._depthOfFieldBlurX = [];
  75679. var blurCount = 1;
  75680. var kernelSize = 15;
  75681. switch (blurLevel) {
  75682. case DepthOfFieldEffectBlurLevel.High: {
  75683. blurCount = 3;
  75684. kernelSize = 51;
  75685. break;
  75686. }
  75687. case DepthOfFieldEffectBlurLevel.Medium: {
  75688. blurCount = 2;
  75689. kernelSize = 31;
  75690. break;
  75691. }
  75692. default: {
  75693. kernelSize = 15;
  75694. blurCount = 1;
  75695. break;
  75696. }
  75697. }
  75698. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75699. var ratio = 1.0;
  75700. for (var i = 0; i < blurCount; i++) {
  75701. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75702. blurY.autoClear = false;
  75703. ratio = 0.75 / Math.pow(2, i);
  75704. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75705. blurX.autoClear = false;
  75706. _this._depthOfFieldBlurY.push(blurY);
  75707. _this._depthOfFieldBlurX.push(blurX);
  75708. }
  75709. // Set all post processes on the effect.
  75710. _this._effects = [_this._circleOfConfusion];
  75711. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75712. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75713. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75714. }
  75715. // Merge blurred images with original image based on circleOfConfusion
  75716. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75717. _this._dofMerge.autoClear = false;
  75718. _this._effects.push(_this._dofMerge);
  75719. return _this;
  75720. }
  75721. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75722. get: function () {
  75723. return this._circleOfConfusion.focalLength;
  75724. },
  75725. /**
  75726. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75727. */
  75728. set: function (value) {
  75729. this._circleOfConfusion.focalLength = value;
  75730. },
  75731. enumerable: true,
  75732. configurable: true
  75733. });
  75734. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75735. get: function () {
  75736. return this._circleOfConfusion.fStop;
  75737. },
  75738. /**
  75739. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75740. */
  75741. set: function (value) {
  75742. this._circleOfConfusion.fStop = value;
  75743. },
  75744. enumerable: true,
  75745. configurable: true
  75746. });
  75747. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75748. get: function () {
  75749. return this._circleOfConfusion.focusDistance;
  75750. },
  75751. /**
  75752. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75753. */
  75754. set: function (value) {
  75755. this._circleOfConfusion.focusDistance = value;
  75756. },
  75757. enumerable: true,
  75758. configurable: true
  75759. });
  75760. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75761. get: function () {
  75762. return this._circleOfConfusion.lensSize;
  75763. },
  75764. /**
  75765. * 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.
  75766. */
  75767. set: function (value) {
  75768. this._circleOfConfusion.lensSize = value;
  75769. },
  75770. enumerable: true,
  75771. configurable: true
  75772. });
  75773. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75774. /**
  75775. * 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.
  75776. */
  75777. set: function (value) {
  75778. this._circleOfConfusion.depthTexture = value;
  75779. },
  75780. enumerable: true,
  75781. configurable: true
  75782. });
  75783. /**
  75784. * Disposes each of the internal effects for a given camera.
  75785. * @param camera The camera to dispose the effect on.
  75786. */
  75787. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75788. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75789. this._effects[effectIndex].dispose(camera);
  75790. }
  75791. };
  75792. /**
  75793. * Internal
  75794. */
  75795. DepthOfFieldEffect.prototype._updateEffects = function () {
  75796. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75797. this._effects[effectIndex].updateEffect();
  75798. }
  75799. };
  75800. /**
  75801. * Internal
  75802. * @returns if all the contained post processes are ready.
  75803. */
  75804. DepthOfFieldEffect.prototype._isReady = function () {
  75805. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75806. if (!this._effects[effectIndex].isReady()) {
  75807. return false;
  75808. }
  75809. }
  75810. return true;
  75811. };
  75812. return DepthOfFieldEffect;
  75813. }(BABYLON.PostProcessRenderEffect));
  75814. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75815. })(BABYLON || (BABYLON = {}));
  75816. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75817. var BABYLON;
  75818. (function (BABYLON) {
  75819. /**
  75820. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75821. */
  75822. var BloomMergePostProcess = /** @class */ (function (_super) {
  75823. __extends(BloomMergePostProcess, _super);
  75824. /**
  75825. * Creates a new instance of @see BloomMergePostProcess
  75826. * @param name The name of the effect.
  75827. * @param originalFromInput Post process which's input will be used for the merge.
  75828. * @param blurred Blurred highlights post process which's output will be used.
  75829. * @param weight Weight of the bloom to be added to the original input.
  75830. * @param options The required width/height ratio to downsize to before computing the render pass.
  75831. * @param camera The camera to apply the render pass to.
  75832. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75833. * @param engine The engine which the post process will be applied. (default: current engine)
  75834. * @param reusable If the post process can be reused on the same frame. (default: false)
  75835. * @param textureType Type of textures used when performing the post process. (default: 0)
  75836. * @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)
  75837. */
  75838. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75840. if (blockCompilation === void 0) { blockCompilation = false; }
  75841. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75842. _this.weight = weight;
  75843. _this.onApplyObservable.add(function (effect) {
  75844. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75845. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75846. effect.setFloat("bloomWeight", _this.weight);
  75847. });
  75848. if (!blockCompilation) {
  75849. _this.updateEffect();
  75850. }
  75851. return _this;
  75852. }
  75853. return BloomMergePostProcess;
  75854. }(BABYLON.PostProcess));
  75855. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75856. })(BABYLON || (BABYLON = {}));
  75857. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75858. var BABYLON;
  75859. (function (BABYLON) {
  75860. /**
  75861. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75862. */
  75863. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75864. __extends(ExtractHighlightsPostProcess, _super);
  75865. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75866. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75867. if (blockCompilation === void 0) { blockCompilation = false; }
  75868. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75869. /**
  75870. * The luminance threshold, pixels below this value will be set to black.
  75871. */
  75872. _this.threshold = 0.9;
  75873. /**
  75874. * Internal
  75875. */
  75876. _this._exposure = 1;
  75877. /**
  75878. * Post process which has the input texture to be used when performing highlight extraction
  75879. */
  75880. _this._inputPostProcess = null;
  75881. _this.onApplyObservable.add(function (effect) {
  75882. if (_this._inputPostProcess) {
  75883. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75884. }
  75885. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75886. effect.setFloat('exposure', _this._exposure);
  75887. });
  75888. return _this;
  75889. }
  75890. return ExtractHighlightsPostProcess;
  75891. }(BABYLON.PostProcess));
  75892. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75893. })(BABYLON || (BABYLON = {}));
  75894. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75895. var BABYLON;
  75896. (function (BABYLON) {
  75897. /**
  75898. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75899. */
  75900. var BloomEffect = /** @class */ (function (_super) {
  75901. __extends(BloomEffect, _super);
  75902. /**
  75903. * Creates a new instance of @see BloomEffect
  75904. * @param scene The scene the effect belongs to.
  75905. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75906. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75907. * @param bloomWeight The the strength of bloom.
  75908. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75909. * @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)
  75910. */
  75911. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75912. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75913. if (blockCompilation === void 0) { blockCompilation = false; }
  75914. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75915. return _this._effects;
  75916. }, true) || this;
  75917. _this.bloomScale = bloomScale;
  75918. /**
  75919. * Internal
  75920. */
  75921. _this._effects = [];
  75922. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75923. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75924. _this._blurX.alwaysForcePOT = true;
  75925. _this._blurX.autoClear = false;
  75926. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75927. _this._blurY.alwaysForcePOT = true;
  75928. _this._blurY.autoClear = false;
  75929. _this.kernel = bloomKernel;
  75930. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75931. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75932. _this._merge.autoClear = false;
  75933. _this._effects.push(_this._merge);
  75934. return _this;
  75935. }
  75936. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75937. /**
  75938. * The luminance threshold to find bright areas of the image to bloom.
  75939. */
  75940. get: function () {
  75941. return this._downscale.threshold;
  75942. },
  75943. set: function (value) {
  75944. this._downscale.threshold = value;
  75945. },
  75946. enumerable: true,
  75947. configurable: true
  75948. });
  75949. Object.defineProperty(BloomEffect.prototype, "weight", {
  75950. /**
  75951. * The strength of the bloom.
  75952. */
  75953. get: function () {
  75954. return this._merge.weight;
  75955. },
  75956. set: function (value) {
  75957. this._merge.weight = value;
  75958. },
  75959. enumerable: true,
  75960. configurable: true
  75961. });
  75962. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75963. /**
  75964. * Specifies the size of the bloom blur kernel, relative to the final output size
  75965. */
  75966. get: function () {
  75967. return this._blurX.kernel / this.bloomScale;
  75968. },
  75969. set: function (value) {
  75970. this._blurX.kernel = value * this.bloomScale;
  75971. this._blurY.kernel = value * this.bloomScale;
  75972. },
  75973. enumerable: true,
  75974. configurable: true
  75975. });
  75976. /**
  75977. * Disposes each of the internal effects for a given camera.
  75978. * @param camera The camera to dispose the effect on.
  75979. */
  75980. BloomEffect.prototype.disposeEffects = function (camera) {
  75981. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75982. this._effects[effectIndex].dispose(camera);
  75983. }
  75984. };
  75985. /**
  75986. * Internal
  75987. */
  75988. BloomEffect.prototype._updateEffects = function () {
  75989. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75990. this._effects[effectIndex].updateEffect();
  75991. }
  75992. };
  75993. /**
  75994. * Internal
  75995. * @returns if all the contained post processes are ready.
  75996. */
  75997. BloomEffect.prototype._isReady = function () {
  75998. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75999. if (!this._effects[effectIndex].isReady()) {
  76000. return false;
  76001. }
  76002. }
  76003. return true;
  76004. };
  76005. return BloomEffect;
  76006. }(BABYLON.PostProcessRenderEffect));
  76007. BABYLON.BloomEffect = BloomEffect;
  76008. })(BABYLON || (BABYLON = {}));
  76009. //# sourceMappingURL=babylon.bloomEffect.js.map
  76010. var BABYLON;
  76011. (function (BABYLON) {
  76012. /**
  76013. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76014. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76015. */
  76016. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76017. __extends(DefaultRenderingPipeline, _super);
  76018. /**
  76019. * @constructor
  76020. * @param {string} name - The rendering pipeline name (default: "")
  76021. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76022. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76023. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76024. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76025. */
  76026. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76027. if (name === void 0) { name = ""; }
  76028. if (hdr === void 0) { hdr = true; }
  76029. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76030. if (automaticBuild === void 0) { automaticBuild = true; }
  76031. var _this = _super.call(this, scene.getEngine(), name) || this;
  76032. _this._originalCameras = [];
  76033. /**
  76034. * ID of the sharpen post process,
  76035. */
  76036. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76037. /**
  76038. * ID of the image processing post process;
  76039. */
  76040. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76041. /**
  76042. * ID of the Fast Approximate Anti-Aliasing post process;
  76043. */
  76044. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76045. /**
  76046. * ID of the chromatic aberration post process,
  76047. */
  76048. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76049. /**
  76050. * ID of the grain post process
  76051. */
  76052. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76053. /**
  76054. * Glow post process which adds a glow to emmisive areas of the image
  76055. */
  76056. _this._glowLayer = null;
  76057. /**
  76058. * Animations which can be used to tweak settings over a period of time
  76059. */
  76060. _this.animations = [];
  76061. _this._imageProcessingConfigurationObserver = null;
  76062. // Values
  76063. _this._sharpenEnabled = false;
  76064. _this._bloomEnabled = false;
  76065. _this._depthOfFieldEnabled = false;
  76066. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76067. _this._fxaaEnabled = false;
  76068. _this._imageProcessingEnabled = true;
  76069. _this._bloomScale = 0.5;
  76070. _this._chromaticAberrationEnabled = false;
  76071. _this._grainEnabled = false;
  76072. _this._buildAllowed = true;
  76073. _this._resizeObserver = null;
  76074. _this._hardwareScaleLevel = 1.0;
  76075. _this._bloomKernel = 64;
  76076. /**
  76077. * Specifies the weight of the bloom in the final rendering
  76078. */
  76079. _this._bloomWeight = 0.15;
  76080. /**
  76081. * Specifies the luma threshold for the area that will be blurred by the bloom
  76082. */
  76083. _this._bloomThreshold = 0.9;
  76084. _this._samples = 1;
  76085. _this._hasCleared = false;
  76086. _this._prevPostProcess = null;
  76087. _this._prevPrevPostProcess = null;
  76088. _this._cameras = cameras || scene.cameras;
  76089. _this._originalCameras = _this._cameras.slice();
  76090. _this._buildAllowed = automaticBuild;
  76091. // Initialize
  76092. _this._scene = scene;
  76093. var caps = _this._scene.getEngine().getCaps();
  76094. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76095. // Misc
  76096. if (_this._hdr) {
  76097. if (caps.textureHalfFloatRender) {
  76098. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76099. }
  76100. else if (caps.textureFloatRender) {
  76101. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76102. }
  76103. }
  76104. else {
  76105. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76106. }
  76107. // Attach
  76108. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76109. var engine = _this._scene.getEngine();
  76110. // Create post processes before hand so they can be modified before enabled.
  76111. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76112. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76113. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76114. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76115. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76116. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76117. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76118. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76119. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76120. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76121. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76122. _this.bloomKernel = _this.bloomKernel;
  76123. });
  76124. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76125. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76126. });
  76127. _this._buildPipeline();
  76128. return _this;
  76129. }
  76130. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76131. get: function () {
  76132. return this._sharpenEnabled;
  76133. },
  76134. /**
  76135. * Enable or disable the sharpen process from the pipeline
  76136. */
  76137. set: function (enabled) {
  76138. if (this._sharpenEnabled === enabled) {
  76139. return;
  76140. }
  76141. this._sharpenEnabled = enabled;
  76142. this._buildPipeline();
  76143. },
  76144. enumerable: true,
  76145. configurable: true
  76146. });
  76147. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76148. /**
  76149. * Specifies the size of the bloom blur kernel, relative to the final output size
  76150. */
  76151. get: function () {
  76152. return this._bloomKernel;
  76153. },
  76154. set: function (value) {
  76155. this._bloomKernel = value;
  76156. this.bloom.kernel = value / this._hardwareScaleLevel;
  76157. },
  76158. enumerable: true,
  76159. configurable: true
  76160. });
  76161. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76162. get: function () {
  76163. return this._bloomWeight;
  76164. },
  76165. /**
  76166. * The strength of the bloom.
  76167. */
  76168. set: function (value) {
  76169. if (this._bloomWeight === value) {
  76170. return;
  76171. }
  76172. this.bloom.weight = value;
  76173. this._bloomWeight = value;
  76174. },
  76175. enumerable: true,
  76176. configurable: true
  76177. });
  76178. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76179. get: function () {
  76180. return this._bloomThreshold;
  76181. },
  76182. /**
  76183. * The strength of the bloom.
  76184. */
  76185. set: function (value) {
  76186. if (this._bloomThreshold === value) {
  76187. return;
  76188. }
  76189. this.bloom.threshold = value;
  76190. this._bloomThreshold = value;
  76191. },
  76192. enumerable: true,
  76193. configurable: true
  76194. });
  76195. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76196. get: function () {
  76197. return this._bloomScale;
  76198. },
  76199. /**
  76200. * The scale of the bloom, lower value will provide better performance.
  76201. */
  76202. set: function (value) {
  76203. if (this._bloomScale === value) {
  76204. return;
  76205. }
  76206. this._bloomScale = value;
  76207. // recreate bloom and dispose old as this setting is not dynamic
  76208. this._rebuildBloom();
  76209. this._buildPipeline();
  76210. },
  76211. enumerable: true,
  76212. configurable: true
  76213. });
  76214. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76215. get: function () {
  76216. return this._bloomEnabled;
  76217. },
  76218. /**
  76219. * Enable or disable the bloom from the pipeline
  76220. */
  76221. set: function (enabled) {
  76222. if (this._bloomEnabled === enabled) {
  76223. return;
  76224. }
  76225. this._bloomEnabled = enabled;
  76226. this._buildPipeline();
  76227. },
  76228. enumerable: true,
  76229. configurable: true
  76230. });
  76231. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76232. // recreate bloom and dispose old as this setting is not dynamic
  76233. var oldBloom = this.bloom;
  76234. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76235. this.bloom.threshold = oldBloom.threshold;
  76236. for (var i = 0; i < this._cameras.length; i++) {
  76237. oldBloom.disposeEffects(this._cameras[i]);
  76238. }
  76239. };
  76240. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76241. /**
  76242. * If the depth of field is enabled.
  76243. */
  76244. get: function () {
  76245. return this._depthOfFieldEnabled;
  76246. },
  76247. set: function (enabled) {
  76248. if (this._depthOfFieldEnabled === enabled) {
  76249. return;
  76250. }
  76251. this._depthOfFieldEnabled = enabled;
  76252. this._buildPipeline();
  76253. },
  76254. enumerable: true,
  76255. configurable: true
  76256. });
  76257. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76258. /**
  76259. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76260. */
  76261. get: function () {
  76262. return this._depthOfFieldBlurLevel;
  76263. },
  76264. set: function (value) {
  76265. if (this._depthOfFieldBlurLevel === value) {
  76266. return;
  76267. }
  76268. this._depthOfFieldBlurLevel = value;
  76269. // recreate dof and dispose old as this setting is not dynamic
  76270. var oldDof = this.depthOfField;
  76271. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76272. this.depthOfField.focalLength = oldDof.focalLength;
  76273. this.depthOfField.focusDistance = oldDof.focusDistance;
  76274. this.depthOfField.fStop = oldDof.fStop;
  76275. this.depthOfField.lensSize = oldDof.lensSize;
  76276. for (var i = 0; i < this._cameras.length; i++) {
  76277. oldDof.disposeEffects(this._cameras[i]);
  76278. }
  76279. this._buildPipeline();
  76280. },
  76281. enumerable: true,
  76282. configurable: true
  76283. });
  76284. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76285. get: function () {
  76286. return this._fxaaEnabled;
  76287. },
  76288. /**
  76289. * If the anti aliasing is enabled.
  76290. */
  76291. set: function (enabled) {
  76292. if (this._fxaaEnabled === enabled) {
  76293. return;
  76294. }
  76295. this._fxaaEnabled = enabled;
  76296. this._buildPipeline();
  76297. },
  76298. enumerable: true,
  76299. configurable: true
  76300. });
  76301. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76302. get: function () {
  76303. return this._samples;
  76304. },
  76305. /**
  76306. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76307. */
  76308. set: function (sampleCount) {
  76309. if (this._samples === sampleCount) {
  76310. return;
  76311. }
  76312. this._samples = sampleCount;
  76313. this._buildPipeline();
  76314. },
  76315. enumerable: true,
  76316. configurable: true
  76317. });
  76318. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76319. get: function () {
  76320. return this._imageProcessingEnabled;
  76321. },
  76322. /**
  76323. * If image processing is enabled.
  76324. */
  76325. set: function (enabled) {
  76326. if (this._imageProcessingEnabled === enabled) {
  76327. return;
  76328. }
  76329. this._imageProcessingEnabled = enabled;
  76330. this._buildPipeline();
  76331. },
  76332. enumerable: true,
  76333. configurable: true
  76334. });
  76335. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76336. get: function () {
  76337. return this._glowLayer == null;
  76338. },
  76339. /**
  76340. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76341. */
  76342. set: function (enabled) {
  76343. if (enabled && !this._glowLayer) {
  76344. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76345. }
  76346. else if (!enabled && this._glowLayer) {
  76347. this._glowLayer.dispose();
  76348. this._glowLayer = null;
  76349. }
  76350. },
  76351. enumerable: true,
  76352. configurable: true
  76353. });
  76354. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76355. get: function () {
  76356. return this._chromaticAberrationEnabled;
  76357. },
  76358. /**
  76359. * Enable or disable the chromaticAberration process from the pipeline
  76360. */
  76361. set: function (enabled) {
  76362. if (this._chromaticAberrationEnabled === enabled) {
  76363. return;
  76364. }
  76365. this._chromaticAberrationEnabled = enabled;
  76366. this._buildPipeline();
  76367. },
  76368. enumerable: true,
  76369. configurable: true
  76370. });
  76371. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76372. get: function () {
  76373. return this._grainEnabled;
  76374. },
  76375. /**
  76376. * Enable or disable the grain process from the pipeline
  76377. */
  76378. set: function (enabled) {
  76379. if (this._grainEnabled === enabled) {
  76380. return;
  76381. }
  76382. this._grainEnabled = enabled;
  76383. this._buildPipeline();
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. /**
  76389. * Force the compilation of the entire pipeline.
  76390. */
  76391. DefaultRenderingPipeline.prototype.prepare = function () {
  76392. var previousState = this._buildAllowed;
  76393. this._buildAllowed = true;
  76394. this._buildPipeline();
  76395. this._buildAllowed = previousState;
  76396. };
  76397. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76398. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76399. if (this._hasCleared) {
  76400. postProcess.autoClear = false;
  76401. }
  76402. else {
  76403. postProcess.autoClear = true;
  76404. this._scene.autoClear = false;
  76405. this._hasCleared = true;
  76406. }
  76407. if (!skipTextureSharing) {
  76408. if (this._prevPrevPostProcess) {
  76409. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76410. }
  76411. else {
  76412. postProcess.useOwnOutput();
  76413. }
  76414. if (this._prevPostProcess) {
  76415. this._prevPrevPostProcess = this._prevPostProcess;
  76416. }
  76417. this._prevPostProcess = postProcess;
  76418. }
  76419. };
  76420. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76421. var _this = this;
  76422. if (!this._buildAllowed) {
  76423. return;
  76424. }
  76425. this._scene.autoClear = true;
  76426. var engine = this._scene.getEngine();
  76427. this._disposePostProcesses();
  76428. if (this._cameras !== null) {
  76429. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76430. // get back cameras to be used to reattach pipeline
  76431. this._cameras = this._originalCameras.slice();
  76432. }
  76433. this._reset();
  76434. this._prevPostProcess = null;
  76435. this._prevPrevPostProcess = null;
  76436. this._hasCleared = false;
  76437. if (this.depthOfFieldEnabled) {
  76438. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76439. this.depthOfField.depthTexture = depthTexture;
  76440. if (!this.depthOfField._isReady()) {
  76441. this.depthOfField._updateEffects();
  76442. }
  76443. this.addEffect(this.depthOfField);
  76444. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76445. }
  76446. if (this.bloomEnabled) {
  76447. if (!this.bloom._isReady()) {
  76448. this.bloom._updateEffects();
  76449. }
  76450. this.addEffect(this.bloom);
  76451. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76452. }
  76453. if (this._imageProcessingEnabled) {
  76454. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76455. if (this._hdr) {
  76456. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76457. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76458. }
  76459. else {
  76460. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76461. }
  76462. }
  76463. if (this.sharpenEnabled) {
  76464. if (!this.sharpen.isReady()) {
  76465. this.sharpen.updateEffect();
  76466. }
  76467. this.addEffect(this._sharpenEffect);
  76468. this._setAutoClearAndTextureSharing(this.sharpen);
  76469. }
  76470. if (this.grainEnabled) {
  76471. if (!this.grain.isReady()) {
  76472. this.grain.updateEffect();
  76473. }
  76474. this.addEffect(this._grainEffect);
  76475. this._setAutoClearAndTextureSharing(this.grain);
  76476. }
  76477. if (this.chromaticAberrationEnabled) {
  76478. if (!this.chromaticAberration.isReady()) {
  76479. this.chromaticAberration.updateEffect();
  76480. }
  76481. this.addEffect(this._chromaticAberrationEffect);
  76482. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76483. }
  76484. if (this.fxaaEnabled) {
  76485. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76486. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76487. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76488. }
  76489. if (this._cameras !== null) {
  76490. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76491. }
  76492. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76493. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76494. }
  76495. };
  76496. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76497. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76498. for (var i = 0; i < this._cameras.length; i++) {
  76499. var camera = this._cameras[i];
  76500. if (this.imageProcessing) {
  76501. this.imageProcessing.dispose(camera);
  76502. }
  76503. if (this.fxaa) {
  76504. this.fxaa.dispose(camera);
  76505. }
  76506. // These are created in the constructor and should not be disposed on every pipeline change
  76507. if (disposeNonRecreated) {
  76508. if (this.sharpen) {
  76509. this.sharpen.dispose(camera);
  76510. }
  76511. if (this.depthOfField) {
  76512. this.depthOfField.disposeEffects(camera);
  76513. }
  76514. if (this.bloom) {
  76515. this.bloom.disposeEffects(camera);
  76516. }
  76517. if (this.chromaticAberration) {
  76518. this.chromaticAberration.dispose(camera);
  76519. }
  76520. if (this.grain) {
  76521. this.grain.dispose(camera);
  76522. }
  76523. if (this._glowLayer) {
  76524. this._glowLayer.dispose();
  76525. }
  76526. }
  76527. }
  76528. this.imageProcessing = null;
  76529. this.fxaa = null;
  76530. if (disposeNonRecreated) {
  76531. this.sharpen = null;
  76532. this._sharpenEffect = null;
  76533. this.depthOfField = null;
  76534. this.bloom = null;
  76535. this.chromaticAberration = null;
  76536. this._chromaticAberrationEffect = null;
  76537. this.grain = null;
  76538. this._grainEffect = null;
  76539. this._glowLayer = null;
  76540. }
  76541. };
  76542. /**
  76543. * Adds a camera to the pipeline
  76544. * @param camera the camera to be added
  76545. */
  76546. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76547. this._originalCameras.push(camera);
  76548. this._buildPipeline();
  76549. };
  76550. /**
  76551. * Removes a camera from the pipeline
  76552. * @param camera the camera to remove
  76553. */
  76554. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76555. var index = this._originalCameras.indexOf(camera);
  76556. this._originalCameras.splice(index, 1);
  76557. this._buildPipeline();
  76558. };
  76559. /**
  76560. * Dispose of the pipeline and stop all post processes
  76561. */
  76562. DefaultRenderingPipeline.prototype.dispose = function () {
  76563. this._disposePostProcesses(true);
  76564. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76565. this._scene.autoClear = true;
  76566. if (this._resizeObserver) {
  76567. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76568. this._resizeObserver = null;
  76569. }
  76570. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76571. _super.prototype.dispose.call(this);
  76572. };
  76573. /**
  76574. * Serialize the rendering pipeline (Used when exporting)
  76575. * @returns the serialized object
  76576. */
  76577. DefaultRenderingPipeline.prototype.serialize = function () {
  76578. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76579. serializationObject.customType = "DefaultRenderingPipeline";
  76580. return serializationObject;
  76581. };
  76582. /**
  76583. * Parse the serialized pipeline
  76584. * @param source Source pipeline.
  76585. * @param scene The scene to load the pipeline to.
  76586. * @param rootUrl The URL of the serialized pipeline.
  76587. * @returns An instantiated pipeline from the serialized object.
  76588. */
  76589. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76590. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76591. };
  76592. __decorate([
  76593. BABYLON.serialize()
  76594. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76595. __decorate([
  76596. BABYLON.serialize()
  76597. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76598. __decorate([
  76599. BABYLON.serialize()
  76600. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76601. __decorate([
  76602. BABYLON.serialize()
  76603. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76604. __decorate([
  76605. BABYLON.serialize()
  76606. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76607. __decorate([
  76608. BABYLON.serialize()
  76609. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76610. __decorate([
  76611. BABYLON.serialize()
  76612. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76613. __decorate([
  76614. BABYLON.serialize()
  76615. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76616. __decorate([
  76617. BABYLON.serialize()
  76618. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76619. __decorate([
  76620. BABYLON.serialize()
  76621. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76622. __decorate([
  76623. BABYLON.serialize()
  76624. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76625. __decorate([
  76626. BABYLON.serialize()
  76627. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76628. __decorate([
  76629. BABYLON.serialize()
  76630. ], DefaultRenderingPipeline.prototype, "samples", null);
  76631. __decorate([
  76632. BABYLON.serialize()
  76633. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76634. __decorate([
  76635. BABYLON.serialize()
  76636. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76637. __decorate([
  76638. BABYLON.serialize()
  76639. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76640. __decorate([
  76641. BABYLON.serialize()
  76642. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76643. return DefaultRenderingPipeline;
  76644. }(BABYLON.PostProcessRenderPipeline));
  76645. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76646. })(BABYLON || (BABYLON = {}));
  76647. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76648. var BABYLON;
  76649. (function (BABYLON) {
  76650. /**
  76651. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76652. */
  76653. var GeometryBufferRenderer = /** @class */ (function () {
  76654. /**
  76655. * Creates a new G Buffer for the scene
  76656. * @param scene The scene the buffer belongs to
  76657. * @param ratio How big is the buffer related to the main canvas.
  76658. */
  76659. function GeometryBufferRenderer(scene, ratio) {
  76660. if (ratio === void 0) { ratio = 1; }
  76661. this._enablePosition = false;
  76662. this._scene = scene;
  76663. this._ratio = ratio;
  76664. // Render target
  76665. this._createRenderTargets();
  76666. }
  76667. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76668. /**
  76669. * Set the render list (meshes to be rendered) used in the G buffer.
  76670. */
  76671. set: function (meshes) {
  76672. this._multiRenderTarget.renderList = meshes;
  76673. },
  76674. enumerable: true,
  76675. configurable: true
  76676. });
  76677. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76678. /**
  76679. * Gets wether or not G buffer are supported by the running hardware.
  76680. * This requires draw buffer supports
  76681. */
  76682. get: function () {
  76683. return this._multiRenderTarget.isSupported;
  76684. },
  76685. enumerable: true,
  76686. configurable: true
  76687. });
  76688. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76689. /**
  76690. * Gets wether or not position are enabled for the G buffer.
  76691. */
  76692. get: function () {
  76693. return this._enablePosition;
  76694. },
  76695. /**
  76696. * Sets wether or not position are enabled for the G buffer.
  76697. */
  76698. set: function (enable) {
  76699. this._enablePosition = enable;
  76700. this.dispose();
  76701. this._createRenderTargets();
  76702. },
  76703. enumerable: true,
  76704. configurable: true
  76705. });
  76706. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76707. /**
  76708. * Gets the scene associated with the buffer.
  76709. */
  76710. get: function () {
  76711. return this._scene;
  76712. },
  76713. enumerable: true,
  76714. configurable: true
  76715. });
  76716. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76717. /**
  76718. * Gets the ratio used by the buffer during its creation.
  76719. * How big is the buffer related to the main canvas.
  76720. */
  76721. get: function () {
  76722. return this._ratio;
  76723. },
  76724. enumerable: true,
  76725. configurable: true
  76726. });
  76727. /**
  76728. * Checks wether everything is ready to render a submesh to the G buffer.
  76729. * @param subMesh the submesh to check readiness for
  76730. * @param useInstances is the mesh drawn using instance or not
  76731. * @returns true if ready otherwise false
  76732. */
  76733. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76734. var material = subMesh.getMaterial();
  76735. if (material && material.disableDepthWrite) {
  76736. return false;
  76737. }
  76738. var defines = [];
  76739. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76740. var mesh = subMesh.getMesh();
  76741. // Alpha test
  76742. if (material && material.needAlphaTesting()) {
  76743. defines.push("#define ALPHATEST");
  76744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76745. attribs.push(BABYLON.VertexBuffer.UVKind);
  76746. defines.push("#define UV1");
  76747. }
  76748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76750. defines.push("#define UV2");
  76751. }
  76752. }
  76753. // Buffers
  76754. if (this._enablePosition) {
  76755. defines.push("#define POSITION");
  76756. }
  76757. // Bones
  76758. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76759. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76760. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76761. if (mesh.numBoneInfluencers > 4) {
  76762. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76763. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76764. }
  76765. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76766. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76767. }
  76768. else {
  76769. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76770. }
  76771. // Instances
  76772. if (useInstances) {
  76773. defines.push("#define INSTANCES");
  76774. attribs.push("world0");
  76775. attribs.push("world1");
  76776. attribs.push("world2");
  76777. attribs.push("world3");
  76778. }
  76779. // Get correct effect
  76780. var join = defines.join("\n");
  76781. if (this._cachedDefines !== join) {
  76782. this._cachedDefines = join;
  76783. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76784. }
  76785. return this._effect.isReady();
  76786. };
  76787. /**
  76788. * Gets the current underlying G Buffer.
  76789. * @returns the buffer
  76790. */
  76791. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76792. return this._multiRenderTarget;
  76793. };
  76794. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76795. /**
  76796. * Gets the number of samples used to render the buffer (anti aliasing).
  76797. */
  76798. get: function () {
  76799. return this._multiRenderTarget.samples;
  76800. },
  76801. /**
  76802. * Sets the number of samples used to render the buffer (anti aliasing).
  76803. */
  76804. set: function (value) {
  76805. this._multiRenderTarget.samples = value;
  76806. },
  76807. enumerable: true,
  76808. configurable: true
  76809. });
  76810. /**
  76811. * Disposes the renderer and frees up associated resources.
  76812. */
  76813. GeometryBufferRenderer.prototype.dispose = function () {
  76814. this.getGBuffer().dispose();
  76815. };
  76816. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76817. var _this = this;
  76818. var engine = this._scene.getEngine();
  76819. var count = this._enablePosition ? 3 : 2;
  76820. 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 });
  76821. if (!this.isSupported) {
  76822. return;
  76823. }
  76824. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76825. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76826. this._multiRenderTarget.refreshRate = 1;
  76827. this._multiRenderTarget.renderParticles = false;
  76828. this._multiRenderTarget.renderList = null;
  76829. // set default depth value to 1.0 (far away)
  76830. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76831. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76832. });
  76833. // Custom render function
  76834. var renderSubMesh = function (subMesh) {
  76835. var mesh = subMesh.getRenderingMesh();
  76836. var scene = _this._scene;
  76837. var engine = scene.getEngine();
  76838. var material = subMesh.getMaterial();
  76839. if (!material) {
  76840. return;
  76841. }
  76842. // Culling
  76843. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76844. // Managing instances
  76845. var batch = mesh._getInstancesRenderList(subMesh._id);
  76846. if (batch.mustReturn) {
  76847. return;
  76848. }
  76849. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76850. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76851. engine.enableEffect(_this._effect);
  76852. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76853. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76854. _this._effect.setMatrix("view", scene.getViewMatrix());
  76855. // Alpha test
  76856. if (material && material.needAlphaTesting()) {
  76857. var alphaTexture = material.getAlphaTestTexture();
  76858. if (alphaTexture) {
  76859. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76860. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76861. }
  76862. }
  76863. // Bones
  76864. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76865. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76866. }
  76867. // Draw
  76868. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76869. }
  76870. };
  76871. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76872. var index;
  76873. if (depthOnlySubMeshes.length) {
  76874. engine.setColorWrite(false);
  76875. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76876. renderSubMesh(depthOnlySubMeshes.data[index]);
  76877. }
  76878. engine.setColorWrite(true);
  76879. }
  76880. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76881. renderSubMesh(opaqueSubMeshes.data[index]);
  76882. }
  76883. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76884. renderSubMesh(alphaTestSubMeshes.data[index]);
  76885. }
  76886. };
  76887. };
  76888. return GeometryBufferRenderer;
  76889. }());
  76890. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76891. })(BABYLON || (BABYLON = {}));
  76892. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76893. var BABYLON;
  76894. (function (BABYLON) {
  76895. /**
  76896. * This groups together the common properties used for image processing either in direct forward pass
  76897. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76898. * or not.
  76899. */
  76900. var ImageProcessingConfiguration = /** @class */ (function () {
  76901. function ImageProcessingConfiguration() {
  76902. /**
  76903. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76904. */
  76905. this.colorCurves = new BABYLON.ColorCurves();
  76906. this._colorCurvesEnabled = false;
  76907. this._colorGradingEnabled = false;
  76908. this._colorGradingWithGreenDepth = true;
  76909. this._colorGradingBGR = true;
  76910. this._exposure = 1.0;
  76911. this._toneMappingEnabled = false;
  76912. this._contrast = 1.0;
  76913. /**
  76914. * Vignette stretch size.
  76915. */
  76916. this.vignetteStretch = 0;
  76917. /**
  76918. * Vignette centre X Offset.
  76919. */
  76920. this.vignetteCentreX = 0;
  76921. /**
  76922. * Vignette centre Y Offset.
  76923. */
  76924. this.vignetteCentreY = 0;
  76925. /**
  76926. * Vignette weight or intensity of the vignette effect.
  76927. */
  76928. this.vignetteWeight = 1.5;
  76929. /**
  76930. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76931. * if vignetteEnabled is set to true.
  76932. */
  76933. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76934. /**
  76935. * Camera field of view used by the Vignette effect.
  76936. */
  76937. this.vignetteCameraFov = 0.5;
  76938. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76939. this._vignetteEnabled = false;
  76940. this._applyByPostProcess = false;
  76941. this._isEnabled = true;
  76942. /**
  76943. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76944. */
  76945. this.onUpdateParameters = new BABYLON.Observable();
  76946. }
  76947. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76948. /**
  76949. * Gets wether the color curves effect is enabled.
  76950. */
  76951. get: function () {
  76952. return this._colorCurvesEnabled;
  76953. },
  76954. /**
  76955. * Sets wether the color curves effect is enabled.
  76956. */
  76957. set: function (value) {
  76958. if (this._colorCurvesEnabled === value) {
  76959. return;
  76960. }
  76961. this._colorCurvesEnabled = value;
  76962. this._updateParameters();
  76963. },
  76964. enumerable: true,
  76965. configurable: true
  76966. });
  76967. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76968. /**
  76969. * Gets wether the color grading effect is enabled.
  76970. */
  76971. get: function () {
  76972. return this._colorGradingEnabled;
  76973. },
  76974. /**
  76975. * Sets wether the color grading effect is enabled.
  76976. */
  76977. set: function (value) {
  76978. if (this._colorGradingEnabled === value) {
  76979. return;
  76980. }
  76981. this._colorGradingEnabled = value;
  76982. this._updateParameters();
  76983. },
  76984. enumerable: true,
  76985. configurable: true
  76986. });
  76987. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76988. /**
  76989. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76990. */
  76991. get: function () {
  76992. return this._colorGradingWithGreenDepth;
  76993. },
  76994. /**
  76995. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76996. */
  76997. set: function (value) {
  76998. if (this._colorGradingWithGreenDepth === value) {
  76999. return;
  77000. }
  77001. this._colorGradingWithGreenDepth = value;
  77002. this._updateParameters();
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77008. /**
  77009. * Gets wether the color grading texture contains BGR values.
  77010. */
  77011. get: function () {
  77012. return this._colorGradingBGR;
  77013. },
  77014. /**
  77015. * Sets wether the color grading texture contains BGR values.
  77016. */
  77017. set: function (value) {
  77018. if (this._colorGradingBGR === value) {
  77019. return;
  77020. }
  77021. this._colorGradingBGR = value;
  77022. this._updateParameters();
  77023. },
  77024. enumerable: true,
  77025. configurable: true
  77026. });
  77027. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77028. /**
  77029. * Gets the Exposure used in the effect.
  77030. */
  77031. get: function () {
  77032. return this._exposure;
  77033. },
  77034. /**
  77035. * Sets the Exposure used in the effect.
  77036. */
  77037. set: function (value) {
  77038. if (this._exposure === value) {
  77039. return;
  77040. }
  77041. this._exposure = value;
  77042. this._updateParameters();
  77043. },
  77044. enumerable: true,
  77045. configurable: true
  77046. });
  77047. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77048. /**
  77049. * Gets wether the tone mapping effect is enabled.
  77050. */
  77051. get: function () {
  77052. return this._toneMappingEnabled;
  77053. },
  77054. /**
  77055. * Sets wether the tone mapping effect is enabled.
  77056. */
  77057. set: function (value) {
  77058. if (this._toneMappingEnabled === value) {
  77059. return;
  77060. }
  77061. this._toneMappingEnabled = value;
  77062. this._updateParameters();
  77063. },
  77064. enumerable: true,
  77065. configurable: true
  77066. });
  77067. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77068. /**
  77069. * Gets the contrast used in the effect.
  77070. */
  77071. get: function () {
  77072. return this._contrast;
  77073. },
  77074. /**
  77075. * Sets the contrast used in the effect.
  77076. */
  77077. set: function (value) {
  77078. if (this._contrast === value) {
  77079. return;
  77080. }
  77081. this._contrast = value;
  77082. this._updateParameters();
  77083. },
  77084. enumerable: true,
  77085. configurable: true
  77086. });
  77087. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77088. /**
  77089. * Gets the vignette blend mode allowing different kind of effect.
  77090. */
  77091. get: function () {
  77092. return this._vignetteBlendMode;
  77093. },
  77094. /**
  77095. * Sets the vignette blend mode allowing different kind of effect.
  77096. */
  77097. set: function (value) {
  77098. if (this._vignetteBlendMode === value) {
  77099. return;
  77100. }
  77101. this._vignetteBlendMode = value;
  77102. this._updateParameters();
  77103. },
  77104. enumerable: true,
  77105. configurable: true
  77106. });
  77107. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77108. /**
  77109. * Gets wether the vignette effect is enabled.
  77110. */
  77111. get: function () {
  77112. return this._vignetteEnabled;
  77113. },
  77114. /**
  77115. * Sets wether the vignette effect is enabled.
  77116. */
  77117. set: function (value) {
  77118. if (this._vignetteEnabled === value) {
  77119. return;
  77120. }
  77121. this._vignetteEnabled = value;
  77122. this._updateParameters();
  77123. },
  77124. enumerable: true,
  77125. configurable: true
  77126. });
  77127. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77128. /**
  77129. * Gets wether the image processing is applied through a post process or not.
  77130. */
  77131. get: function () {
  77132. return this._applyByPostProcess;
  77133. },
  77134. /**
  77135. * Sets wether the image processing is applied through a post process or not.
  77136. */
  77137. set: function (value) {
  77138. if (this._applyByPostProcess === value) {
  77139. return;
  77140. }
  77141. this._applyByPostProcess = value;
  77142. this._updateParameters();
  77143. },
  77144. enumerable: true,
  77145. configurable: true
  77146. });
  77147. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77148. /**
  77149. * Gets wether the image processing is enabled or not.
  77150. */
  77151. get: function () {
  77152. return this._isEnabled;
  77153. },
  77154. /**
  77155. * Sets wether the image processing is enabled or not.
  77156. */
  77157. set: function (value) {
  77158. if (this._isEnabled === value) {
  77159. return;
  77160. }
  77161. this._isEnabled = value;
  77162. this._updateParameters();
  77163. },
  77164. enumerable: true,
  77165. configurable: true
  77166. });
  77167. /**
  77168. * Method called each time the image processing information changes requires to recompile the effect.
  77169. */
  77170. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77171. this.onUpdateParameters.notifyObservers(this);
  77172. };
  77173. ImageProcessingConfiguration.prototype.getClassName = function () {
  77174. return "ImageProcessingConfiguration";
  77175. };
  77176. /**
  77177. * Prepare the list of uniforms associated with the Image Processing effects.
  77178. * @param uniformsList The list of uniforms used in the effect
  77179. * @param defines the list of defines currently in use
  77180. */
  77181. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77182. if (defines.EXPOSURE) {
  77183. uniforms.push("exposureLinear");
  77184. }
  77185. if (defines.CONTRAST) {
  77186. uniforms.push("contrast");
  77187. }
  77188. if (defines.COLORGRADING) {
  77189. uniforms.push("colorTransformSettings");
  77190. }
  77191. if (defines.VIGNETTE) {
  77192. uniforms.push("vInverseScreenSize");
  77193. uniforms.push("vignetteSettings1");
  77194. uniforms.push("vignetteSettings2");
  77195. }
  77196. if (defines.COLORCURVES) {
  77197. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77198. }
  77199. };
  77200. /**
  77201. * Prepare the list of samplers associated with the Image Processing effects.
  77202. * @param uniformsList The list of uniforms used in the effect
  77203. * @param defines the list of defines currently in use
  77204. */
  77205. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77206. if (defines.COLORGRADING) {
  77207. samplersList.push("txColorTransform");
  77208. }
  77209. };
  77210. /**
  77211. * Prepare the list of defines associated to the shader.
  77212. * @param defines the list of defines to complete
  77213. */
  77214. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77215. if (forPostProcess === void 0) { forPostProcess = false; }
  77216. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77217. defines.VIGNETTE = false;
  77218. defines.TONEMAPPING = false;
  77219. defines.CONTRAST = false;
  77220. defines.EXPOSURE = false;
  77221. defines.COLORCURVES = false;
  77222. defines.COLORGRADING = false;
  77223. defines.COLORGRADING3D = false;
  77224. defines.IMAGEPROCESSING = false;
  77225. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77226. return;
  77227. }
  77228. defines.VIGNETTE = this.vignetteEnabled;
  77229. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77230. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77231. defines.TONEMAPPING = this.toneMappingEnabled;
  77232. defines.CONTRAST = (this.contrast !== 1.0);
  77233. defines.EXPOSURE = (this.exposure !== 1.0);
  77234. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77235. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77236. if (defines.COLORGRADING) {
  77237. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77238. }
  77239. else {
  77240. defines.COLORGRADING3D = false;
  77241. }
  77242. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77243. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77244. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77245. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77246. };
  77247. /**
  77248. * Returns true if all the image processing information are ready.
  77249. */
  77250. ImageProcessingConfiguration.prototype.isReady = function () {
  77251. // Color Grading texure can not be none blocking.
  77252. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77253. };
  77254. /**
  77255. * Binds the image processing to the shader.
  77256. * @param effect The effect to bind to
  77257. */
  77258. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77259. if (aspectRatio === void 0) { aspectRatio = 1; }
  77260. // Color Curves
  77261. if (this._colorCurvesEnabled && this.colorCurves) {
  77262. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77263. }
  77264. // Vignette
  77265. if (this._vignetteEnabled) {
  77266. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77267. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77268. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77269. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77270. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77271. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77272. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77273. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77274. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77275. var vignettePower = -2.0 * this.vignetteWeight;
  77276. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77277. }
  77278. // Exposure
  77279. effect.setFloat("exposureLinear", this.exposure);
  77280. // Contrast
  77281. effect.setFloat("contrast", this.contrast);
  77282. // Color transform settings
  77283. if (this.colorGradingTexture) {
  77284. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77285. var textureSize = this.colorGradingTexture.getSize().height;
  77286. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77287. 0.5 / textureSize, // textureOffset
  77288. textureSize, // textureSize
  77289. this.colorGradingTexture.level // weight
  77290. );
  77291. }
  77292. };
  77293. /**
  77294. * Clones the current image processing instance.
  77295. * @return The cloned image processing
  77296. */
  77297. ImageProcessingConfiguration.prototype.clone = function () {
  77298. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77299. };
  77300. /**
  77301. * Serializes the current image processing instance to a json representation.
  77302. * @return a JSON representation
  77303. */
  77304. ImageProcessingConfiguration.prototype.serialize = function () {
  77305. return BABYLON.SerializationHelper.Serialize(this);
  77306. };
  77307. /**
  77308. * Parses the image processing from a json representation.
  77309. * @param source the JSON source to parse
  77310. * @return The parsed image processing
  77311. */
  77312. ImageProcessingConfiguration.Parse = function (source) {
  77313. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77314. };
  77315. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77316. /**
  77317. * Used to apply the vignette as a mix with the pixel color.
  77318. */
  77319. get: function () {
  77320. return this._VIGNETTEMODE_MULTIPLY;
  77321. },
  77322. enumerable: true,
  77323. configurable: true
  77324. });
  77325. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77326. /**
  77327. * Used to apply the vignette as a replacement of the pixel color.
  77328. */
  77329. get: function () {
  77330. return this._VIGNETTEMODE_OPAQUE;
  77331. },
  77332. enumerable: true,
  77333. configurable: true
  77334. });
  77335. // Static constants associated to the image processing.
  77336. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77337. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77338. __decorate([
  77339. BABYLON.serializeAsColorCurves()
  77340. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77341. __decorate([
  77342. BABYLON.serialize()
  77343. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77344. __decorate([
  77345. BABYLON.serializeAsTexture()
  77346. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77347. __decorate([
  77348. BABYLON.serialize()
  77349. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77350. __decorate([
  77351. BABYLON.serialize()
  77352. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77353. __decorate([
  77354. BABYLON.serialize()
  77355. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77356. __decorate([
  77357. BABYLON.serialize()
  77358. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77359. __decorate([
  77360. BABYLON.serialize()
  77361. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77362. __decorate([
  77363. BABYLON.serialize()
  77364. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77365. __decorate([
  77366. BABYLON.serialize()
  77367. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77368. __decorate([
  77369. BABYLON.serialize()
  77370. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77371. __decorate([
  77372. BABYLON.serialize()
  77373. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77374. __decorate([
  77375. BABYLON.serialize()
  77376. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77377. __decorate([
  77378. BABYLON.serializeAsColor4()
  77379. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77380. __decorate([
  77381. BABYLON.serialize()
  77382. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77383. __decorate([
  77384. BABYLON.serialize()
  77385. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77386. __decorate([
  77387. BABYLON.serialize()
  77388. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77389. __decorate([
  77390. BABYLON.serialize()
  77391. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77392. __decorate([
  77393. BABYLON.serialize()
  77394. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77395. return ImageProcessingConfiguration;
  77396. }());
  77397. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77398. })(BABYLON || (BABYLON = {}));
  77399. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77400. var BABYLON;
  77401. (function (BABYLON) {
  77402. /**
  77403. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77404. * It can help converting any input color in a desired output one. This can then be used to create effects
  77405. * from sepia, black and white to sixties or futuristic rendering...
  77406. *
  77407. * The only supported format is currently 3dl.
  77408. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77409. */
  77410. var ColorGradingTexture = /** @class */ (function (_super) {
  77411. __extends(ColorGradingTexture, _super);
  77412. /**
  77413. * Instantiates a ColorGradingTexture from the following parameters.
  77414. *
  77415. * @param url The location of the color gradind data (currently only supporting 3dl)
  77416. * @param scene The scene the texture will be used in
  77417. */
  77418. function ColorGradingTexture(url, scene) {
  77419. var _this = _super.call(this, scene) || this;
  77420. if (!url) {
  77421. return _this;
  77422. }
  77423. _this._engine = scene.getEngine();
  77424. _this._textureMatrix = BABYLON.Matrix.Identity();
  77425. _this.name = url;
  77426. _this.url = url;
  77427. _this.hasAlpha = false;
  77428. _this.isCube = false;
  77429. _this.is3D = _this._engine.webGLVersion > 1;
  77430. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77431. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77432. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77433. _this.anisotropicFilteringLevel = 1;
  77434. _this._texture = _this._getFromCache(url, true);
  77435. if (!_this._texture) {
  77436. if (!scene.useDelayedTextureLoading) {
  77437. _this.loadTexture();
  77438. }
  77439. else {
  77440. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77441. }
  77442. }
  77443. return _this;
  77444. }
  77445. /**
  77446. * Returns the texture matrix used in most of the material.
  77447. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77448. */
  77449. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77450. return this._textureMatrix;
  77451. };
  77452. /**
  77453. * Occurs when the file being loaded is a .3dl LUT file.
  77454. */
  77455. ColorGradingTexture.prototype.load3dlTexture = function () {
  77456. var engine = this._engine;
  77457. var texture;
  77458. if (engine.webGLVersion === 1) {
  77459. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77460. }
  77461. else {
  77462. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77463. }
  77464. this._texture = texture;
  77465. var callback = function (text) {
  77466. if (typeof text !== "string") {
  77467. return;
  77468. }
  77469. var data = null;
  77470. var tempData = null;
  77471. var line;
  77472. var lines = text.split('\n');
  77473. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77474. var maxColor = 0;
  77475. for (var i = 0; i < lines.length; i++) {
  77476. line = lines[i];
  77477. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77478. continue;
  77479. if (line.indexOf('#') === 0)
  77480. continue;
  77481. var words = line.split(" ");
  77482. if (size === 0) {
  77483. // Number of space + one
  77484. size = words.length;
  77485. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77486. tempData = new Float32Array(size * size * size * 4);
  77487. continue;
  77488. }
  77489. if (size != 0) {
  77490. var r = Math.max(parseInt(words[0]), 0);
  77491. var g = Math.max(parseInt(words[1]), 0);
  77492. var b = Math.max(parseInt(words[2]), 0);
  77493. maxColor = Math.max(r, maxColor);
  77494. maxColor = Math.max(g, maxColor);
  77495. maxColor = Math.max(b, maxColor);
  77496. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77497. if (tempData) {
  77498. tempData[pixelStorageIndex + 0] = r;
  77499. tempData[pixelStorageIndex + 1] = g;
  77500. tempData[pixelStorageIndex + 2] = b;
  77501. }
  77502. pixelIndexSlice++;
  77503. if (pixelIndexSlice % size == 0) {
  77504. pixelIndexH++;
  77505. pixelIndexSlice = 0;
  77506. if (pixelIndexH % size == 0) {
  77507. pixelIndexW++;
  77508. pixelIndexH = 0;
  77509. }
  77510. }
  77511. }
  77512. }
  77513. if (tempData && data) {
  77514. for (var i = 0; i < tempData.length; i++) {
  77515. if (i > 0 && (i + 1) % 4 === 0) {
  77516. data[i] = 255;
  77517. }
  77518. else {
  77519. var value = tempData[i];
  77520. data[i] = (value / maxColor * 255);
  77521. }
  77522. }
  77523. }
  77524. if (texture.is3D) {
  77525. texture.updateSize(size, size, size);
  77526. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77527. }
  77528. else {
  77529. texture.updateSize(size * size, size);
  77530. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77531. }
  77532. };
  77533. var scene = this.getScene();
  77534. if (scene) {
  77535. scene._loadFile(this.url, callback);
  77536. }
  77537. else {
  77538. this._engine._loadFile(this.url, callback);
  77539. }
  77540. return this._texture;
  77541. };
  77542. /**
  77543. * Starts the loading process of the texture.
  77544. */
  77545. ColorGradingTexture.prototype.loadTexture = function () {
  77546. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77547. this.load3dlTexture();
  77548. }
  77549. };
  77550. /**
  77551. * Clones the color gradind texture.
  77552. */
  77553. ColorGradingTexture.prototype.clone = function () {
  77554. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77555. // Base texture
  77556. newTexture.level = this.level;
  77557. return newTexture;
  77558. };
  77559. /**
  77560. * Called during delayed load for textures.
  77561. */
  77562. ColorGradingTexture.prototype.delayLoad = function () {
  77563. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77564. return;
  77565. }
  77566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77567. this._texture = this._getFromCache(this.url, true);
  77568. if (!this._texture) {
  77569. this.loadTexture();
  77570. }
  77571. };
  77572. /**
  77573. * Parses a color grading texture serialized by Babylon.
  77574. * @param parsedTexture The texture information being parsedTexture
  77575. * @param scene The scene to load the texture in
  77576. * @param rootUrl The root url of the data assets to load
  77577. * @return A color gradind texture
  77578. */
  77579. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77580. var texture = null;
  77581. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77582. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77583. texture.name = parsedTexture.name;
  77584. texture.level = parsedTexture.level;
  77585. }
  77586. return texture;
  77587. };
  77588. /**
  77589. * Serializes the LUT texture to json format.
  77590. */
  77591. ColorGradingTexture.prototype.serialize = function () {
  77592. if (!this.name) {
  77593. return null;
  77594. }
  77595. var serializationObject = {};
  77596. serializationObject.name = this.name;
  77597. serializationObject.level = this.level;
  77598. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77599. return serializationObject;
  77600. };
  77601. /**
  77602. * Empty line regex stored for GC.
  77603. */
  77604. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77605. return ColorGradingTexture;
  77606. }(BABYLON.BaseTexture));
  77607. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77608. })(BABYLON || (BABYLON = {}));
  77609. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77610. var BABYLON;
  77611. (function (BABYLON) {
  77612. /**
  77613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77615. * 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;
  77616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77617. */
  77618. var ColorCurves = /** @class */ (function () {
  77619. function ColorCurves() {
  77620. this._dirty = true;
  77621. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77622. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77623. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77624. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77625. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77626. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77627. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77628. this._globalHue = 30;
  77629. this._globalDensity = 0;
  77630. this._globalSaturation = 0;
  77631. this._globalExposure = 0;
  77632. this._highlightsHue = 30;
  77633. this._highlightsDensity = 0;
  77634. this._highlightsSaturation = 0;
  77635. this._highlightsExposure = 0;
  77636. this._midtonesHue = 30;
  77637. this._midtonesDensity = 0;
  77638. this._midtonesSaturation = 0;
  77639. this._midtonesExposure = 0;
  77640. this._shadowsHue = 30;
  77641. this._shadowsDensity = 0;
  77642. this._shadowsSaturation = 0;
  77643. this._shadowsExposure = 0;
  77644. }
  77645. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77646. /**
  77647. * Gets the global Hue value.
  77648. * 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).
  77649. */
  77650. get: function () {
  77651. return this._globalHue;
  77652. },
  77653. /**
  77654. * Sets the global Hue value.
  77655. * 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).
  77656. */
  77657. set: function (value) {
  77658. this._globalHue = value;
  77659. this._dirty = true;
  77660. },
  77661. enumerable: true,
  77662. configurable: true
  77663. });
  77664. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77665. /**
  77666. * Gets the global Density value.
  77667. * 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.
  77668. * Values less than zero provide a filter of opposite hue.
  77669. */
  77670. get: function () {
  77671. return this._globalDensity;
  77672. },
  77673. /**
  77674. * Sets the global Density value.
  77675. * 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.
  77676. * Values less than zero provide a filter of opposite hue.
  77677. */
  77678. set: function (value) {
  77679. this._globalDensity = value;
  77680. this._dirty = true;
  77681. },
  77682. enumerable: true,
  77683. configurable: true
  77684. });
  77685. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77686. /**
  77687. * Gets the global Saturation value.
  77688. * 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.
  77689. */
  77690. get: function () {
  77691. return this._globalSaturation;
  77692. },
  77693. /**
  77694. * Sets the global Saturation value.
  77695. * 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.
  77696. */
  77697. set: function (value) {
  77698. this._globalSaturation = value;
  77699. this._dirty = true;
  77700. },
  77701. enumerable: true,
  77702. configurable: true
  77703. });
  77704. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77705. /**
  77706. * Gets the global Exposure value.
  77707. * 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.
  77708. */
  77709. get: function () {
  77710. return this._globalExposure;
  77711. },
  77712. /**
  77713. * Sets the global Exposure value.
  77714. * 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.
  77715. */
  77716. set: function (value) {
  77717. this._globalExposure = value;
  77718. this._dirty = true;
  77719. },
  77720. enumerable: true,
  77721. configurable: true
  77722. });
  77723. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77724. /**
  77725. * Gets the highlights Hue value.
  77726. * 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).
  77727. */
  77728. get: function () {
  77729. return this._highlightsHue;
  77730. },
  77731. /**
  77732. * Sets the highlights Hue value.
  77733. * 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).
  77734. */
  77735. set: function (value) {
  77736. this._highlightsHue = value;
  77737. this._dirty = true;
  77738. },
  77739. enumerable: true,
  77740. configurable: true
  77741. });
  77742. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77743. /**
  77744. * Gets the highlights Density value.
  77745. * 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.
  77746. * Values less than zero provide a filter of opposite hue.
  77747. */
  77748. get: function () {
  77749. return this._highlightsDensity;
  77750. },
  77751. /**
  77752. * Sets the highlights Density value.
  77753. * 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.
  77754. * Values less than zero provide a filter of opposite hue.
  77755. */
  77756. set: function (value) {
  77757. this._highlightsDensity = value;
  77758. this._dirty = true;
  77759. },
  77760. enumerable: true,
  77761. configurable: true
  77762. });
  77763. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77764. /**
  77765. * Gets the highlights Saturation value.
  77766. * 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.
  77767. */
  77768. get: function () {
  77769. return this._highlightsSaturation;
  77770. },
  77771. /**
  77772. * Sets the highlights Saturation value.
  77773. * 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.
  77774. */
  77775. set: function (value) {
  77776. this._highlightsSaturation = value;
  77777. this._dirty = true;
  77778. },
  77779. enumerable: true,
  77780. configurable: true
  77781. });
  77782. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77783. /**
  77784. * Gets the highlights Exposure value.
  77785. * 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.
  77786. */
  77787. get: function () {
  77788. return this._highlightsExposure;
  77789. },
  77790. /**
  77791. * Sets the highlights Exposure value.
  77792. * 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.
  77793. */
  77794. set: function (value) {
  77795. this._highlightsExposure = value;
  77796. this._dirty = true;
  77797. },
  77798. enumerable: true,
  77799. configurable: true
  77800. });
  77801. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77802. /**
  77803. * Gets the midtones Hue value.
  77804. * 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).
  77805. */
  77806. get: function () {
  77807. return this._midtonesHue;
  77808. },
  77809. /**
  77810. * Sets the midtones Hue value.
  77811. * 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).
  77812. */
  77813. set: function (value) {
  77814. this._midtonesHue = value;
  77815. this._dirty = true;
  77816. },
  77817. enumerable: true,
  77818. configurable: true
  77819. });
  77820. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77821. /**
  77822. * Gets the midtones Density value.
  77823. * 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.
  77824. * Values less than zero provide a filter of opposite hue.
  77825. */
  77826. get: function () {
  77827. return this._midtonesDensity;
  77828. },
  77829. /**
  77830. * Sets the midtones Density value.
  77831. * 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.
  77832. * Values less than zero provide a filter of opposite hue.
  77833. */
  77834. set: function (value) {
  77835. this._midtonesDensity = value;
  77836. this._dirty = true;
  77837. },
  77838. enumerable: true,
  77839. configurable: true
  77840. });
  77841. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77842. /**
  77843. * Gets the midtones Saturation value.
  77844. * 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.
  77845. */
  77846. get: function () {
  77847. return this._midtonesSaturation;
  77848. },
  77849. /**
  77850. * Sets the midtones Saturation value.
  77851. * 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.
  77852. */
  77853. set: function (value) {
  77854. this._midtonesSaturation = value;
  77855. this._dirty = true;
  77856. },
  77857. enumerable: true,
  77858. configurable: true
  77859. });
  77860. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77861. /**
  77862. * Gets the midtones Exposure value.
  77863. * 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.
  77864. */
  77865. get: function () {
  77866. return this._midtonesExposure;
  77867. },
  77868. /**
  77869. * Sets the midtones Exposure value.
  77870. * 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.
  77871. */
  77872. set: function (value) {
  77873. this._midtonesExposure = value;
  77874. this._dirty = true;
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77880. /**
  77881. * Gets the shadows Hue value.
  77882. * 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).
  77883. */
  77884. get: function () {
  77885. return this._shadowsHue;
  77886. },
  77887. /**
  77888. * Sets the shadows Hue value.
  77889. * 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).
  77890. */
  77891. set: function (value) {
  77892. this._shadowsHue = value;
  77893. this._dirty = true;
  77894. },
  77895. enumerable: true,
  77896. configurable: true
  77897. });
  77898. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77899. /**
  77900. * Gets the shadows Density value.
  77901. * 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.
  77902. * Values less than zero provide a filter of opposite hue.
  77903. */
  77904. get: function () {
  77905. return this._shadowsDensity;
  77906. },
  77907. /**
  77908. * Sets the shadows Density value.
  77909. * 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.
  77910. * Values less than zero provide a filter of opposite hue.
  77911. */
  77912. set: function (value) {
  77913. this._shadowsDensity = value;
  77914. this._dirty = true;
  77915. },
  77916. enumerable: true,
  77917. configurable: true
  77918. });
  77919. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77920. /**
  77921. * Gets the shadows Saturation value.
  77922. * 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.
  77923. */
  77924. get: function () {
  77925. return this._shadowsSaturation;
  77926. },
  77927. /**
  77928. * Sets the shadows Saturation value.
  77929. * 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.
  77930. */
  77931. set: function (value) {
  77932. this._shadowsSaturation = value;
  77933. this._dirty = true;
  77934. },
  77935. enumerable: true,
  77936. configurable: true
  77937. });
  77938. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77939. /**
  77940. * Gets the shadows Exposure value.
  77941. * 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.
  77942. */
  77943. get: function () {
  77944. return this._shadowsExposure;
  77945. },
  77946. /**
  77947. * Sets the shadows Exposure value.
  77948. * 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.
  77949. */
  77950. set: function (value) {
  77951. this._shadowsExposure = value;
  77952. this._dirty = true;
  77953. },
  77954. enumerable: true,
  77955. configurable: true
  77956. });
  77957. ColorCurves.prototype.getClassName = function () {
  77958. return "ColorCurves";
  77959. };
  77960. /**
  77961. * Binds the color curves to the shader.
  77962. * @param colorCurves The color curve to bind
  77963. * @param effect The effect to bind to
  77964. */
  77965. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77966. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77967. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77968. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77969. if (colorCurves._dirty) {
  77970. colorCurves._dirty = false;
  77971. // Fill in global info.
  77972. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77973. // Compute highlights info.
  77974. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77975. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77976. // Compute midtones info.
  77977. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77978. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77979. // Compute shadows info.
  77980. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77981. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77982. // Compute deltas (neutral is midtones).
  77983. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77984. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77985. }
  77986. if (effect) {
  77987. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77988. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77989. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77990. }
  77991. };
  77992. /**
  77993. * Prepare the list of uniforms associated with the ColorCurves effects.
  77994. * @param uniformsList The list of uniforms used in the effect
  77995. */
  77996. ColorCurves.PrepareUniforms = function (uniformsList) {
  77997. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77998. };
  77999. /**
  78000. * Returns color grading data based on a hue, density, saturation and exposure value.
  78001. * @param filterHue The hue of the color filter.
  78002. * @param filterDensity The density of the color filter.
  78003. * @param saturation The saturation.
  78004. * @param exposure The exposure.
  78005. * @param result The result data container.
  78006. */
  78007. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78008. if (hue == null) {
  78009. return;
  78010. }
  78011. hue = ColorCurves.clamp(hue, 0, 360);
  78012. density = ColorCurves.clamp(density, -100, 100);
  78013. saturation = ColorCurves.clamp(saturation, -100, 100);
  78014. exposure = ColorCurves.clamp(exposure, -100, 100);
  78015. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78016. // so that the maximum filter density is only 50% control. This provides fine control
  78017. // for small values and reasonable range.
  78018. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78019. density *= 0.5;
  78020. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78021. if (density < 0) {
  78022. density *= -1;
  78023. hue = (hue + 180) % 360;
  78024. }
  78025. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78026. result.scaleToRef(2, result);
  78027. result.a = 1 + 0.01 * saturation;
  78028. };
  78029. /**
  78030. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78031. * @param value The input slider value in range [-100,100].
  78032. * @returns Adjusted value.
  78033. */
  78034. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78035. value /= 100;
  78036. var x = Math.abs(value);
  78037. x = Math.pow(x, 2);
  78038. if (value < 0) {
  78039. x *= -1;
  78040. }
  78041. x *= 100;
  78042. return x;
  78043. };
  78044. /**
  78045. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78046. * @param hue The hue (H) input.
  78047. * @param saturation The saturation (S) input.
  78048. * @param brightness The brightness (B) input.
  78049. * @result An RGBA color represented as Vector4.
  78050. */
  78051. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78052. var h = ColorCurves.clamp(hue, 0, 360);
  78053. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78054. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78055. if (s === 0) {
  78056. result.r = v;
  78057. result.g = v;
  78058. result.b = v;
  78059. }
  78060. else {
  78061. // sector 0 to 5
  78062. h /= 60;
  78063. var i = Math.floor(h);
  78064. // fractional part of h
  78065. var f = h - i;
  78066. var p = v * (1 - s);
  78067. var q = v * (1 - s * f);
  78068. var t = v * (1 - s * (1 - f));
  78069. switch (i) {
  78070. case 0:
  78071. result.r = v;
  78072. result.g = t;
  78073. result.b = p;
  78074. break;
  78075. case 1:
  78076. result.r = q;
  78077. result.g = v;
  78078. result.b = p;
  78079. break;
  78080. case 2:
  78081. result.r = p;
  78082. result.g = v;
  78083. result.b = t;
  78084. break;
  78085. case 3:
  78086. result.r = p;
  78087. result.g = q;
  78088. result.b = v;
  78089. break;
  78090. case 4:
  78091. result.r = t;
  78092. result.g = p;
  78093. result.b = v;
  78094. break;
  78095. default: // case 5:
  78096. result.r = v;
  78097. result.g = p;
  78098. result.b = q;
  78099. break;
  78100. }
  78101. }
  78102. result.a = 1;
  78103. };
  78104. /**
  78105. * Returns a value clamped between min and max
  78106. * @param value The value to clamp
  78107. * @param min The minimum of value
  78108. * @param max The maximum of value
  78109. * @returns The clamped value.
  78110. */
  78111. ColorCurves.clamp = function (value, min, max) {
  78112. return Math.min(Math.max(value, min), max);
  78113. };
  78114. /**
  78115. * Clones the current color curve instance.
  78116. * @return The cloned curves
  78117. */
  78118. ColorCurves.prototype.clone = function () {
  78119. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78120. };
  78121. /**
  78122. * Serializes the current color curve instance to a json representation.
  78123. * @return a JSON representation
  78124. */
  78125. ColorCurves.prototype.serialize = function () {
  78126. return BABYLON.SerializationHelper.Serialize(this);
  78127. };
  78128. /**
  78129. * Parses the color curve from a json representation.
  78130. * @param source the JSON source to parse
  78131. * @return The parsed curves
  78132. */
  78133. ColorCurves.Parse = function (source) {
  78134. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78135. };
  78136. __decorate([
  78137. BABYLON.serialize()
  78138. ], ColorCurves.prototype, "_globalHue", void 0);
  78139. __decorate([
  78140. BABYLON.serialize()
  78141. ], ColorCurves.prototype, "_globalDensity", void 0);
  78142. __decorate([
  78143. BABYLON.serialize()
  78144. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78145. __decorate([
  78146. BABYLON.serialize()
  78147. ], ColorCurves.prototype, "_globalExposure", void 0);
  78148. __decorate([
  78149. BABYLON.serialize()
  78150. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78151. __decorate([
  78152. BABYLON.serialize()
  78153. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78154. __decorate([
  78155. BABYLON.serialize()
  78156. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78157. __decorate([
  78158. BABYLON.serialize()
  78159. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78160. __decorate([
  78161. BABYLON.serialize()
  78162. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78163. __decorate([
  78164. BABYLON.serialize()
  78165. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78166. __decorate([
  78167. BABYLON.serialize()
  78168. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78169. __decorate([
  78170. BABYLON.serialize()
  78171. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78172. return ColorCurves;
  78173. }());
  78174. BABYLON.ColorCurves = ColorCurves;
  78175. })(BABYLON || (BABYLON = {}));
  78176. //# sourceMappingURL=babylon.colorCurves.js.map
  78177. var BABYLON;
  78178. (function (BABYLON) {
  78179. var RefractionPostProcess = /** @class */ (function (_super) {
  78180. __extends(RefractionPostProcess, _super);
  78181. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78182. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78183. _this.color = color;
  78184. _this.depth = depth;
  78185. _this.colorLevel = colorLevel;
  78186. _this._ownRefractionTexture = true;
  78187. _this.onActivateObservable.add(function (cam) {
  78188. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78189. });
  78190. _this.onApplyObservable.add(function (effect) {
  78191. effect.setColor3("baseColor", _this.color);
  78192. effect.setFloat("depth", _this.depth);
  78193. effect.setFloat("colorLevel", _this.colorLevel);
  78194. effect.setTexture("refractionSampler", _this._refTexture);
  78195. });
  78196. return _this;
  78197. }
  78198. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78199. /**
  78200. * Gets or sets the refraction texture
  78201. * Please note that you are responsible for disposing the texture if you set it manually
  78202. */
  78203. get: function () {
  78204. return this._refTexture;
  78205. },
  78206. set: function (value) {
  78207. if (this._refTexture && this._ownRefractionTexture) {
  78208. this._refTexture.dispose();
  78209. }
  78210. this._refTexture = value;
  78211. this._ownRefractionTexture = false;
  78212. },
  78213. enumerable: true,
  78214. configurable: true
  78215. });
  78216. // Methods
  78217. RefractionPostProcess.prototype.dispose = function (camera) {
  78218. if (this._refTexture && this._ownRefractionTexture) {
  78219. this._refTexture.dispose();
  78220. this._refTexture = null;
  78221. }
  78222. _super.prototype.dispose.call(this, camera);
  78223. };
  78224. return RefractionPostProcess;
  78225. }(BABYLON.PostProcess));
  78226. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78227. })(BABYLON || (BABYLON = {}));
  78228. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78229. var BABYLON;
  78230. (function (BABYLON) {
  78231. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78232. __extends(BlackAndWhitePostProcess, _super);
  78233. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78234. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78235. _this.degree = 1;
  78236. _this.onApplyObservable.add(function (effect) {
  78237. effect.setFloat("degree", _this.degree);
  78238. });
  78239. return _this;
  78240. }
  78241. return BlackAndWhitePostProcess;
  78242. }(BABYLON.PostProcess));
  78243. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78244. })(BABYLON || (BABYLON = {}));
  78245. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78246. var BABYLON;
  78247. (function (BABYLON) {
  78248. /**
  78249. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78250. * input texture to perform effects such as edge detection or sharpening
  78251. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78252. */
  78253. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78254. __extends(ConvolutionPostProcess, _super);
  78255. /**
  78256. * Creates a new instance ConvolutionPostProcess
  78257. * @param name The name of the effect.
  78258. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78259. * @param options The required width/height ratio to downsize to before computing the render pass.
  78260. * @param camera The camera to apply the render pass to.
  78261. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78262. * @param engine The engine which the post process will be applied. (default: current engine)
  78263. * @param reusable If the post process can be reused on the same frame. (default: false)
  78264. * @param textureType Type of textures used when performing the post process. (default: 0)
  78265. */
  78266. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78267. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78268. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78269. _this.kernel = kernel;
  78270. _this.onApply = function (effect) {
  78271. effect.setFloat2("screenSize", _this.width, _this.height);
  78272. effect.setArray("kernel", _this.kernel);
  78273. };
  78274. return _this;
  78275. }
  78276. // Statics
  78277. /**
  78278. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78279. */
  78280. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78281. /**
  78282. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78283. */
  78284. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78285. /**
  78286. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78287. */
  78288. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78289. /**
  78290. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78291. */
  78292. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78293. /**
  78294. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78295. */
  78296. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78297. /**
  78298. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78299. */
  78300. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78301. return ConvolutionPostProcess;
  78302. }(BABYLON.PostProcess));
  78303. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78304. })(BABYLON || (BABYLON = {}));
  78305. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78306. var BABYLON;
  78307. (function (BABYLON) {
  78308. var FilterPostProcess = /** @class */ (function (_super) {
  78309. __extends(FilterPostProcess, _super);
  78310. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78311. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78312. _this.kernelMatrix = kernelMatrix;
  78313. _this.onApply = function (effect) {
  78314. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78315. };
  78316. return _this;
  78317. }
  78318. return FilterPostProcess;
  78319. }(BABYLON.PostProcess));
  78320. BABYLON.FilterPostProcess = FilterPostProcess;
  78321. })(BABYLON || (BABYLON = {}));
  78322. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78323. var BABYLON;
  78324. (function (BABYLON) {
  78325. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78326. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78327. __extends(VolumetricLightScatteringPostProcess, _super);
  78328. /**
  78329. * @constructor
  78330. * @param {string} name - The post-process name
  78331. * @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)
  78332. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78333. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78334. * @param {number} samples - The post-process quality, default 100
  78335. * @param {number} samplingMode - The post-process filtering mode
  78336. * @param {BABYLON.Engine} engine - The babylon engine
  78337. * @param {boolean} reusable - If the post-process is reusable
  78338. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78339. */
  78340. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78341. if (samples === void 0) { samples = 100; }
  78342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78343. 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;
  78344. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78345. /**
  78346. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78347. */
  78348. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78349. /**
  78350. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78351. */
  78352. _this.useCustomMeshPosition = false;
  78353. /**
  78354. * If the post-process should inverse the light scattering direction
  78355. */
  78356. _this.invert = true;
  78357. /**
  78358. * Array containing the excluded meshes not rendered in the internal pass
  78359. */
  78360. _this.excludedMeshes = new Array();
  78361. /**
  78362. * Controls the overall intensity of the post-process
  78363. */
  78364. _this.exposure = 0.3;
  78365. /**
  78366. * Dissipates each sample's contribution in range [0, 1]
  78367. */
  78368. _this.decay = 0.96815;
  78369. /**
  78370. * Controls the overall intensity of each sample
  78371. */
  78372. _this.weight = 0.58767;
  78373. /**
  78374. * Controls the density of each sample
  78375. */
  78376. _this.density = 0.926;
  78377. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78378. engine = scene.getEngine();
  78379. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78380. // Configure mesh
  78381. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78382. // Configure
  78383. _this._createPass(scene, ratio.passRatio || ratio);
  78384. _this.onActivate = function (camera) {
  78385. if (!_this.isSupported) {
  78386. _this.dispose(camera);
  78387. }
  78388. _this.onActivate = null;
  78389. };
  78390. _this.onApplyObservable.add(function (effect) {
  78391. _this._updateMeshScreenCoordinates(scene);
  78392. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78393. effect.setFloat("exposure", _this.exposure);
  78394. effect.setFloat("decay", _this.decay);
  78395. effect.setFloat("weight", _this.weight);
  78396. effect.setFloat("density", _this.density);
  78397. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78398. });
  78399. return _this;
  78400. }
  78401. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78402. get: function () {
  78403. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78404. return false;
  78405. },
  78406. set: function (useDiffuseColor) {
  78407. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78408. },
  78409. enumerable: true,
  78410. configurable: true
  78411. });
  78412. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78413. return "VolumetricLightScatteringPostProcess";
  78414. };
  78415. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78416. var mesh = subMesh.getMesh();
  78417. // Render this.mesh as default
  78418. if (mesh === this.mesh && mesh.material) {
  78419. return mesh.material.isReady(mesh);
  78420. }
  78421. var defines = [];
  78422. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78423. var material = subMesh.getMaterial();
  78424. // Alpha test
  78425. if (material) {
  78426. if (material.needAlphaTesting()) {
  78427. defines.push("#define ALPHATEST");
  78428. }
  78429. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78430. attribs.push(BABYLON.VertexBuffer.UVKind);
  78431. defines.push("#define UV1");
  78432. }
  78433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78434. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78435. defines.push("#define UV2");
  78436. }
  78437. }
  78438. // Bones
  78439. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78440. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78441. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78442. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78443. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78444. }
  78445. else {
  78446. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78447. }
  78448. // Instances
  78449. if (useInstances) {
  78450. defines.push("#define INSTANCES");
  78451. attribs.push("world0");
  78452. attribs.push("world1");
  78453. attribs.push("world2");
  78454. attribs.push("world3");
  78455. }
  78456. // Get correct effect
  78457. var join = defines.join("\n");
  78458. if (this._cachedDefines !== join) {
  78459. this._cachedDefines = join;
  78460. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78461. }
  78462. return this._volumetricLightScatteringPass.isReady();
  78463. };
  78464. /**
  78465. * Sets the new light position for light scattering effect
  78466. * @param {BABYLON.Vector3} The new custom light position
  78467. */
  78468. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78469. this.customMeshPosition = position;
  78470. };
  78471. /**
  78472. * Returns the light position for light scattering effect
  78473. * @return {BABYLON.Vector3} The custom light position
  78474. */
  78475. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78476. return this.customMeshPosition;
  78477. };
  78478. /**
  78479. * Disposes the internal assets and detaches the post-process from the camera
  78480. */
  78481. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78482. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78483. if (rttIndex !== -1) {
  78484. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78485. }
  78486. this._volumetricLightScatteringRTT.dispose();
  78487. _super.prototype.dispose.call(this, camera);
  78488. };
  78489. /**
  78490. * Returns the render target texture used by the post-process
  78491. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78492. */
  78493. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78494. return this._volumetricLightScatteringRTT;
  78495. };
  78496. // Private methods
  78497. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78498. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78499. return true;
  78500. }
  78501. return false;
  78502. };
  78503. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78504. var _this = this;
  78505. var engine = scene.getEngine();
  78506. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78507. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78508. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78509. this._volumetricLightScatteringRTT.renderList = null;
  78510. this._volumetricLightScatteringRTT.renderParticles = false;
  78511. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78512. var camera = this.getCamera();
  78513. if (camera) {
  78514. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78515. }
  78516. else {
  78517. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78518. }
  78519. // Custom render function for submeshes
  78520. var renderSubMesh = function (subMesh) {
  78521. var mesh = subMesh.getRenderingMesh();
  78522. if (_this._meshExcluded(mesh)) {
  78523. return;
  78524. }
  78525. var material = subMesh.getMaterial();
  78526. if (!material) {
  78527. return;
  78528. }
  78529. var scene = mesh.getScene();
  78530. var engine = scene.getEngine();
  78531. // Culling
  78532. engine.setState(material.backFaceCulling);
  78533. // Managing instances
  78534. var batch = mesh._getInstancesRenderList(subMesh._id);
  78535. if (batch.mustReturn) {
  78536. return;
  78537. }
  78538. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78539. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78540. var effect = _this._volumetricLightScatteringPass;
  78541. if (mesh === _this.mesh) {
  78542. if (subMesh.effect) {
  78543. effect = subMesh.effect;
  78544. }
  78545. else {
  78546. effect = material.getEffect();
  78547. }
  78548. }
  78549. engine.enableEffect(effect);
  78550. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78551. if (mesh === _this.mesh) {
  78552. material.bind(mesh.getWorldMatrix(), mesh);
  78553. }
  78554. else {
  78555. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78556. // Alpha test
  78557. if (material && material.needAlphaTesting()) {
  78558. var alphaTexture = material.getAlphaTestTexture();
  78559. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78560. if (alphaTexture) {
  78561. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78562. }
  78563. }
  78564. // Bones
  78565. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78566. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78567. }
  78568. }
  78569. // Draw
  78570. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78571. }
  78572. };
  78573. // Render target texture callbacks
  78574. var savedSceneClearColor;
  78575. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78576. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78577. savedSceneClearColor = scene.clearColor;
  78578. scene.clearColor = sceneClearColor;
  78579. });
  78580. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78581. scene.clearColor = savedSceneClearColor;
  78582. });
  78583. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78584. var engine = scene.getEngine();
  78585. var index;
  78586. if (depthOnlySubMeshes.length) {
  78587. engine.setColorWrite(false);
  78588. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78589. renderSubMesh(depthOnlySubMeshes.data[index]);
  78590. }
  78591. engine.setColorWrite(true);
  78592. }
  78593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78594. renderSubMesh(opaqueSubMeshes.data[index]);
  78595. }
  78596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78597. renderSubMesh(alphaTestSubMeshes.data[index]);
  78598. }
  78599. if (transparentSubMeshes.length) {
  78600. // Sort sub meshes
  78601. for (index = 0; index < transparentSubMeshes.length; index++) {
  78602. var submesh = transparentSubMeshes.data[index];
  78603. var boundingInfo = submesh.getBoundingInfo();
  78604. if (boundingInfo && scene.activeCamera) {
  78605. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78606. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78607. }
  78608. }
  78609. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78610. sortedArray.sort(function (a, b) {
  78611. // Alpha index first
  78612. if (a._alphaIndex > b._alphaIndex) {
  78613. return 1;
  78614. }
  78615. if (a._alphaIndex < b._alphaIndex) {
  78616. return -1;
  78617. }
  78618. // Then distance to camera
  78619. if (a._distanceToCamera < b._distanceToCamera) {
  78620. return 1;
  78621. }
  78622. if (a._distanceToCamera > b._distanceToCamera) {
  78623. return -1;
  78624. }
  78625. return 0;
  78626. });
  78627. // Render sub meshes
  78628. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78629. for (index = 0; index < sortedArray.length; index++) {
  78630. renderSubMesh(sortedArray[index]);
  78631. }
  78632. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78633. }
  78634. };
  78635. };
  78636. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78637. var transform = scene.getTransformMatrix();
  78638. var meshPosition;
  78639. if (this.useCustomMeshPosition) {
  78640. meshPosition = this.customMeshPosition;
  78641. }
  78642. else if (this.attachedNode) {
  78643. meshPosition = this.attachedNode.position;
  78644. }
  78645. else {
  78646. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78647. }
  78648. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78649. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78650. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78651. if (this.invert)
  78652. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78653. };
  78654. // Static methods
  78655. /**
  78656. * Creates a default mesh for the Volumeric Light Scattering post-process
  78657. * @param {string} The mesh name
  78658. * @param {BABYLON.Scene} The scene where to create the mesh
  78659. * @return {BABYLON.Mesh} the default mesh
  78660. */
  78661. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78662. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78663. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78664. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78665. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78666. mesh.material = material;
  78667. return mesh;
  78668. };
  78669. __decorate([
  78670. BABYLON.serializeAsVector3()
  78671. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78672. __decorate([
  78673. BABYLON.serialize()
  78674. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78675. __decorate([
  78676. BABYLON.serialize()
  78677. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78678. __decorate([
  78679. BABYLON.serializeAsMeshReference()
  78680. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78681. __decorate([
  78682. BABYLON.serialize()
  78683. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78684. __decorate([
  78685. BABYLON.serialize()
  78686. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78687. __decorate([
  78688. BABYLON.serialize()
  78689. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78690. __decorate([
  78691. BABYLON.serialize()
  78692. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78693. __decorate([
  78694. BABYLON.serialize()
  78695. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78696. return VolumetricLightScatteringPostProcess;
  78697. }(BABYLON.PostProcess));
  78698. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78699. })(BABYLON || (BABYLON = {}));
  78700. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78701. //
  78702. // This post-process allows the modification of rendered colors by using
  78703. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78704. //
  78705. // The object needs to be provided an url to a texture containing the color
  78706. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78707. // Use an image editing software to tweak the LUT to match your needs.
  78708. //
  78709. // For an example of a color LUT, see here:
  78710. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78711. // For explanations on color grading, see here:
  78712. // http://udn.epicgames.com/Three/ColorGrading.html
  78713. //
  78714. var BABYLON;
  78715. (function (BABYLON) {
  78716. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78717. __extends(ColorCorrectionPostProcess, _super);
  78718. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78719. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78720. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78721. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78722. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78723. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78724. _this.onApply = function (effect) {
  78725. effect.setTexture("colorTable", _this._colorTableTexture);
  78726. };
  78727. return _this;
  78728. }
  78729. return ColorCorrectionPostProcess;
  78730. }(BABYLON.PostProcess));
  78731. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78732. })(BABYLON || (BABYLON = {}));
  78733. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78734. var BABYLON;
  78735. (function (BABYLON) {
  78736. /** Defines operator used for tonemapping */
  78737. var TonemappingOperator;
  78738. (function (TonemappingOperator) {
  78739. /** Hable */
  78740. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78741. /** Reinhard */
  78742. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78743. /** HejiDawson */
  78744. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78745. /** Photographic */
  78746. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78747. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78748. ;
  78749. /**
  78750. * Defines a post process to apply tone mapping
  78751. */
  78752. var TonemapPostProcess = /** @class */ (function (_super) {
  78753. __extends(TonemapPostProcess, _super);
  78754. /**
  78755. * Creates a new TonemapPostProcess
  78756. * @param name defines the name of the postprocess
  78757. * @param _operator defines the operator to use
  78758. * @param exposureAdjustment defines the required exposure adjustement
  78759. * @param camera defines the camera to use (can be null)
  78760. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78761. * @param engine defines the hosting engine (can be ignore if camera is set)
  78762. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78763. */
  78764. function TonemapPostProcess(name, _operator,
  78765. /** Defines the required exposure adjustement */
  78766. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78768. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78769. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78770. _this._operator = _operator;
  78771. _this.exposureAdjustment = exposureAdjustment;
  78772. var defines = "#define ";
  78773. if (_this._operator === TonemappingOperator.Hable)
  78774. defines += "HABLE_TONEMAPPING";
  78775. else if (_this._operator === TonemappingOperator.Reinhard)
  78776. defines += "REINHARD_TONEMAPPING";
  78777. else if (_this._operator === TonemappingOperator.HejiDawson)
  78778. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78779. else if (_this._operator === TonemappingOperator.Photographic)
  78780. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78781. //sadly a second call to create the effect.
  78782. _this.updateEffect(defines);
  78783. _this.onApply = function (effect) {
  78784. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78785. };
  78786. return _this;
  78787. }
  78788. return TonemapPostProcess;
  78789. }(BABYLON.PostProcess));
  78790. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78791. })(BABYLON || (BABYLON = {}));
  78792. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78793. var BABYLON;
  78794. (function (BABYLON) {
  78795. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78796. __extends(DisplayPassPostProcess, _super);
  78797. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78798. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78799. }
  78800. return DisplayPassPostProcess;
  78801. }(BABYLON.PostProcess));
  78802. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78803. })(BABYLON || (BABYLON = {}));
  78804. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78805. var BABYLON;
  78806. (function (BABYLON) {
  78807. var HighlightsPostProcess = /** @class */ (function (_super) {
  78808. __extends(HighlightsPostProcess, _super);
  78809. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78810. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78811. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78812. }
  78813. return HighlightsPostProcess;
  78814. }(BABYLON.PostProcess));
  78815. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78816. })(BABYLON || (BABYLON = {}));
  78817. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78818. var BABYLON;
  78819. (function (BABYLON) {
  78820. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78821. __extends(ImageProcessingPostProcess, _super);
  78822. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78823. if (camera === void 0) { camera = null; }
  78824. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78825. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78826. _this._fromLinearSpace = true;
  78827. /**
  78828. * Defines cache preventing GC.
  78829. */
  78830. _this._defines = {
  78831. IMAGEPROCESSING: false,
  78832. VIGNETTE: false,
  78833. VIGNETTEBLENDMODEMULTIPLY: false,
  78834. VIGNETTEBLENDMODEOPAQUE: false,
  78835. TONEMAPPING: false,
  78836. CONTRAST: false,
  78837. COLORCURVES: false,
  78838. COLORGRADING: false,
  78839. COLORGRADING3D: false,
  78840. FROMLINEARSPACE: false,
  78841. SAMPLER3DGREENDEPTH: false,
  78842. SAMPLER3DBGRMAP: false,
  78843. IMAGEPROCESSINGPOSTPROCESS: false,
  78844. EXPOSURE: false,
  78845. };
  78846. // Setup the configuration as forced by the constructor. This would then not force the
  78847. // scene materials output in linear space and let untouched the default forward pass.
  78848. if (imageProcessingConfiguration) {
  78849. imageProcessingConfiguration.applyByPostProcess = true;
  78850. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78851. // This will cause the shader to be compiled
  78852. _this.fromLinearSpace = false;
  78853. }
  78854. // Setup the default processing configuration to the scene.
  78855. else {
  78856. _this._attachImageProcessingConfiguration(null, true);
  78857. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78858. }
  78859. _this.onApply = function (effect) {
  78860. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78861. };
  78862. return _this;
  78863. }
  78864. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78865. /**
  78866. * Gets the image processing configuration used either in this material.
  78867. */
  78868. get: function () {
  78869. return this._imageProcessingConfiguration;
  78870. },
  78871. /**
  78872. * Sets the Default image processing configuration used either in the this material.
  78873. *
  78874. * If sets to null, the scene one is in use.
  78875. */
  78876. set: function (value) {
  78877. this._attachImageProcessingConfiguration(value);
  78878. },
  78879. enumerable: true,
  78880. configurable: true
  78881. });
  78882. /**
  78883. * Attaches a new image processing configuration to the PBR Material.
  78884. * @param configuration
  78885. */
  78886. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78887. var _this = this;
  78888. if (doNotBuild === void 0) { doNotBuild = false; }
  78889. if (configuration === this._imageProcessingConfiguration) {
  78890. return;
  78891. }
  78892. // Detaches observer.
  78893. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78894. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78895. }
  78896. // Pick the scene configuration if needed.
  78897. if (!configuration) {
  78898. var scene = null;
  78899. var engine = this.getEngine();
  78900. var camera = this.getCamera();
  78901. if (camera) {
  78902. scene = camera.getScene();
  78903. }
  78904. else if (engine && engine.scenes) {
  78905. var scenes = engine.scenes;
  78906. scene = scenes[scenes.length - 1];
  78907. }
  78908. else {
  78909. scene = BABYLON.Engine.LastCreatedScene;
  78910. }
  78911. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78912. }
  78913. else {
  78914. this._imageProcessingConfiguration = configuration;
  78915. }
  78916. // Attaches observer.
  78917. if (this._imageProcessingConfiguration) {
  78918. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78919. _this._updateParameters();
  78920. });
  78921. }
  78922. // Ensure the effect will be rebuilt.
  78923. if (!doNotBuild) {
  78924. this._updateParameters();
  78925. }
  78926. };
  78927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78928. /**
  78929. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78930. */
  78931. get: function () {
  78932. return this.imageProcessingConfiguration.colorCurves;
  78933. },
  78934. /**
  78935. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78936. */
  78937. set: function (value) {
  78938. this.imageProcessingConfiguration.colorCurves = value;
  78939. },
  78940. enumerable: true,
  78941. configurable: true
  78942. });
  78943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78944. /**
  78945. * Gets wether the color curves effect is enabled.
  78946. */
  78947. get: function () {
  78948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78949. },
  78950. /**
  78951. * Sets wether the color curves effect is enabled.
  78952. */
  78953. set: function (value) {
  78954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78955. },
  78956. enumerable: true,
  78957. configurable: true
  78958. });
  78959. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78960. /**
  78961. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78962. */
  78963. get: function () {
  78964. return this.imageProcessingConfiguration.colorGradingTexture;
  78965. },
  78966. /**
  78967. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78968. */
  78969. set: function (value) {
  78970. this.imageProcessingConfiguration.colorGradingTexture = value;
  78971. },
  78972. enumerable: true,
  78973. configurable: true
  78974. });
  78975. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78976. /**
  78977. * Gets wether the color grading effect is enabled.
  78978. */
  78979. get: function () {
  78980. return this.imageProcessingConfiguration.colorGradingEnabled;
  78981. },
  78982. /**
  78983. * Gets wether the color grading effect is enabled.
  78984. */
  78985. set: function (value) {
  78986. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78987. },
  78988. enumerable: true,
  78989. configurable: true
  78990. });
  78991. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78992. /**
  78993. * Gets exposure used in the effect.
  78994. */
  78995. get: function () {
  78996. return this.imageProcessingConfiguration.exposure;
  78997. },
  78998. /**
  78999. * Sets exposure used in the effect.
  79000. */
  79001. set: function (value) {
  79002. this.imageProcessingConfiguration.exposure = value;
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79008. /**
  79009. * Gets wether tonemapping is enabled or not.
  79010. */
  79011. get: function () {
  79012. return this._imageProcessingConfiguration.toneMappingEnabled;
  79013. },
  79014. /**
  79015. * Sets wether tonemapping is enabled or not
  79016. */
  79017. set: function (value) {
  79018. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79019. },
  79020. enumerable: true,
  79021. configurable: true
  79022. });
  79023. ;
  79024. ;
  79025. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79026. /**
  79027. * Gets contrast used in the effect.
  79028. */
  79029. get: function () {
  79030. return this.imageProcessingConfiguration.contrast;
  79031. },
  79032. /**
  79033. * Sets contrast used in the effect.
  79034. */
  79035. set: function (value) {
  79036. this.imageProcessingConfiguration.contrast = value;
  79037. },
  79038. enumerable: true,
  79039. configurable: true
  79040. });
  79041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79042. /**
  79043. * Gets Vignette stretch size.
  79044. */
  79045. get: function () {
  79046. return this.imageProcessingConfiguration.vignetteStretch;
  79047. },
  79048. /**
  79049. * Sets Vignette stretch size.
  79050. */
  79051. set: function (value) {
  79052. this.imageProcessingConfiguration.vignetteStretch = value;
  79053. },
  79054. enumerable: true,
  79055. configurable: true
  79056. });
  79057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79058. /**
  79059. * Gets Vignette centre X Offset.
  79060. */
  79061. get: function () {
  79062. return this.imageProcessingConfiguration.vignetteCentreX;
  79063. },
  79064. /**
  79065. * Sets Vignette centre X Offset.
  79066. */
  79067. set: function (value) {
  79068. this.imageProcessingConfiguration.vignetteCentreX = value;
  79069. },
  79070. enumerable: true,
  79071. configurable: true
  79072. });
  79073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79074. /**
  79075. * Gets Vignette centre Y Offset.
  79076. */
  79077. get: function () {
  79078. return this.imageProcessingConfiguration.vignetteCentreY;
  79079. },
  79080. /**
  79081. * Sets Vignette centre Y Offset.
  79082. */
  79083. set: function (value) {
  79084. this.imageProcessingConfiguration.vignetteCentreY = value;
  79085. },
  79086. enumerable: true,
  79087. configurable: true
  79088. });
  79089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79090. /**
  79091. * Gets Vignette weight or intensity of the vignette effect.
  79092. */
  79093. get: function () {
  79094. return this.imageProcessingConfiguration.vignetteWeight;
  79095. },
  79096. /**
  79097. * Sets Vignette weight or intensity of the vignette effect.
  79098. */
  79099. set: function (value) {
  79100. this.imageProcessingConfiguration.vignetteWeight = value;
  79101. },
  79102. enumerable: true,
  79103. configurable: true
  79104. });
  79105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79106. /**
  79107. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79108. * if vignetteEnabled is set to true.
  79109. */
  79110. get: function () {
  79111. return this.imageProcessingConfiguration.vignetteColor;
  79112. },
  79113. /**
  79114. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79115. * if vignetteEnabled is set to true.
  79116. */
  79117. set: function (value) {
  79118. this.imageProcessingConfiguration.vignetteColor = value;
  79119. },
  79120. enumerable: true,
  79121. configurable: true
  79122. });
  79123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79124. /**
  79125. * Gets Camera field of view used by the Vignette effect.
  79126. */
  79127. get: function () {
  79128. return this.imageProcessingConfiguration.vignetteCameraFov;
  79129. },
  79130. /**
  79131. * Sets Camera field of view used by the Vignette effect.
  79132. */
  79133. set: function (value) {
  79134. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79135. },
  79136. enumerable: true,
  79137. configurable: true
  79138. });
  79139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79140. /**
  79141. * Gets the vignette blend mode allowing different kind of effect.
  79142. */
  79143. get: function () {
  79144. return this.imageProcessingConfiguration.vignetteBlendMode;
  79145. },
  79146. /**
  79147. * Sets the vignette blend mode allowing different kind of effect.
  79148. */
  79149. set: function (value) {
  79150. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79151. },
  79152. enumerable: true,
  79153. configurable: true
  79154. });
  79155. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79156. /**
  79157. * Gets wether the vignette effect is enabled.
  79158. */
  79159. get: function () {
  79160. return this.imageProcessingConfiguration.vignetteEnabled;
  79161. },
  79162. /**
  79163. * Sets wether the vignette effect is enabled.
  79164. */
  79165. set: function (value) {
  79166. this.imageProcessingConfiguration.vignetteEnabled = value;
  79167. },
  79168. enumerable: true,
  79169. configurable: true
  79170. });
  79171. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79172. /**
  79173. * Gets wether the input of the processing is in Gamma or Linear Space.
  79174. */
  79175. get: function () {
  79176. return this._fromLinearSpace;
  79177. },
  79178. /**
  79179. * Sets wether the input of the processing is in Gamma or Linear Space.
  79180. */
  79181. set: function (value) {
  79182. if (this._fromLinearSpace === value) {
  79183. return;
  79184. }
  79185. this._fromLinearSpace = value;
  79186. this._updateParameters();
  79187. },
  79188. enumerable: true,
  79189. configurable: true
  79190. });
  79191. ImageProcessingPostProcess.prototype.getClassName = function () {
  79192. return "ImageProcessingPostProcess";
  79193. };
  79194. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79195. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79196. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79197. var defines = "";
  79198. for (var define in this._defines) {
  79199. if (this._defines[define]) {
  79200. defines += "#define " + define + ";\r\n";
  79201. }
  79202. }
  79203. var samplers = ["textureSampler"];
  79204. var uniforms = ["scale"];
  79205. if (BABYLON.ImageProcessingConfiguration) {
  79206. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79207. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79208. }
  79209. this.updateEffect(defines, uniforms, samplers);
  79210. };
  79211. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79212. _super.prototype.dispose.call(this, camera);
  79213. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79214. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79215. }
  79216. if (this._imageProcessingConfiguration) {
  79217. this.imageProcessingConfiguration.applyByPostProcess = false;
  79218. }
  79219. };
  79220. __decorate([
  79221. BABYLON.serialize()
  79222. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79223. return ImageProcessingPostProcess;
  79224. }(BABYLON.PostProcess));
  79225. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79226. })(BABYLON || (BABYLON = {}));
  79227. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79228. var BABYLON;
  79229. (function (BABYLON) {
  79230. /**
  79231. * Class used to store bone information
  79232. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79233. */
  79234. var Bone = /** @class */ (function (_super) {
  79235. __extends(Bone, _super);
  79236. /**
  79237. * Create a new bone
  79238. * @param name defines the bone name
  79239. * @param skeleton defines the parent skeleton
  79240. * @param parentBone defines the parent (can be null if the bone is the root)
  79241. * @param localMatrix defines the local matrix
  79242. * @param restPose defines the rest pose matrix
  79243. * @param baseMatrix defines the base matrix
  79244. * @param index defines index of the bone in the hiearchy
  79245. */
  79246. function Bone(
  79247. /**
  79248. * defines the bone name
  79249. */
  79250. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79251. if (parentBone === void 0) { parentBone = null; }
  79252. if (localMatrix === void 0) { localMatrix = null; }
  79253. if (restPose === void 0) { restPose = null; }
  79254. if (baseMatrix === void 0) { baseMatrix = null; }
  79255. if (index === void 0) { index = null; }
  79256. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79257. _this.name = name;
  79258. /**
  79259. * Gets the list of child bones
  79260. */
  79261. _this.children = new Array();
  79262. /** Gets the animations associated with this bone */
  79263. _this.animations = new Array();
  79264. /**
  79265. * @hidden Internal only
  79266. * Set this value to map this bone to a different index in the transform matrices
  79267. * Set this value to -1 to exclude the bone from the transform matrices
  79268. */
  79269. _this._index = null;
  79270. _this._absoluteTransform = new BABYLON.Matrix();
  79271. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79272. _this._scalingDeterminant = 1;
  79273. _this._worldTransform = new BABYLON.Matrix();
  79274. _this._needToDecompose = true;
  79275. _this._needToCompose = false;
  79276. _this._skeleton = skeleton;
  79277. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79278. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79279. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79280. _this._index = index;
  79281. skeleton.bones.push(_this);
  79282. _this.setParent(parentBone, false);
  79283. if (baseMatrix || localMatrix) {
  79284. _this._updateDifferenceMatrix();
  79285. }
  79286. return _this;
  79287. }
  79288. Object.defineProperty(Bone.prototype, "_matrix", {
  79289. /** @hidden */
  79290. get: function () {
  79291. this._compose();
  79292. return this._localMatrix;
  79293. },
  79294. /** @hidden */
  79295. set: function (value) {
  79296. this._localMatrix.copyFrom(value);
  79297. this._needToDecompose = true;
  79298. },
  79299. enumerable: true,
  79300. configurable: true
  79301. });
  79302. // Members
  79303. /**
  79304. * Gets the parent skeleton
  79305. * @returns a skeleton
  79306. */
  79307. Bone.prototype.getSkeleton = function () {
  79308. return this._skeleton;
  79309. };
  79310. /**
  79311. * Gets parent bone
  79312. * @returns a bone or null if the bone is the root of the bone hierarchy
  79313. */
  79314. Bone.prototype.getParent = function () {
  79315. return this._parent;
  79316. };
  79317. /**
  79318. * Sets the parent bone
  79319. * @param parent defines the parent (can be null if the bone is the root)
  79320. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79321. */
  79322. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79323. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79324. if (this._parent === parent) {
  79325. return;
  79326. }
  79327. if (this._parent) {
  79328. var index = this._parent.children.indexOf(this);
  79329. if (index !== -1) {
  79330. this._parent.children.splice(index, 1);
  79331. }
  79332. }
  79333. this._parent = parent;
  79334. if (this._parent) {
  79335. this._parent.children.push(this);
  79336. }
  79337. if (updateDifferenceMatrix) {
  79338. this._updateDifferenceMatrix();
  79339. }
  79340. this.markAsDirty();
  79341. };
  79342. /**
  79343. * Gets the local matrix
  79344. * @returns a matrix
  79345. */
  79346. Bone.prototype.getLocalMatrix = function () {
  79347. this._compose();
  79348. return this._localMatrix;
  79349. };
  79350. /**
  79351. * Gets the base matrix (initial matrix which remains unchanged)
  79352. * @returns a matrix
  79353. */
  79354. Bone.prototype.getBaseMatrix = function () {
  79355. return this._baseMatrix;
  79356. };
  79357. /**
  79358. * Gets the rest pose matrix
  79359. * @returns a matrix
  79360. */
  79361. Bone.prototype.getRestPose = function () {
  79362. return this._restPose;
  79363. };
  79364. /**
  79365. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79366. */
  79367. Bone.prototype.getWorldMatrix = function () {
  79368. return this._worldTransform;
  79369. };
  79370. /**
  79371. * Sets the local matrix to rest pose matrix
  79372. */
  79373. Bone.prototype.returnToRest = function () {
  79374. this.updateMatrix(this._restPose.clone());
  79375. };
  79376. /**
  79377. * Gets the inverse of the absolute transform matrix.
  79378. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79379. * @returns a matrix
  79380. */
  79381. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79382. return this._invertedAbsoluteTransform;
  79383. };
  79384. /**
  79385. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79386. * @returns a matrix
  79387. */
  79388. Bone.prototype.getAbsoluteTransform = function () {
  79389. return this._absoluteTransform;
  79390. };
  79391. Object.defineProperty(Bone.prototype, "position", {
  79392. // Properties (matches AbstractMesh properties)
  79393. /** Gets or sets current position (in local space) */
  79394. get: function () {
  79395. this._decompose();
  79396. return this._localPosition;
  79397. },
  79398. set: function (newPosition) {
  79399. this._decompose();
  79400. this._localPosition.copyFrom(newPosition);
  79401. this._markAsDirtyAndCompose();
  79402. },
  79403. enumerable: true,
  79404. configurable: true
  79405. });
  79406. Object.defineProperty(Bone.prototype, "rotation", {
  79407. /** Gets or sets current rotation (in local space) */
  79408. get: function () {
  79409. return this.getRotation();
  79410. },
  79411. set: function (newRotation) {
  79412. this.setRotation(newRotation);
  79413. },
  79414. enumerable: true,
  79415. configurable: true
  79416. });
  79417. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79418. /** Gets or sets current rotation quaternion (in local space) */
  79419. get: function () {
  79420. this._decompose();
  79421. return this._localRotation;
  79422. },
  79423. set: function (newRotation) {
  79424. this.setRotationQuaternion(newRotation);
  79425. },
  79426. enumerable: true,
  79427. configurable: true
  79428. });
  79429. Object.defineProperty(Bone.prototype, "scaling", {
  79430. /** Gets or sets current scaling (in local space) */
  79431. get: function () {
  79432. return this.getScale();
  79433. },
  79434. set: function (newScaling) {
  79435. this.setScale(newScaling);
  79436. },
  79437. enumerable: true,
  79438. configurable: true
  79439. });
  79440. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79441. /**
  79442. * Gets the animation properties override
  79443. */
  79444. get: function () {
  79445. return this._skeleton.animationPropertiesOverride;
  79446. },
  79447. enumerable: true,
  79448. configurable: true
  79449. });
  79450. // Methods
  79451. Bone.prototype._decompose = function () {
  79452. if (!this._needToDecompose) {
  79453. return;
  79454. }
  79455. this._needToDecompose = false;
  79456. if (!this._localScaling) {
  79457. this._localScaling = BABYLON.Vector3.Zero();
  79458. this._localRotation = BABYLON.Quaternion.Zero();
  79459. this._localPosition = BABYLON.Vector3.Zero();
  79460. }
  79461. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79462. };
  79463. Bone.prototype._compose = function () {
  79464. if (!this._needToCompose) {
  79465. return;
  79466. }
  79467. this._needToCompose = false;
  79468. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79469. };
  79470. /**
  79471. * Update the base and local matrices
  79472. * @param matrix defines the new base or local matrix
  79473. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79474. * @param updateLocalMatrix defines if the local matrix should be updated
  79475. */
  79476. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79477. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79478. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79479. this._baseMatrix.copyFrom(matrix);
  79480. if (updateDifferenceMatrix) {
  79481. this._updateDifferenceMatrix();
  79482. }
  79483. if (updateLocalMatrix) {
  79484. this._localMatrix.copyFrom(matrix);
  79485. this._markAsDirtyAndDecompose();
  79486. }
  79487. else {
  79488. this.markAsDirty();
  79489. }
  79490. };
  79491. /** @hidden */
  79492. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79493. if (updateChildren === void 0) { updateChildren = true; }
  79494. if (!rootMatrix) {
  79495. rootMatrix = this._baseMatrix;
  79496. }
  79497. if (this._parent) {
  79498. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79499. }
  79500. else {
  79501. this._absoluteTransform.copyFrom(rootMatrix);
  79502. }
  79503. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79504. if (updateChildren) {
  79505. for (var index = 0; index < this.children.length; index++) {
  79506. this.children[index]._updateDifferenceMatrix();
  79507. }
  79508. }
  79509. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79510. };
  79511. /**
  79512. * Flag the bone as dirty (Forcing it to update everything)
  79513. */
  79514. Bone.prototype.markAsDirty = function () {
  79515. this._currentRenderId++;
  79516. this._childRenderId++;
  79517. this._skeleton._markAsDirty();
  79518. };
  79519. Bone.prototype._markAsDirtyAndCompose = function () {
  79520. this.markAsDirty();
  79521. this._needToCompose = true;
  79522. };
  79523. Bone.prototype._markAsDirtyAndDecompose = function () {
  79524. this.markAsDirty();
  79525. this._needToDecompose = true;
  79526. };
  79527. /**
  79528. * Copy an animation range from another bone
  79529. * @param source defines the source bone
  79530. * @param rangeName defines the range name to copy
  79531. * @param frameOffset defines the frame offset
  79532. * @param rescaleAsRequired defines if rescaling must be applied if required
  79533. * @param skelDimensionsRatio defines the scaling ratio
  79534. * @returns true if operation was successful
  79535. */
  79536. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79537. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79538. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79539. // all animation may be coming from a library skeleton, so may need to create animation
  79540. if (this.animations.length === 0) {
  79541. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79542. this.animations[0].setKeys([]);
  79543. }
  79544. // get animation info / verify there is such a range from the source bone
  79545. var sourceRange = source.animations[0].getRange(rangeName);
  79546. if (!sourceRange) {
  79547. return false;
  79548. }
  79549. var from = sourceRange.from;
  79550. var to = sourceRange.to;
  79551. var sourceKeys = source.animations[0].getKeys();
  79552. // rescaling prep
  79553. var sourceBoneLength = source.length;
  79554. var sourceParent = source.getParent();
  79555. var parent = this.getParent();
  79556. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79557. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79558. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79559. var destKeys = this.animations[0].getKeys();
  79560. // loop vars declaration
  79561. var orig;
  79562. var origTranslation;
  79563. var mat;
  79564. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79565. orig = sourceKeys[key];
  79566. if (orig.frame >= from && orig.frame <= to) {
  79567. if (rescaleAsRequired) {
  79568. mat = orig.value.clone();
  79569. // scale based on parent ratio, when bone has parent
  79570. if (parentScalingReqd) {
  79571. origTranslation = mat.getTranslation();
  79572. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79573. // scale based on skeleton dimension ratio when root bone, and value is passed
  79574. }
  79575. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79576. origTranslation = mat.getTranslation();
  79577. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79578. // use original when root bone, and no data for skelDimensionsRatio
  79579. }
  79580. else {
  79581. mat = orig.value;
  79582. }
  79583. }
  79584. else {
  79585. mat = orig.value;
  79586. }
  79587. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79588. }
  79589. }
  79590. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79591. return true;
  79592. };
  79593. /**
  79594. * Translate the bone in local or world space
  79595. * @param vec The amount to translate the bone
  79596. * @param space The space that the translation is in
  79597. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79598. */
  79599. Bone.prototype.translate = function (vec, space, mesh) {
  79600. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79601. var lm = this.getLocalMatrix();
  79602. if (space == BABYLON.Space.LOCAL) {
  79603. lm.m[12] += vec.x;
  79604. lm.m[13] += vec.y;
  79605. lm.m[14] += vec.z;
  79606. }
  79607. else {
  79608. var wm = null;
  79609. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79610. if (mesh) {
  79611. wm = mesh.getWorldMatrix();
  79612. }
  79613. this._skeleton.computeAbsoluteTransforms();
  79614. var tmat = Bone._tmpMats[0];
  79615. var tvec = Bone._tmpVecs[0];
  79616. if (this._parent) {
  79617. if (mesh && wm) {
  79618. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79619. tmat.multiplyToRef(wm, tmat);
  79620. }
  79621. else {
  79622. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79623. }
  79624. }
  79625. tmat.m[12] = 0;
  79626. tmat.m[13] = 0;
  79627. tmat.m[14] = 0;
  79628. tmat.invert();
  79629. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79630. lm.m[12] += tvec.x;
  79631. lm.m[13] += tvec.y;
  79632. lm.m[14] += tvec.z;
  79633. }
  79634. this._markAsDirtyAndDecompose();
  79635. };
  79636. /**
  79637. * Set the postion of the bone in local or world space
  79638. * @param position The position to set the bone
  79639. * @param space The space that the position is in
  79640. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79641. */
  79642. Bone.prototype.setPosition = function (position, space, mesh) {
  79643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79644. var lm = this.getLocalMatrix();
  79645. if (space == BABYLON.Space.LOCAL) {
  79646. lm.m[12] = position.x;
  79647. lm.m[13] = position.y;
  79648. lm.m[14] = position.z;
  79649. }
  79650. else {
  79651. var wm = null;
  79652. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79653. if (mesh) {
  79654. wm = mesh.getWorldMatrix();
  79655. }
  79656. this._skeleton.computeAbsoluteTransforms();
  79657. var tmat = Bone._tmpMats[0];
  79658. var vec = Bone._tmpVecs[0];
  79659. if (this._parent) {
  79660. if (mesh && wm) {
  79661. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79662. tmat.multiplyToRef(wm, tmat);
  79663. }
  79664. else {
  79665. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79666. }
  79667. }
  79668. tmat.invert();
  79669. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79670. lm.m[12] = vec.x;
  79671. lm.m[13] = vec.y;
  79672. lm.m[14] = vec.z;
  79673. }
  79674. this._markAsDirtyAndDecompose();
  79675. };
  79676. /**
  79677. * Set the absolute position of the bone (world space)
  79678. * @param position The position to set the bone
  79679. * @param mesh The mesh that this bone is attached to
  79680. */
  79681. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79682. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79683. };
  79684. /**
  79685. * Scale the bone on the x, y and z axes (in local space)
  79686. * @param x The amount to scale the bone on the x axis
  79687. * @param y The amount to scale the bone on the y axis
  79688. * @param z The amount to scale the bone on the z axis
  79689. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79690. */
  79691. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79692. if (scaleChildren === void 0) { scaleChildren = false; }
  79693. var locMat = this.getLocalMatrix();
  79694. // Apply new scaling on top of current local matrix
  79695. var scaleMat = Bone._tmpMats[0];
  79696. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79697. scaleMat.multiplyToRef(locMat, locMat);
  79698. // Invert scaling matrix and apply the inverse to all children
  79699. scaleMat.invert();
  79700. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79701. var child = _a[_i];
  79702. var cm = child.getLocalMatrix();
  79703. cm.multiplyToRef(scaleMat, cm);
  79704. cm.m[12] *= x;
  79705. cm.m[13] *= y;
  79706. cm.m[14] *= z;
  79707. child._markAsDirtyAndDecompose();
  79708. }
  79709. this._markAsDirtyAndDecompose();
  79710. if (scaleChildren) {
  79711. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79712. var child = _c[_b];
  79713. child.scale(x, y, z, scaleChildren);
  79714. }
  79715. }
  79716. };
  79717. /**
  79718. * Set the bone scaling in local space
  79719. * @param scale defines the scaling vector
  79720. */
  79721. Bone.prototype.setScale = function (scale) {
  79722. this._decompose();
  79723. this._localScaling.copyFrom(scale);
  79724. this._markAsDirtyAndCompose();
  79725. };
  79726. /**
  79727. * Gets the current scaling in local space
  79728. * @returns the current scaling vector
  79729. */
  79730. Bone.prototype.getScale = function () {
  79731. this._decompose();
  79732. return this._localScaling;
  79733. };
  79734. /**
  79735. * Gets the current scaling in local space and stores it in a target vector
  79736. * @param result defines the target vector
  79737. */
  79738. Bone.prototype.getScaleToRef = function (result) {
  79739. this._decompose();
  79740. result.copyFrom(this._localScaling);
  79741. };
  79742. /**
  79743. * Set the yaw, pitch, and roll of the bone in local or world space
  79744. * @param yaw The rotation of the bone on the y axis
  79745. * @param pitch The rotation of the bone on the x axis
  79746. * @param roll The rotation of the bone on the z axis
  79747. * @param space The space that the axes of rotation are in
  79748. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79749. */
  79750. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79752. if (space === BABYLON.Space.LOCAL) {
  79753. var quat = Bone._tmpQuat;
  79754. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79755. this.setRotationQuaternion(quat, space, mesh);
  79756. return;
  79757. }
  79758. var rotMatInv = Bone._tmpMats[0];
  79759. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79760. return;
  79761. }
  79762. var rotMat = Bone._tmpMats[1];
  79763. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79764. rotMatInv.multiplyToRef(rotMat, rotMat);
  79765. this._rotateWithMatrix(rotMat, space, mesh);
  79766. };
  79767. /**
  79768. * Add a rotation to the bone on an axis in local or world space
  79769. * @param axis The axis to rotate the bone on
  79770. * @param amount The amount to rotate the bone
  79771. * @param space The space that the axis is in
  79772. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79773. */
  79774. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79776. var rmat = Bone._tmpMats[0];
  79777. rmat.m[12] = 0;
  79778. rmat.m[13] = 0;
  79779. rmat.m[14] = 0;
  79780. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79781. this._rotateWithMatrix(rmat, space, mesh);
  79782. };
  79783. /**
  79784. * Set the rotation of the bone to a particular axis angle in local or world space
  79785. * @param axis The axis to rotate the bone on
  79786. * @param angle The angle that the bone should be rotated to
  79787. * @param space The space that the axis is in
  79788. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79789. */
  79790. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79791. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79792. if (space === BABYLON.Space.LOCAL) {
  79793. var quat = Bone._tmpQuat;
  79794. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79795. this.setRotationQuaternion(quat, space, mesh);
  79796. return;
  79797. }
  79798. var rotMatInv = Bone._tmpMats[0];
  79799. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79800. return;
  79801. }
  79802. var rotMat = Bone._tmpMats[1];
  79803. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79804. rotMatInv.multiplyToRef(rotMat, rotMat);
  79805. this._rotateWithMatrix(rotMat, space, mesh);
  79806. };
  79807. /**
  79808. * Set the euler rotation of the bone in local of world space
  79809. * @param rotation The euler rotation that the bone should be set to
  79810. * @param space The space that the rotation is in
  79811. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79812. */
  79813. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79815. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79816. };
  79817. /**
  79818. * Set the quaternion rotation of the bone in local of world space
  79819. * @param quat The quaternion rotation that the bone should be set to
  79820. * @param space The space that the rotation is in
  79821. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79822. */
  79823. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79824. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79825. if (space === BABYLON.Space.LOCAL) {
  79826. this._decompose();
  79827. this._localRotation.copyFrom(quat);
  79828. this._markAsDirtyAndCompose();
  79829. return;
  79830. }
  79831. var rotMatInv = Bone._tmpMats[0];
  79832. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79833. return;
  79834. }
  79835. var rotMat = Bone._tmpMats[1];
  79836. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79837. rotMatInv.multiplyToRef(rotMat, rotMat);
  79838. this._rotateWithMatrix(rotMat, space, mesh);
  79839. };
  79840. /**
  79841. * Set the rotation matrix of the bone in local of world space
  79842. * @param rotMat The rotation matrix that the bone should be set to
  79843. * @param space The space that the rotation is in
  79844. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79845. */
  79846. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79847. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79848. if (space === BABYLON.Space.LOCAL) {
  79849. var quat = Bone._tmpQuat;
  79850. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79851. this.setRotationQuaternion(quat, space, mesh);
  79852. return;
  79853. }
  79854. var rotMatInv = Bone._tmpMats[0];
  79855. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79856. return;
  79857. }
  79858. var rotMat2 = Bone._tmpMats[1];
  79859. rotMat2.copyFrom(rotMat);
  79860. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79861. this._rotateWithMatrix(rotMat2, space, mesh);
  79862. };
  79863. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79864. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79865. var lmat = this.getLocalMatrix();
  79866. var lx = lmat.m[12];
  79867. var ly = lmat.m[13];
  79868. var lz = lmat.m[14];
  79869. var parent = this.getParent();
  79870. var parentScale = Bone._tmpMats[3];
  79871. var parentScaleInv = Bone._tmpMats[4];
  79872. if (parent && space == BABYLON.Space.WORLD) {
  79873. if (mesh) {
  79874. parentScale.copyFrom(mesh.getWorldMatrix());
  79875. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79876. }
  79877. else {
  79878. parentScale.copyFrom(parent.getAbsoluteTransform());
  79879. }
  79880. parentScaleInv.copyFrom(parentScale);
  79881. parentScaleInv.invert();
  79882. lmat.multiplyToRef(parentScale, lmat);
  79883. lmat.multiplyToRef(rmat, lmat);
  79884. lmat.multiplyToRef(parentScaleInv, lmat);
  79885. }
  79886. else {
  79887. if (space == BABYLON.Space.WORLD && mesh) {
  79888. parentScale.copyFrom(mesh.getWorldMatrix());
  79889. parentScaleInv.copyFrom(parentScale);
  79890. parentScaleInv.invert();
  79891. lmat.multiplyToRef(parentScale, lmat);
  79892. lmat.multiplyToRef(rmat, lmat);
  79893. lmat.multiplyToRef(parentScaleInv, lmat);
  79894. }
  79895. else {
  79896. lmat.multiplyToRef(rmat, lmat);
  79897. }
  79898. }
  79899. lmat.m[12] = lx;
  79900. lmat.m[13] = ly;
  79901. lmat.m[14] = lz;
  79902. this.computeAbsoluteTransforms();
  79903. this._markAsDirtyAndDecompose();
  79904. };
  79905. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79906. var scaleMatrix = Bone._tmpMats[2];
  79907. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79908. if (mesh) {
  79909. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79910. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79911. }
  79912. rotMatInv.invert();
  79913. if (isNaN(rotMatInv.m[0])) {
  79914. // Matrix failed to invert.
  79915. // This can happen if scale is zero for example.
  79916. return false;
  79917. }
  79918. scaleMatrix.m[0] *= this._scalingDeterminant;
  79919. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79920. return true;
  79921. };
  79922. /**
  79923. * Get the position of the bone in local or world space
  79924. * @param space The space that the returned position is in
  79925. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79926. * @returns The position of the bone
  79927. */
  79928. Bone.prototype.getPosition = function (space, mesh) {
  79929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79930. if (mesh === void 0) { mesh = null; }
  79931. var pos = BABYLON.Vector3.Zero();
  79932. this.getPositionToRef(space, mesh, pos);
  79933. return pos;
  79934. };
  79935. /**
  79936. * Copy the position of the bone to a vector3 in local or world space
  79937. * @param space The space that the returned position is in
  79938. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79939. * @param result The vector3 to copy the position to
  79940. */
  79941. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79942. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79943. if (space == BABYLON.Space.LOCAL) {
  79944. var lm = this.getLocalMatrix();
  79945. result.x = lm.m[12];
  79946. result.y = lm.m[13];
  79947. result.z = lm.m[14];
  79948. }
  79949. else {
  79950. var wm = null;
  79951. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79952. if (mesh) {
  79953. wm = mesh.getWorldMatrix();
  79954. }
  79955. this._skeleton.computeAbsoluteTransforms();
  79956. var tmat = Bone._tmpMats[0];
  79957. if (mesh && wm) {
  79958. tmat.copyFrom(this.getAbsoluteTransform());
  79959. tmat.multiplyToRef(wm, tmat);
  79960. }
  79961. else {
  79962. tmat = this.getAbsoluteTransform();
  79963. }
  79964. result.x = tmat.m[12];
  79965. result.y = tmat.m[13];
  79966. result.z = tmat.m[14];
  79967. }
  79968. };
  79969. /**
  79970. * Get the absolute position of the bone (world space)
  79971. * @param mesh The mesh that this bone is attached to
  79972. * @returns The absolute position of the bone
  79973. */
  79974. Bone.prototype.getAbsolutePosition = function (mesh) {
  79975. if (mesh === void 0) { mesh = null; }
  79976. var pos = BABYLON.Vector3.Zero();
  79977. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79978. return pos;
  79979. };
  79980. /**
  79981. * Copy the absolute position of the bone (world space) to the result param
  79982. * @param mesh The mesh that this bone is attached to
  79983. * @param result The vector3 to copy the absolute position to
  79984. */
  79985. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79986. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79987. };
  79988. /**
  79989. * Compute the absolute transforms of this bone and its children
  79990. */
  79991. Bone.prototype.computeAbsoluteTransforms = function () {
  79992. this._compose();
  79993. if (this._parent) {
  79994. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79995. }
  79996. else {
  79997. this._absoluteTransform.copyFrom(this._localMatrix);
  79998. var poseMatrix = this._skeleton.getPoseMatrix();
  79999. if (poseMatrix) {
  80000. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80001. }
  80002. }
  80003. var children = this.children;
  80004. var len = children.length;
  80005. for (var i = 0; i < len; i++) {
  80006. children[i].computeAbsoluteTransforms();
  80007. }
  80008. };
  80009. /**
  80010. * Get the world direction from an axis that is in the local space of the bone
  80011. * @param localAxis The local direction that is used to compute the world direction
  80012. * @param mesh The mesh that this bone is attached to
  80013. * @returns The world direction
  80014. */
  80015. Bone.prototype.getDirection = function (localAxis, mesh) {
  80016. if (mesh === void 0) { mesh = null; }
  80017. var result = BABYLON.Vector3.Zero();
  80018. this.getDirectionToRef(localAxis, mesh, result);
  80019. return result;
  80020. };
  80021. /**
  80022. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80023. * @param localAxis The local direction that is used to compute the world direction
  80024. * @param mesh The mesh that this bone is attached to
  80025. * @param result The vector3 that the world direction will be copied to
  80026. */
  80027. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80028. if (mesh === void 0) { mesh = null; }
  80029. var wm = null;
  80030. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80031. if (mesh) {
  80032. wm = mesh.getWorldMatrix();
  80033. }
  80034. this._skeleton.computeAbsoluteTransforms();
  80035. var mat = Bone._tmpMats[0];
  80036. mat.copyFrom(this.getAbsoluteTransform());
  80037. if (mesh && wm) {
  80038. mat.multiplyToRef(wm, mat);
  80039. }
  80040. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80041. result.normalize();
  80042. };
  80043. /**
  80044. * Get the euler rotation of the bone in local or world space
  80045. * @param space The space that the rotation should be in
  80046. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80047. * @returns The euler rotation
  80048. */
  80049. Bone.prototype.getRotation = function (space, mesh) {
  80050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80051. if (mesh === void 0) { mesh = null; }
  80052. var result = BABYLON.Vector3.Zero();
  80053. this.getRotationToRef(space, mesh, result);
  80054. return result;
  80055. };
  80056. /**
  80057. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80058. * @param space The space that the rotation should be in
  80059. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80060. * @param result The vector3 that the rotation should be copied to
  80061. */
  80062. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80063. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80064. if (mesh === void 0) { mesh = null; }
  80065. var quat = Bone._tmpQuat;
  80066. this.getRotationQuaternionToRef(space, mesh, quat);
  80067. quat.toEulerAnglesToRef(result);
  80068. };
  80069. /**
  80070. * Get the quaternion rotation of the bone in either local or world space
  80071. * @param space The space that the rotation should be in
  80072. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80073. * @returns The quaternion rotation
  80074. */
  80075. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80076. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80077. if (mesh === void 0) { mesh = null; }
  80078. var result = BABYLON.Quaternion.Identity();
  80079. this.getRotationQuaternionToRef(space, mesh, result);
  80080. return result;
  80081. };
  80082. /**
  80083. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80084. * @param space The space that the rotation should be in
  80085. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80086. * @param result The quaternion that the rotation should be copied to
  80087. */
  80088. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80090. if (mesh === void 0) { mesh = null; }
  80091. if (space == BABYLON.Space.LOCAL) {
  80092. this._decompose();
  80093. result.copyFrom(this._localRotation);
  80094. }
  80095. else {
  80096. var mat = Bone._tmpMats[0];
  80097. var amat = this.getAbsoluteTransform();
  80098. if (mesh) {
  80099. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80100. }
  80101. else {
  80102. mat.copyFrom(amat);
  80103. }
  80104. mat.m[0] *= this._scalingDeterminant;
  80105. mat.m[1] *= this._scalingDeterminant;
  80106. mat.m[2] *= this._scalingDeterminant;
  80107. mat.decompose(undefined, result, undefined);
  80108. }
  80109. };
  80110. /**
  80111. * Get the rotation matrix of the bone in local or world space
  80112. * @param space The space that the rotation should be in
  80113. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80114. * @returns The rotation matrix
  80115. */
  80116. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80118. var result = BABYLON.Matrix.Identity();
  80119. this.getRotationMatrixToRef(space, mesh, result);
  80120. return result;
  80121. };
  80122. /**
  80123. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80124. * @param space The space that the rotation should be in
  80125. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80126. * @param result The quaternion that the rotation should be copied to
  80127. */
  80128. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80129. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80130. if (space == BABYLON.Space.LOCAL) {
  80131. this.getLocalMatrix().getRotationMatrixToRef(result);
  80132. }
  80133. else {
  80134. var mat = Bone._tmpMats[0];
  80135. var amat = this.getAbsoluteTransform();
  80136. if (mesh) {
  80137. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80138. }
  80139. else {
  80140. mat.copyFrom(amat);
  80141. }
  80142. mat.m[0] *= this._scalingDeterminant;
  80143. mat.m[1] *= this._scalingDeterminant;
  80144. mat.m[2] *= this._scalingDeterminant;
  80145. mat.getRotationMatrixToRef(result);
  80146. }
  80147. };
  80148. /**
  80149. * Get the world position of a point that is in the local space of the bone
  80150. * @param position The local position
  80151. * @param mesh The mesh that this bone is attached to
  80152. * @returns The world position
  80153. */
  80154. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80155. if (mesh === void 0) { mesh = null; }
  80156. var result = BABYLON.Vector3.Zero();
  80157. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80158. return result;
  80159. };
  80160. /**
  80161. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80162. * @param position The local position
  80163. * @param mesh The mesh that this bone is attached to
  80164. * @param result The vector3 that the world position should be copied to
  80165. */
  80166. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80167. if (mesh === void 0) { mesh = null; }
  80168. var wm = null;
  80169. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80170. if (mesh) {
  80171. wm = mesh.getWorldMatrix();
  80172. }
  80173. this._skeleton.computeAbsoluteTransforms();
  80174. var tmat = Bone._tmpMats[0];
  80175. if (mesh && wm) {
  80176. tmat.copyFrom(this.getAbsoluteTransform());
  80177. tmat.multiplyToRef(wm, tmat);
  80178. }
  80179. else {
  80180. tmat = this.getAbsoluteTransform();
  80181. }
  80182. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80183. };
  80184. /**
  80185. * Get the local position of a point that is in world space
  80186. * @param position The world position
  80187. * @param mesh The mesh that this bone is attached to
  80188. * @returns The local position
  80189. */
  80190. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80191. if (mesh === void 0) { mesh = null; }
  80192. var result = BABYLON.Vector3.Zero();
  80193. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80194. return result;
  80195. };
  80196. /**
  80197. * Get the local position of a point that is in world space and copy it to the result param
  80198. * @param position The world position
  80199. * @param mesh The mesh that this bone is attached to
  80200. * @param result The vector3 that the local position should be copied to
  80201. */
  80202. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80203. if (mesh === void 0) { mesh = null; }
  80204. var wm = null;
  80205. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80206. if (mesh) {
  80207. wm = mesh.getWorldMatrix();
  80208. }
  80209. this._skeleton.computeAbsoluteTransforms();
  80210. var tmat = Bone._tmpMats[0];
  80211. tmat.copyFrom(this.getAbsoluteTransform());
  80212. if (mesh && wm) {
  80213. tmat.multiplyToRef(wm, tmat);
  80214. }
  80215. tmat.invert();
  80216. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80217. };
  80218. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80219. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80220. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80221. return Bone;
  80222. }(BABYLON.Node));
  80223. BABYLON.Bone = Bone;
  80224. })(BABYLON || (BABYLON = {}));
  80225. //# sourceMappingURL=babylon.bone.js.map
  80226. var BABYLON;
  80227. (function (BABYLON) {
  80228. /**
  80229. * Class used to apply inverse kinematics to bones
  80230. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80231. */
  80232. var BoneIKController = /** @class */ (function () {
  80233. /**
  80234. * Creates a new BoneIKController
  80235. * @param mesh defines the mesh to control
  80236. * @param bone defines the bone to control
  80237. * @param options defines options to set up the controller
  80238. */
  80239. function BoneIKController(mesh, bone, options) {
  80240. /**
  80241. * Gets or sets the target position
  80242. */
  80243. this.targetPosition = BABYLON.Vector3.Zero();
  80244. /**
  80245. * Gets or sets the pole target position
  80246. */
  80247. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80248. /**
  80249. * Gets or sets the pole target local offset
  80250. */
  80251. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80252. /**
  80253. * Gets or sets the pole angle
  80254. */
  80255. this.poleAngle = 0;
  80256. /**
  80257. * 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)
  80258. */
  80259. this.slerpAmount = 1;
  80260. this._bone1Quat = BABYLON.Quaternion.Identity();
  80261. this._bone1Mat = BABYLON.Matrix.Identity();
  80262. this._bone2Ang = Math.PI;
  80263. this._maxAngle = Math.PI;
  80264. this._rightHandedSystem = false;
  80265. this._bendAxis = BABYLON.Vector3.Right();
  80266. this._slerping = false;
  80267. this._adjustRoll = 0;
  80268. this._bone2 = bone;
  80269. this._bone1 = bone.getParent();
  80270. if (!this._bone1) {
  80271. return;
  80272. }
  80273. this.mesh = mesh;
  80274. var bonePos = bone.getPosition();
  80275. if (bone.getAbsoluteTransform().determinant() > 0) {
  80276. this._rightHandedSystem = true;
  80277. this._bendAxis.x = 0;
  80278. this._bendAxis.y = 0;
  80279. this._bendAxis.z = -1;
  80280. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80281. this._adjustRoll = Math.PI * .5;
  80282. this._bendAxis.z = 1;
  80283. }
  80284. }
  80285. if (this._bone1.length) {
  80286. var boneScale1 = this._bone1.getScale();
  80287. var boneScale2 = this._bone2.getScale();
  80288. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80289. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80290. }
  80291. else if (this._bone1.children[0]) {
  80292. mesh.computeWorldMatrix(true);
  80293. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80294. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80295. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80296. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80297. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80298. }
  80299. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80300. this.maxAngle = Math.PI;
  80301. if (options) {
  80302. if (options.targetMesh) {
  80303. this.targetMesh = options.targetMesh;
  80304. this.targetMesh.computeWorldMatrix(true);
  80305. }
  80306. if (options.poleTargetMesh) {
  80307. this.poleTargetMesh = options.poleTargetMesh;
  80308. this.poleTargetMesh.computeWorldMatrix(true);
  80309. }
  80310. else if (options.poleTargetBone) {
  80311. this.poleTargetBone = options.poleTargetBone;
  80312. }
  80313. else if (this._bone1.getParent()) {
  80314. this.poleTargetBone = this._bone1.getParent();
  80315. }
  80316. if (options.poleTargetLocalOffset) {
  80317. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80318. }
  80319. if (options.poleAngle) {
  80320. this.poleAngle = options.poleAngle;
  80321. }
  80322. if (options.bendAxis) {
  80323. this._bendAxis.copyFrom(options.bendAxis);
  80324. }
  80325. if (options.maxAngle) {
  80326. this.maxAngle = options.maxAngle;
  80327. }
  80328. if (options.slerpAmount) {
  80329. this.slerpAmount = options.slerpAmount;
  80330. }
  80331. }
  80332. }
  80333. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80334. /**
  80335. * Gets or sets maximum allowed angle
  80336. */
  80337. get: function () {
  80338. return this._maxAngle;
  80339. },
  80340. set: function (value) {
  80341. this._setMaxAngle(value);
  80342. },
  80343. enumerable: true,
  80344. configurable: true
  80345. });
  80346. BoneIKController.prototype._setMaxAngle = function (ang) {
  80347. if (ang < 0) {
  80348. ang = 0;
  80349. }
  80350. if (ang > Math.PI || ang == undefined) {
  80351. ang = Math.PI;
  80352. }
  80353. this._maxAngle = ang;
  80354. var a = this._bone1Length;
  80355. var b = this._bone2Length;
  80356. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80357. };
  80358. /**
  80359. * Force the controller to update the bones
  80360. */
  80361. BoneIKController.prototype.update = function () {
  80362. var bone1 = this._bone1;
  80363. if (!bone1) {
  80364. return;
  80365. }
  80366. var target = this.targetPosition;
  80367. var poleTarget = this.poleTargetPosition;
  80368. var mat1 = BoneIKController._tmpMats[0];
  80369. var mat2 = BoneIKController._tmpMats[1];
  80370. if (this.targetMesh) {
  80371. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80372. }
  80373. if (this.poleTargetBone) {
  80374. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80375. }
  80376. else if (this.poleTargetMesh) {
  80377. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80378. }
  80379. var bonePos = BoneIKController._tmpVecs[0];
  80380. var zaxis = BoneIKController._tmpVecs[1];
  80381. var xaxis = BoneIKController._tmpVecs[2];
  80382. var yaxis = BoneIKController._tmpVecs[3];
  80383. var upAxis = BoneIKController._tmpVecs[4];
  80384. var _tmpQuat = BoneIKController._tmpQuat;
  80385. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80386. poleTarget.subtractToRef(bonePos, upAxis);
  80387. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80388. upAxis.y = 1;
  80389. }
  80390. else {
  80391. upAxis.normalize();
  80392. }
  80393. target.subtractToRef(bonePos, yaxis);
  80394. yaxis.normalize();
  80395. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80396. zaxis.normalize();
  80397. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80398. xaxis.normalize();
  80399. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80400. var a = this._bone1Length;
  80401. var b = this._bone2Length;
  80402. var c = BABYLON.Vector3.Distance(bonePos, target);
  80403. if (this._maxReach > 0) {
  80404. c = Math.min(this._maxReach, c);
  80405. }
  80406. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80407. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80408. if (acosa > 1) {
  80409. acosa = 1;
  80410. }
  80411. if (acosb > 1) {
  80412. acosb = 1;
  80413. }
  80414. if (acosa < -1) {
  80415. acosa = -1;
  80416. }
  80417. if (acosb < -1) {
  80418. acosb = -1;
  80419. }
  80420. var angA = Math.acos(acosa);
  80421. var angB = Math.acos(acosb);
  80422. var angC = -angA - angB;
  80423. if (this._rightHandedSystem) {
  80424. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80425. mat2.multiplyToRef(mat1, mat1);
  80426. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80427. mat2.multiplyToRef(mat1, mat1);
  80428. }
  80429. else {
  80430. var _tmpVec = BoneIKController._tmpVecs[5];
  80431. _tmpVec.copyFrom(this._bendAxis);
  80432. _tmpVec.x *= -1;
  80433. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80434. mat2.multiplyToRef(mat1, mat1);
  80435. }
  80436. if (this.poleAngle) {
  80437. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80438. mat1.multiplyToRef(mat2, mat1);
  80439. }
  80440. if (this._bone1) {
  80441. if (this.slerpAmount < 1) {
  80442. if (!this._slerping) {
  80443. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80444. }
  80445. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80446. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80447. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80448. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80449. this._slerping = true;
  80450. }
  80451. else {
  80452. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80453. this._bone1Mat.copyFrom(mat1);
  80454. this._slerping = false;
  80455. }
  80456. }
  80457. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80458. this._bone2Ang = angC;
  80459. };
  80460. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80461. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80462. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80463. return BoneIKController;
  80464. }());
  80465. BABYLON.BoneIKController = BoneIKController;
  80466. })(BABYLON || (BABYLON = {}));
  80467. //# sourceMappingURL=babylon.boneIKController.js.map
  80468. var BABYLON;
  80469. (function (BABYLON) {
  80470. /**
  80471. * Class used to make a bone look toward a point in space
  80472. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80473. */
  80474. var BoneLookController = /** @class */ (function () {
  80475. /**
  80476. * Create a BoneLookController
  80477. * @param mesh the mesh that the bone belongs to
  80478. * @param bone the bone that will be looking to the target
  80479. * @param target the target Vector3 to look at
  80480. * @param settings optional settings:
  80481. * * maxYaw: the maximum angle the bone will yaw to
  80482. * * minYaw: the minimum angle the bone will yaw to
  80483. * * maxPitch: the maximum angle the bone will pitch to
  80484. * * minPitch: the minimum angle the bone will yaw to
  80485. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80486. * * upAxis: the up axis of the coordinate system
  80487. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80488. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80489. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80490. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80491. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80492. * * adjustRoll: used to make an adjustment to the roll of the bone
  80493. **/
  80494. function BoneLookController(mesh, bone, target, options) {
  80495. /**
  80496. * The up axis of the coordinate system that is used when the bone is rotated
  80497. */
  80498. this.upAxis = BABYLON.Vector3.Up();
  80499. /**
  80500. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80501. */
  80502. this.upAxisSpace = BABYLON.Space.LOCAL;
  80503. /**
  80504. * Used to make an adjustment to the yaw of the bone
  80505. */
  80506. this.adjustYaw = 0;
  80507. /**
  80508. * Used to make an adjustment to the pitch of the bone
  80509. */
  80510. this.adjustPitch = 0;
  80511. /**
  80512. * Used to make an adjustment to the roll of the bone
  80513. */
  80514. this.adjustRoll = 0;
  80515. /**
  80516. * 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)
  80517. */
  80518. this.slerpAmount = 1;
  80519. this._boneQuat = BABYLON.Quaternion.Identity();
  80520. this._slerping = false;
  80521. this._firstFrameSkipped = false;
  80522. this._fowardAxis = BABYLON.Vector3.Forward();
  80523. this.mesh = mesh;
  80524. this.bone = bone;
  80525. this.target = target;
  80526. if (options) {
  80527. if (options.adjustYaw) {
  80528. this.adjustYaw = options.adjustYaw;
  80529. }
  80530. if (options.adjustPitch) {
  80531. this.adjustPitch = options.adjustPitch;
  80532. }
  80533. if (options.adjustRoll) {
  80534. this.adjustRoll = options.adjustRoll;
  80535. }
  80536. if (options.maxYaw != null) {
  80537. this.maxYaw = options.maxYaw;
  80538. }
  80539. else {
  80540. this.maxYaw = Math.PI;
  80541. }
  80542. if (options.minYaw != null) {
  80543. this.minYaw = options.minYaw;
  80544. }
  80545. else {
  80546. this.minYaw = -Math.PI;
  80547. }
  80548. if (options.maxPitch != null) {
  80549. this.maxPitch = options.maxPitch;
  80550. }
  80551. else {
  80552. this.maxPitch = Math.PI;
  80553. }
  80554. if (options.minPitch != null) {
  80555. this.minPitch = options.minPitch;
  80556. }
  80557. else {
  80558. this.minPitch = -Math.PI;
  80559. }
  80560. if (options.slerpAmount != null) {
  80561. this.slerpAmount = options.slerpAmount;
  80562. }
  80563. if (options.upAxis != null) {
  80564. this.upAxis = options.upAxis;
  80565. }
  80566. if (options.upAxisSpace != null) {
  80567. this.upAxisSpace = options.upAxisSpace;
  80568. }
  80569. if (options.yawAxis != null || options.pitchAxis != null) {
  80570. var newYawAxis = BABYLON.Axis.Y;
  80571. var newPitchAxis = BABYLON.Axis.X;
  80572. if (options.yawAxis != null) {
  80573. newYawAxis = options.yawAxis.clone();
  80574. newYawAxis.normalize();
  80575. }
  80576. if (options.pitchAxis != null) {
  80577. newPitchAxis = options.pitchAxis.clone();
  80578. newPitchAxis.normalize();
  80579. }
  80580. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80581. this._transformYawPitch = BABYLON.Matrix.Identity();
  80582. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80583. this._transformYawPitchInv = this._transformYawPitch.clone();
  80584. this._transformYawPitch.invert();
  80585. }
  80586. }
  80587. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80588. this.upAxisSpace = BABYLON.Space.LOCAL;
  80589. }
  80590. }
  80591. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80592. /**
  80593. * Gets or sets the minimum yaw angle that the bone can look to
  80594. */
  80595. get: function () {
  80596. return this._minYaw;
  80597. },
  80598. set: function (value) {
  80599. this._minYaw = value;
  80600. this._minYawSin = Math.sin(value);
  80601. this._minYawCos = Math.cos(value);
  80602. if (this._maxYaw != null) {
  80603. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80604. this._yawRange = this._maxYaw - this._minYaw;
  80605. }
  80606. },
  80607. enumerable: true,
  80608. configurable: true
  80609. });
  80610. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80611. /**
  80612. * Gets or sets the maximum yaw angle that the bone can look to
  80613. */
  80614. get: function () {
  80615. return this._maxYaw;
  80616. },
  80617. set: function (value) {
  80618. this._maxYaw = value;
  80619. this._maxYawSin = Math.sin(value);
  80620. this._maxYawCos = Math.cos(value);
  80621. if (this._minYaw != null) {
  80622. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80623. this._yawRange = this._maxYaw - this._minYaw;
  80624. }
  80625. },
  80626. enumerable: true,
  80627. configurable: true
  80628. });
  80629. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80630. /**
  80631. * Gets or sets the minimum pitch angle that the bone can look to
  80632. */
  80633. get: function () {
  80634. return this._minPitch;
  80635. },
  80636. set: function (value) {
  80637. this._minPitch = value;
  80638. this._minPitchTan = Math.tan(value);
  80639. },
  80640. enumerable: true,
  80641. configurable: true
  80642. });
  80643. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80644. /**
  80645. * Gets or sets the maximum pitch angle that the bone can look to
  80646. */
  80647. get: function () {
  80648. return this._maxPitch;
  80649. },
  80650. set: function (value) {
  80651. this._maxPitch = value;
  80652. this._maxPitchTan = Math.tan(value);
  80653. },
  80654. enumerable: true,
  80655. configurable: true
  80656. });
  80657. /**
  80658. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80659. */
  80660. BoneLookController.prototype.update = function () {
  80661. //skip the first frame when slerping so that the mesh rotation is correct
  80662. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80663. this._firstFrameSkipped = true;
  80664. return;
  80665. }
  80666. var bone = this.bone;
  80667. var bonePos = BoneLookController._tmpVecs[0];
  80668. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80669. var target = this.target;
  80670. var _tmpMat1 = BoneLookController._tmpMats[0];
  80671. var _tmpMat2 = BoneLookController._tmpMats[1];
  80672. var mesh = this.mesh;
  80673. var parentBone = bone.getParent();
  80674. var upAxis = BoneLookController._tmpVecs[1];
  80675. upAxis.copyFrom(this.upAxis);
  80676. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80677. if (this._transformYawPitch) {
  80678. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80679. }
  80680. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80681. }
  80682. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80683. mesh.getDirectionToRef(upAxis, upAxis);
  80684. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80685. upAxis.normalize();
  80686. }
  80687. }
  80688. var checkYaw = false;
  80689. var checkPitch = false;
  80690. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80691. checkYaw = true;
  80692. }
  80693. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80694. checkPitch = true;
  80695. }
  80696. if (checkYaw || checkPitch) {
  80697. var spaceMat = BoneLookController._tmpMats[2];
  80698. var spaceMatInv = BoneLookController._tmpMats[3];
  80699. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80700. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80701. }
  80702. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80703. spaceMat.copyFrom(mesh.getWorldMatrix());
  80704. }
  80705. else {
  80706. var forwardAxis = BoneLookController._tmpVecs[2];
  80707. forwardAxis.copyFrom(this._fowardAxis);
  80708. if (this._transformYawPitch) {
  80709. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80710. }
  80711. if (parentBone) {
  80712. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80713. }
  80714. else {
  80715. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80716. }
  80717. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80718. rightAxis.normalize();
  80719. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80720. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80721. }
  80722. spaceMat.invertToRef(spaceMatInv);
  80723. var xzlen = null;
  80724. if (checkPitch) {
  80725. var localTarget = BoneLookController._tmpVecs[3];
  80726. target.subtractToRef(bonePos, localTarget);
  80727. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80728. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80729. var pitch = Math.atan2(localTarget.y, xzlen);
  80730. var newPitch = pitch;
  80731. if (pitch > this._maxPitch) {
  80732. localTarget.y = this._maxPitchTan * xzlen;
  80733. newPitch = this._maxPitch;
  80734. }
  80735. else if (pitch < this._minPitch) {
  80736. localTarget.y = this._minPitchTan * xzlen;
  80737. newPitch = this._minPitch;
  80738. }
  80739. if (pitch != newPitch) {
  80740. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80741. localTarget.addInPlace(bonePos);
  80742. target = localTarget;
  80743. }
  80744. }
  80745. if (checkYaw) {
  80746. var localTarget = BoneLookController._tmpVecs[4];
  80747. target.subtractToRef(bonePos, localTarget);
  80748. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80749. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80750. var newYaw = yaw;
  80751. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80752. if (xzlen == null) {
  80753. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80754. }
  80755. if (this._yawRange > Math.PI) {
  80756. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80757. localTarget.z = this._maxYawCos * xzlen;
  80758. localTarget.x = this._maxYawSin * xzlen;
  80759. newYaw = this._maxYaw;
  80760. }
  80761. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80762. localTarget.z = this._minYawCos * xzlen;
  80763. localTarget.x = this._minYawSin * xzlen;
  80764. newYaw = this._minYaw;
  80765. }
  80766. }
  80767. else {
  80768. if (yaw > this._maxYaw) {
  80769. localTarget.z = this._maxYawCos * xzlen;
  80770. localTarget.x = this._maxYawSin * xzlen;
  80771. newYaw = this._maxYaw;
  80772. }
  80773. else if (yaw < this._minYaw) {
  80774. localTarget.z = this._minYawCos * xzlen;
  80775. localTarget.x = this._minYawSin * xzlen;
  80776. newYaw = this._minYaw;
  80777. }
  80778. }
  80779. }
  80780. if (this._slerping && this._yawRange > Math.PI) {
  80781. //are we going to be crossing into the min/max region?
  80782. var boneFwd = BoneLookController._tmpVecs[8];
  80783. boneFwd.copyFrom(BABYLON.Axis.Z);
  80784. if (this._transformYawPitch) {
  80785. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80786. }
  80787. var boneRotMat = BoneLookController._tmpMats[4];
  80788. this._boneQuat.toRotationMatrix(boneRotMat);
  80789. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80790. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80791. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80792. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80793. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80794. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80795. if (angBtwTar > angBtwMidYaw) {
  80796. if (xzlen == null) {
  80797. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80798. }
  80799. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80800. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80801. if (angBtwMin < angBtwMax) {
  80802. newYaw = boneYaw + Math.PI * .75;
  80803. localTarget.z = Math.cos(newYaw) * xzlen;
  80804. localTarget.x = Math.sin(newYaw) * xzlen;
  80805. }
  80806. else {
  80807. newYaw = boneYaw - Math.PI * .75;
  80808. localTarget.z = Math.cos(newYaw) * xzlen;
  80809. localTarget.x = Math.sin(newYaw) * xzlen;
  80810. }
  80811. }
  80812. }
  80813. if (yaw != newYaw) {
  80814. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80815. localTarget.addInPlace(bonePos);
  80816. target = localTarget;
  80817. }
  80818. }
  80819. }
  80820. var zaxis = BoneLookController._tmpVecs[5];
  80821. var xaxis = BoneLookController._tmpVecs[6];
  80822. var yaxis = BoneLookController._tmpVecs[7];
  80823. var _tmpQuat = BoneLookController._tmpQuat;
  80824. target.subtractToRef(bonePos, zaxis);
  80825. zaxis.normalize();
  80826. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80827. xaxis.normalize();
  80828. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80829. yaxis.normalize();
  80830. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80831. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80832. return;
  80833. }
  80834. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80835. return;
  80836. }
  80837. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80838. return;
  80839. }
  80840. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80841. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80842. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80843. }
  80844. if (this.slerpAmount < 1) {
  80845. if (!this._slerping) {
  80846. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80847. }
  80848. if (this._transformYawPitch) {
  80849. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80850. }
  80851. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80852. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80853. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80854. this._slerping = true;
  80855. }
  80856. else {
  80857. if (this._transformYawPitch) {
  80858. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80859. }
  80860. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80861. this._slerping = false;
  80862. }
  80863. };
  80864. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80865. var angDiff = ang2 - ang1;
  80866. angDiff %= Math.PI * 2;
  80867. if (angDiff > Math.PI) {
  80868. angDiff -= Math.PI * 2;
  80869. }
  80870. else if (angDiff < -Math.PI) {
  80871. angDiff += Math.PI * 2;
  80872. }
  80873. return angDiff;
  80874. };
  80875. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80876. ang1 %= (2 * Math.PI);
  80877. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80878. ang2 %= (2 * Math.PI);
  80879. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80880. var ab = 0;
  80881. if (ang1 < ang2) {
  80882. ab = ang2 - ang1;
  80883. }
  80884. else {
  80885. ab = ang1 - ang2;
  80886. }
  80887. if (ab > Math.PI) {
  80888. ab = Math.PI * 2 - ab;
  80889. }
  80890. return ab;
  80891. };
  80892. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80893. ang %= (2 * Math.PI);
  80894. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80895. ang1 %= (2 * Math.PI);
  80896. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80897. ang2 %= (2 * Math.PI);
  80898. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80899. if (ang1 < ang2) {
  80900. if (ang > ang1 && ang < ang2) {
  80901. return true;
  80902. }
  80903. }
  80904. else {
  80905. if (ang > ang2 && ang < ang1) {
  80906. return true;
  80907. }
  80908. }
  80909. return false;
  80910. };
  80911. 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()];
  80912. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80913. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80914. return BoneLookController;
  80915. }());
  80916. BABYLON.BoneLookController = BoneLookController;
  80917. })(BABYLON || (BABYLON = {}));
  80918. //# sourceMappingURL=babylon.boneLookController.js.map
  80919. var BABYLON;
  80920. (function (BABYLON) {
  80921. /**
  80922. * Class used to handle skinning animations
  80923. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80924. */
  80925. var Skeleton = /** @class */ (function () {
  80926. /**
  80927. * Creates a new skeleton
  80928. * @param name defines the skeleton name
  80929. * @param id defines the skeleton Id
  80930. * @param scene defines the hosting scene
  80931. */
  80932. function Skeleton(
  80933. /** defines the skeleton name */
  80934. name,
  80935. /** defines the skeleton Id */
  80936. id, scene) {
  80937. this.name = name;
  80938. this.id = id;
  80939. /**
  80940. * Gets the list of child bones
  80941. */
  80942. this.bones = new Array();
  80943. /**
  80944. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80945. */
  80946. this.needInitialSkinMatrix = false;
  80947. this._isDirty = true;
  80948. this._meshesWithPoseMatrix = new Array();
  80949. this._identity = BABYLON.Matrix.Identity();
  80950. this._ranges = {};
  80951. this._lastAbsoluteTransformsUpdateId = -1;
  80952. /**
  80953. * Specifies if the skeleton should be serialized
  80954. */
  80955. this.doNotSerialize = false;
  80956. this._animationPropertiesOverride = null;
  80957. // Events
  80958. /**
  80959. * An observable triggered before computing the skeleton's matrices
  80960. */
  80961. this.onBeforeComputeObservable = new BABYLON.Observable();
  80962. this.bones = [];
  80963. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80964. scene.skeletons.push(this);
  80965. //make sure it will recalculate the matrix next time prepare is called.
  80966. this._isDirty = true;
  80967. }
  80968. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80969. /**
  80970. * Gets or sets the animation properties override
  80971. */
  80972. get: function () {
  80973. if (!this._animationPropertiesOverride) {
  80974. return this._scene.animationPropertiesOverride;
  80975. }
  80976. return this._animationPropertiesOverride;
  80977. },
  80978. set: function (value) {
  80979. this._animationPropertiesOverride = value;
  80980. },
  80981. enumerable: true,
  80982. configurable: true
  80983. });
  80984. // Members
  80985. /**
  80986. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80987. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80988. * @returns a Float32Array containing matrices data
  80989. */
  80990. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80991. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80992. return mesh._bonesTransformMatrices;
  80993. }
  80994. if (!this._transformMatrices) {
  80995. this.prepare();
  80996. }
  80997. return this._transformMatrices;
  80998. };
  80999. /**
  81000. * Gets the current hosting scene
  81001. * @returns a scene object
  81002. */
  81003. Skeleton.prototype.getScene = function () {
  81004. return this._scene;
  81005. };
  81006. // Methods
  81007. /**
  81008. * Gets a string representing the current skeleton data
  81009. * @param fullDetails defines a boolean indicating if we want a verbose version
  81010. * @returns a string representing the current skeleton data
  81011. */
  81012. Skeleton.prototype.toString = function (fullDetails) {
  81013. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81014. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81015. if (fullDetails) {
  81016. ret += ", Ranges: {";
  81017. var first = true;
  81018. for (var name_1 in this._ranges) {
  81019. if (first) {
  81020. ret += ", ";
  81021. first = false;
  81022. }
  81023. ret += name_1;
  81024. }
  81025. ret += "}";
  81026. }
  81027. return ret;
  81028. };
  81029. /**
  81030. * Get bone's index searching by name
  81031. * @param name defines bone's name to search for
  81032. * @return the indice of the bone. Returns -1 if not found
  81033. */
  81034. Skeleton.prototype.getBoneIndexByName = function (name) {
  81035. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81036. if (this.bones[boneIndex].name === name) {
  81037. return boneIndex;
  81038. }
  81039. }
  81040. return -1;
  81041. };
  81042. /**
  81043. * Creater a new animation range
  81044. * @param name defines the name of the range
  81045. * @param from defines the start key
  81046. * @param to defines the end key
  81047. */
  81048. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81049. // check name not already in use
  81050. if (!this._ranges[name]) {
  81051. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81052. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81053. if (this.bones[i].animations[0]) {
  81054. this.bones[i].animations[0].createRange(name, from, to);
  81055. }
  81056. }
  81057. }
  81058. };
  81059. /**
  81060. * Delete a specific animation range
  81061. * @param name defines the name of the range
  81062. * @param deleteFrames defines if frames must be removed as well
  81063. */
  81064. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81065. if (deleteFrames === void 0) { deleteFrames = true; }
  81066. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81067. if (this.bones[i].animations[0]) {
  81068. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81069. }
  81070. }
  81071. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81072. };
  81073. /**
  81074. * Gets a specific animation range
  81075. * @param name defines the name of the range to look for
  81076. * @returns the requested animation range or null if not found
  81077. */
  81078. Skeleton.prototype.getAnimationRange = function (name) {
  81079. return this._ranges[name];
  81080. };
  81081. /**
  81082. * Gets the list of all animation ranges defined on this skeleton
  81083. * @returns an array
  81084. */
  81085. Skeleton.prototype.getAnimationRanges = function () {
  81086. var animationRanges = [];
  81087. var name;
  81088. var i = 0;
  81089. for (name in this._ranges) {
  81090. animationRanges[i] = this._ranges[name];
  81091. i++;
  81092. }
  81093. return animationRanges;
  81094. };
  81095. /**
  81096. * Copy animation range from a source skeleton.
  81097. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81098. * @param source defines the source skeleton
  81099. * @param name defines the name of the range to copy
  81100. * @param rescaleAsRequired defines if rescaling must be applied if required
  81101. * @returns true if operation was successful
  81102. */
  81103. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81104. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81105. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81106. return false;
  81107. }
  81108. var ret = true;
  81109. var frameOffset = this._getHighestAnimationFrame() + 1;
  81110. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81111. var boneDict = {};
  81112. var sourceBones = source.bones;
  81113. var nBones;
  81114. var i;
  81115. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81116. boneDict[sourceBones[i].name] = sourceBones[i];
  81117. }
  81118. if (this.bones.length !== sourceBones.length) {
  81119. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81120. ret = false;
  81121. }
  81122. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81123. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81124. var boneName = this.bones[i].name;
  81125. var sourceBone = boneDict[boneName];
  81126. if (sourceBone) {
  81127. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81128. }
  81129. else {
  81130. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81131. ret = false;
  81132. }
  81133. }
  81134. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81135. var range = source.getAnimationRange(name);
  81136. if (range) {
  81137. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81138. }
  81139. return ret;
  81140. };
  81141. /**
  81142. * Forces the skeleton to go to rest pose
  81143. */
  81144. Skeleton.prototype.returnToRest = function () {
  81145. for (var index = 0; index < this.bones.length; index++) {
  81146. this.bones[index].returnToRest();
  81147. }
  81148. };
  81149. Skeleton.prototype._getHighestAnimationFrame = function () {
  81150. var ret = 0;
  81151. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81152. if (this.bones[i].animations[0]) {
  81153. var highest = this.bones[i].animations[0].getHighestFrame();
  81154. if (ret < highest) {
  81155. ret = highest;
  81156. }
  81157. }
  81158. }
  81159. return ret;
  81160. };
  81161. /**
  81162. * Begin a specific animation range
  81163. * @param name defines the name of the range to start
  81164. * @param loop defines if looping must be turned on (false by default)
  81165. * @param speedRatio defines the speed ratio to apply (1 by default)
  81166. * @param onAnimationEnd defines a callback which will be called when animation will end
  81167. * @returns a new animatable
  81168. */
  81169. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81170. var range = this.getAnimationRange(name);
  81171. if (!range) {
  81172. return null;
  81173. }
  81174. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81175. };
  81176. /** @hidden */
  81177. Skeleton.prototype._markAsDirty = function () {
  81178. this._isDirty = true;
  81179. };
  81180. /** @hidden */
  81181. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81182. this._meshesWithPoseMatrix.push(mesh);
  81183. };
  81184. /** @hidden */
  81185. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81186. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81187. if (index > -1) {
  81188. this._meshesWithPoseMatrix.splice(index, 1);
  81189. }
  81190. };
  81191. /** @hidden */
  81192. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81193. this.onBeforeComputeObservable.notifyObservers(this);
  81194. for (var index = 0; index < this.bones.length; index++) {
  81195. var bone = this.bones[index];
  81196. var parentBone = bone.getParent();
  81197. if (parentBone) {
  81198. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81199. }
  81200. else {
  81201. if (initialSkinMatrix) {
  81202. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81203. }
  81204. else {
  81205. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81206. }
  81207. }
  81208. if (bone._index !== -1) {
  81209. var mappedIndex = bone._index === null ? index : bone._index;
  81210. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81211. }
  81212. }
  81213. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81214. };
  81215. /**
  81216. * Build all resources required to render a skeleton
  81217. */
  81218. Skeleton.prototype.prepare = function () {
  81219. if (!this._isDirty) {
  81220. return;
  81221. }
  81222. if (this.needInitialSkinMatrix) {
  81223. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81224. var mesh = this._meshesWithPoseMatrix[index];
  81225. var poseMatrix = mesh.getPoseMatrix();
  81226. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81227. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81228. }
  81229. if (this._synchronizedWithMesh !== mesh) {
  81230. this._synchronizedWithMesh = mesh;
  81231. // Prepare bones
  81232. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81233. var bone = this.bones[boneIndex];
  81234. if (!bone.getParent()) {
  81235. var matrix = bone.getBaseMatrix();
  81236. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81237. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81238. }
  81239. }
  81240. }
  81241. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81242. }
  81243. }
  81244. else {
  81245. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81246. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81247. }
  81248. this._computeTransformMatrices(this._transformMatrices, null);
  81249. }
  81250. this._isDirty = false;
  81251. this._scene._activeBones.addCount(this.bones.length, false);
  81252. };
  81253. /**
  81254. * Gets the list of animatables currently running for this skeleton
  81255. * @returns an array of animatables
  81256. */
  81257. Skeleton.prototype.getAnimatables = function () {
  81258. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81259. this._animatables = [];
  81260. for (var index = 0; index < this.bones.length; index++) {
  81261. this._animatables.push(this.bones[index]);
  81262. }
  81263. }
  81264. return this._animatables;
  81265. };
  81266. /**
  81267. * Clone the current skeleton
  81268. * @param name defines the name of the new skeleton
  81269. * @param id defines the id of the enw skeleton
  81270. * @returns the new skeleton
  81271. */
  81272. Skeleton.prototype.clone = function (name, id) {
  81273. var result = new Skeleton(name, id || name, this._scene);
  81274. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81275. for (var index = 0; index < this.bones.length; index++) {
  81276. var source = this.bones[index];
  81277. var parentBone = null;
  81278. var parent_1 = source.getParent();
  81279. if (parent_1) {
  81280. var parentIndex = this.bones.indexOf(parent_1);
  81281. parentBone = result.bones[parentIndex];
  81282. }
  81283. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81284. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81285. }
  81286. if (this._ranges) {
  81287. result._ranges = {};
  81288. for (var rangeName in this._ranges) {
  81289. var range = this._ranges[rangeName];
  81290. if (range) {
  81291. result._ranges[rangeName] = range.clone();
  81292. }
  81293. }
  81294. }
  81295. this._isDirty = true;
  81296. return result;
  81297. };
  81298. /**
  81299. * Enable animation blending for this skeleton
  81300. * @param blendingSpeed defines the blending speed to apply
  81301. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81302. */
  81303. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81304. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81305. this.bones.forEach(function (bone) {
  81306. bone.animations.forEach(function (animation) {
  81307. animation.enableBlending = true;
  81308. animation.blendingSpeed = blendingSpeed;
  81309. });
  81310. });
  81311. };
  81312. /**
  81313. * Releases all resources associated with the current skeleton
  81314. */
  81315. Skeleton.prototype.dispose = function () {
  81316. this._meshesWithPoseMatrix = [];
  81317. // Animations
  81318. this.getScene().stopAnimation(this);
  81319. // Remove from scene
  81320. this.getScene().removeSkeleton(this);
  81321. };
  81322. /**
  81323. * Serialize the skeleton in a JSON object
  81324. * @returns a JSON object
  81325. */
  81326. Skeleton.prototype.serialize = function () {
  81327. var serializationObject = {};
  81328. serializationObject.name = this.name;
  81329. serializationObject.id = this.id;
  81330. if (this.dimensionsAtRest) {
  81331. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81332. }
  81333. serializationObject.bones = [];
  81334. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81335. for (var index = 0; index < this.bones.length; index++) {
  81336. var bone = this.bones[index];
  81337. var parent_2 = bone.getParent();
  81338. var serializedBone = {
  81339. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81340. name: bone.name,
  81341. matrix: bone.getBaseMatrix().toArray(),
  81342. rest: bone.getRestPose().toArray()
  81343. };
  81344. serializationObject.bones.push(serializedBone);
  81345. if (bone.length) {
  81346. serializedBone.length = bone.length;
  81347. }
  81348. if (bone.metadata) {
  81349. serializedBone.metadata = bone.metadata;
  81350. }
  81351. if (bone.animations && bone.animations.length > 0) {
  81352. serializedBone.animation = bone.animations[0].serialize();
  81353. }
  81354. serializationObject.ranges = [];
  81355. for (var name in this._ranges) {
  81356. var source = this._ranges[name];
  81357. if (!source) {
  81358. continue;
  81359. }
  81360. var range = {};
  81361. range.name = name;
  81362. range.from = source.from;
  81363. range.to = source.to;
  81364. serializationObject.ranges.push(range);
  81365. }
  81366. }
  81367. return serializationObject;
  81368. };
  81369. /**
  81370. * Creates a new skeleton from serialized data
  81371. * @param parsedSkeleton defines the serialized data
  81372. * @param scene defines the hosting scene
  81373. * @returns a new skeleton
  81374. */
  81375. Skeleton.Parse = function (parsedSkeleton, scene) {
  81376. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81377. if (parsedSkeleton.dimensionsAtRest) {
  81378. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81379. }
  81380. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81381. var index;
  81382. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81383. var parsedBone = parsedSkeleton.bones[index];
  81384. var parentBone = null;
  81385. if (parsedBone.parentBoneIndex > -1) {
  81386. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81387. }
  81388. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81389. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81390. if (parsedBone.length) {
  81391. bone.length = parsedBone.length;
  81392. }
  81393. if (parsedBone.metadata) {
  81394. bone.metadata = parsedBone.metadata;
  81395. }
  81396. if (parsedBone.animation) {
  81397. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81398. }
  81399. }
  81400. // placed after bones, so createAnimationRange can cascade down
  81401. if (parsedSkeleton.ranges) {
  81402. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81403. var data = parsedSkeleton.ranges[index];
  81404. skeleton.createAnimationRange(data.name, data.from, data.to);
  81405. }
  81406. }
  81407. return skeleton;
  81408. };
  81409. /**
  81410. * Compute all node absolute transforms
  81411. * @param forceUpdate defines if computation must be done even if cache is up to date
  81412. */
  81413. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81414. if (forceUpdate === void 0) { forceUpdate = false; }
  81415. var renderId = this._scene.getRenderId();
  81416. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81417. this.bones[0].computeAbsoluteTransforms();
  81418. this._lastAbsoluteTransformsUpdateId = renderId;
  81419. }
  81420. };
  81421. /**
  81422. * Gets the root pose matrix
  81423. * @returns a matrix
  81424. */
  81425. Skeleton.prototype.getPoseMatrix = function () {
  81426. var poseMatrix = null;
  81427. if (this._meshesWithPoseMatrix.length > 0) {
  81428. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81429. }
  81430. return poseMatrix;
  81431. };
  81432. /**
  81433. * Sorts bones per internal index
  81434. */
  81435. Skeleton.prototype.sortBones = function () {
  81436. var bones = new Array();
  81437. var visited = new Array(this.bones.length);
  81438. for (var index = 0; index < this.bones.length; index++) {
  81439. this._sortBones(index, bones, visited);
  81440. }
  81441. this.bones = bones;
  81442. };
  81443. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81444. if (visited[index]) {
  81445. return;
  81446. }
  81447. visited[index] = true;
  81448. var bone = this.bones[index];
  81449. if (bone._index === undefined) {
  81450. bone._index = index;
  81451. }
  81452. var parentBone = bone.getParent();
  81453. if (parentBone) {
  81454. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81455. }
  81456. bones.push(bone);
  81457. };
  81458. return Skeleton;
  81459. }());
  81460. BABYLON.Skeleton = Skeleton;
  81461. })(BABYLON || (BABYLON = {}));
  81462. //# sourceMappingURL=babylon.skeleton.js.map
  81463. var BABYLON;
  81464. (function (BABYLON) {
  81465. var SphericalPolynomial = /** @class */ (function () {
  81466. function SphericalPolynomial() {
  81467. this.x = BABYLON.Vector3.Zero();
  81468. this.y = BABYLON.Vector3.Zero();
  81469. this.z = BABYLON.Vector3.Zero();
  81470. this.xx = BABYLON.Vector3.Zero();
  81471. this.yy = BABYLON.Vector3.Zero();
  81472. this.zz = BABYLON.Vector3.Zero();
  81473. this.xy = BABYLON.Vector3.Zero();
  81474. this.yz = BABYLON.Vector3.Zero();
  81475. this.zx = BABYLON.Vector3.Zero();
  81476. }
  81477. SphericalPolynomial.prototype.addAmbient = function (color) {
  81478. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81479. this.xx = this.xx.add(colorVector);
  81480. this.yy = this.yy.add(colorVector);
  81481. this.zz = this.zz.add(colorVector);
  81482. };
  81483. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81484. var result = new SphericalPolynomial();
  81485. result.x = harmonics.L11.scale(1.02333);
  81486. result.y = harmonics.L1_1.scale(1.02333);
  81487. result.z = harmonics.L10.scale(1.02333);
  81488. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81489. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81490. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81491. result.yz = harmonics.L2_1.scale(0.858086);
  81492. result.zx = harmonics.L21.scale(0.858086);
  81493. result.xy = harmonics.L2_2.scale(0.858086);
  81494. result.scale(1.0 / Math.PI);
  81495. return result;
  81496. };
  81497. SphericalPolynomial.prototype.scale = function (scale) {
  81498. this.x = this.x.scale(scale);
  81499. this.y = this.y.scale(scale);
  81500. this.z = this.z.scale(scale);
  81501. this.xx = this.xx.scale(scale);
  81502. this.yy = this.yy.scale(scale);
  81503. this.zz = this.zz.scale(scale);
  81504. this.yz = this.yz.scale(scale);
  81505. this.zx = this.zx.scale(scale);
  81506. this.xy = this.xy.scale(scale);
  81507. };
  81508. return SphericalPolynomial;
  81509. }());
  81510. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81511. var SphericalHarmonics = /** @class */ (function () {
  81512. function SphericalHarmonics() {
  81513. this.L00 = BABYLON.Vector3.Zero();
  81514. this.L1_1 = BABYLON.Vector3.Zero();
  81515. this.L10 = BABYLON.Vector3.Zero();
  81516. this.L11 = BABYLON.Vector3.Zero();
  81517. this.L2_2 = BABYLON.Vector3.Zero();
  81518. this.L2_1 = BABYLON.Vector3.Zero();
  81519. this.L20 = BABYLON.Vector3.Zero();
  81520. this.L21 = BABYLON.Vector3.Zero();
  81521. this.L22 = BABYLON.Vector3.Zero();
  81522. }
  81523. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81524. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81525. var c = colorVector.scale(deltaSolidAngle);
  81526. this.L00 = this.L00.add(c.scale(0.282095));
  81527. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81528. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81529. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81530. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81531. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81532. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81533. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81534. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81535. };
  81536. SphericalHarmonics.prototype.scale = function (scale) {
  81537. this.L00 = this.L00.scale(scale);
  81538. this.L1_1 = this.L1_1.scale(scale);
  81539. this.L10 = this.L10.scale(scale);
  81540. this.L11 = this.L11.scale(scale);
  81541. this.L2_2 = this.L2_2.scale(scale);
  81542. this.L2_1 = this.L2_1.scale(scale);
  81543. this.L20 = this.L20.scale(scale);
  81544. this.L21 = this.L21.scale(scale);
  81545. this.L22 = this.L22.scale(scale);
  81546. };
  81547. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81548. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81549. //
  81550. // E_lm = A_l * L_lm
  81551. //
  81552. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81553. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81554. // the scaling factors are given in equation 9.
  81555. // Constant (Band 0)
  81556. this.L00 = this.L00.scale(3.141593);
  81557. // Linear (Band 1)
  81558. this.L1_1 = this.L1_1.scale(2.094395);
  81559. this.L10 = this.L10.scale(2.094395);
  81560. this.L11 = this.L11.scale(2.094395);
  81561. // Quadratic (Band 2)
  81562. this.L2_2 = this.L2_2.scale(0.785398);
  81563. this.L2_1 = this.L2_1.scale(0.785398);
  81564. this.L20 = this.L20.scale(0.785398);
  81565. this.L21 = this.L21.scale(0.785398);
  81566. this.L22 = this.L22.scale(0.785398);
  81567. };
  81568. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81569. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81570. // L = (1/pi) * E * rho
  81571. //
  81572. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81573. this.scale(1.0 / Math.PI);
  81574. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81575. // (The pixel shader must apply albedo after texture fetches, etc).
  81576. };
  81577. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81578. var result = new SphericalHarmonics();
  81579. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81580. result.L1_1 = polynomial.y.scale(0.977204);
  81581. result.L10 = polynomial.z.scale(0.977204);
  81582. result.L11 = polynomial.x.scale(0.977204);
  81583. result.L2_2 = polynomial.xy.scale(1.16538);
  81584. result.L2_1 = polynomial.yz.scale(1.16538);
  81585. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81586. result.L21 = polynomial.zx.scale(1.16538);
  81587. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81588. result.scale(Math.PI);
  81589. return result;
  81590. };
  81591. return SphericalHarmonics;
  81592. }());
  81593. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81594. })(BABYLON || (BABYLON = {}));
  81595. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81596. var BABYLON;
  81597. (function (BABYLON) {
  81598. var FileFaceOrientation = /** @class */ (function () {
  81599. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81600. this.name = name;
  81601. this.worldAxisForNormal = worldAxisForNormal;
  81602. this.worldAxisForFileX = worldAxisForFileX;
  81603. this.worldAxisForFileY = worldAxisForFileY;
  81604. }
  81605. return FileFaceOrientation;
  81606. }());
  81607. ;
  81608. /**
  81609. * Helper class dealing with the extraction of spherical polynomial dataArray
  81610. * from a cube map.
  81611. */
  81612. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81613. function CubeMapToSphericalPolynomialTools() {
  81614. }
  81615. /**
  81616. * Converts a texture to the according Spherical Polynomial data.
  81617. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81618. *
  81619. * @param texture The texture to extract the information from.
  81620. * @return The Spherical Polynomial data.
  81621. */
  81622. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81623. if (!texture.isCube) {
  81624. // Only supports cube Textures currently.
  81625. return null;
  81626. }
  81627. var size = texture.getSize().width;
  81628. var right = texture.readPixels(0);
  81629. var left = texture.readPixels(1);
  81630. var up;
  81631. var down;
  81632. if (texture.isRenderTarget) {
  81633. up = texture.readPixels(3);
  81634. down = texture.readPixels(2);
  81635. }
  81636. else {
  81637. up = texture.readPixels(2);
  81638. down = texture.readPixels(3);
  81639. }
  81640. var front = texture.readPixels(4);
  81641. var back = texture.readPixels(5);
  81642. var gammaSpace = texture.gammaSpace;
  81643. // Always read as RGBA.
  81644. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81645. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81646. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81647. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81648. }
  81649. var cubeInfo = {
  81650. size: size,
  81651. right: right,
  81652. left: left,
  81653. up: up,
  81654. down: down,
  81655. front: front,
  81656. back: back,
  81657. format: format,
  81658. type: type,
  81659. gammaSpace: gammaSpace,
  81660. };
  81661. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81662. };
  81663. /**
  81664. * Converts a cubemap to the according Spherical Polynomial data.
  81665. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81666. *
  81667. * @param cubeInfo The Cube map to extract the information from.
  81668. * @return The Spherical Polynomial data.
  81669. */
  81670. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81671. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81672. var totalSolidAngle = 0.0;
  81673. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81674. var du = 2.0 / cubeInfo.size;
  81675. var dv = du;
  81676. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81677. var minUV = du * 0.5 - 1.0;
  81678. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81679. var fileFace = this.FileFaces[faceIndex];
  81680. var dataArray = cubeInfo[fileFace.name];
  81681. var v = minUV;
  81682. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81683. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81684. // Because SP is still linear, so summation is fine in that basis.
  81685. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81686. for (var y = 0; y < cubeInfo.size; y++) {
  81687. var u = minUV;
  81688. for (var x = 0; x < cubeInfo.size; x++) {
  81689. // World direction (not normalised)
  81690. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81691. worldDirection.normalize();
  81692. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81693. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81694. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81695. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81696. // Handle Integer types.
  81697. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81698. r /= 255;
  81699. g /= 255;
  81700. b /= 255;
  81701. }
  81702. // Handle Gamma space textures.
  81703. if (cubeInfo.gammaSpace) {
  81704. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81705. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81706. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81707. }
  81708. var color = new BABYLON.Color3(r, g, b);
  81709. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81710. totalSolidAngle += deltaSolidAngle;
  81711. u += du;
  81712. }
  81713. v += dv;
  81714. }
  81715. }
  81716. // Solid angle for entire sphere is 4*pi
  81717. var sphereSolidAngle = 4.0 * Math.PI;
  81718. // Adjust the solid angle to allow for how many faces we processed.
  81719. var facesProcessed = 6.0;
  81720. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81721. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81722. // This is needed because the numerical integration over the cube uses a
  81723. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81724. // and also to compensate for accumulative error due to float precision in the summation.
  81725. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81726. sphericalHarmonics.scale(correctionFactor);
  81727. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81728. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81729. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81730. };
  81731. CubeMapToSphericalPolynomialTools.FileFaces = [
  81732. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81733. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81734. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81735. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81736. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81737. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81738. ];
  81739. return CubeMapToSphericalPolynomialTools;
  81740. }());
  81741. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81742. })(BABYLON || (BABYLON = {}));
  81743. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81744. var BABYLON;
  81745. (function (BABYLON) {
  81746. /**
  81747. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81748. */
  81749. var PanoramaToCubeMapTools = /** @class */ (function () {
  81750. function PanoramaToCubeMapTools() {
  81751. }
  81752. /**
  81753. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81754. *
  81755. * @param float32Array The source data.
  81756. * @param inputWidth The width of the input panorama.
  81757. * @param inputhHeight The height of the input panorama.
  81758. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81759. * @return The cubemap data
  81760. */
  81761. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81762. if (!float32Array) {
  81763. throw "ConvertPanoramaToCubemap: input cannot be null";
  81764. }
  81765. if (float32Array.length != inputWidth * inputHeight * 3) {
  81766. throw "ConvertPanoramaToCubemap: input size is wrong";
  81767. }
  81768. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81769. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81770. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81771. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81772. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81773. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81774. return {
  81775. front: textureFront,
  81776. back: textureBack,
  81777. left: textureLeft,
  81778. right: textureRight,
  81779. up: textureUp,
  81780. down: textureDown,
  81781. size: size,
  81782. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81783. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81784. gammaSpace: false,
  81785. };
  81786. };
  81787. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81788. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81789. var textureArray = new Float32Array(buffer);
  81790. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81791. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81792. var dy = 1 / texSize;
  81793. var fy = 0;
  81794. for (var y = 0; y < texSize; y++) {
  81795. var xv1 = faceData[0];
  81796. var xv2 = faceData[2];
  81797. for (var x = 0; x < texSize; x++) {
  81798. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81799. v.normalize();
  81800. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81801. // 3 channels per pixels
  81802. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81803. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81804. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81805. xv1 = xv1.add(rotDX1);
  81806. xv2 = xv2.add(rotDX2);
  81807. }
  81808. fy += dy;
  81809. }
  81810. return textureArray;
  81811. };
  81812. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81813. var theta = Math.atan2(vDir.z, vDir.x);
  81814. var phi = Math.acos(vDir.y);
  81815. while (theta < -Math.PI)
  81816. theta += 2 * Math.PI;
  81817. while (theta > Math.PI)
  81818. theta -= 2 * Math.PI;
  81819. var dx = theta / Math.PI;
  81820. var dy = phi / Math.PI;
  81821. // recenter.
  81822. dx = dx * 0.5 + 0.5;
  81823. var px = Math.round(dx * inputWidth);
  81824. if (px < 0)
  81825. px = 0;
  81826. else if (px >= inputWidth)
  81827. px = inputWidth - 1;
  81828. var py = Math.round(dy * inputHeight);
  81829. if (py < 0)
  81830. py = 0;
  81831. else if (py >= inputHeight)
  81832. py = inputHeight - 1;
  81833. var inputY = (inputHeight - py - 1);
  81834. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81835. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81836. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81837. return {
  81838. r: r,
  81839. g: g,
  81840. b: b
  81841. };
  81842. };
  81843. PanoramaToCubeMapTools.FACE_FRONT = [
  81844. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81845. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81846. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81847. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81848. ];
  81849. PanoramaToCubeMapTools.FACE_BACK = [
  81850. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81851. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81852. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81853. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81854. ];
  81855. PanoramaToCubeMapTools.FACE_RIGHT = [
  81856. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81857. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81858. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81859. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81860. ];
  81861. PanoramaToCubeMapTools.FACE_LEFT = [
  81862. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81863. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81864. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81865. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81866. ];
  81867. PanoramaToCubeMapTools.FACE_DOWN = [
  81868. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81869. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81870. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81871. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81872. ];
  81873. PanoramaToCubeMapTools.FACE_UP = [
  81874. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81875. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81876. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81877. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81878. ];
  81879. return PanoramaToCubeMapTools;
  81880. }());
  81881. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81882. })(BABYLON || (BABYLON = {}));
  81883. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81884. var BABYLON;
  81885. (function (BABYLON) {
  81886. ;
  81887. /**
  81888. * This groups tools to convert HDR texture to native colors array.
  81889. */
  81890. var HDRTools = /** @class */ (function () {
  81891. function HDRTools() {
  81892. }
  81893. HDRTools.Ldexp = function (mantissa, exponent) {
  81894. if (exponent > 1023) {
  81895. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81896. }
  81897. if (exponent < -1074) {
  81898. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81899. }
  81900. return mantissa * Math.pow(2, exponent);
  81901. };
  81902. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81903. if (exponent > 0) { /*nonzero pixel*/
  81904. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81905. float32array[index + 0] = red * exponent;
  81906. float32array[index + 1] = green * exponent;
  81907. float32array[index + 2] = blue * exponent;
  81908. }
  81909. else {
  81910. float32array[index + 0] = 0;
  81911. float32array[index + 1] = 0;
  81912. float32array[index + 2] = 0;
  81913. }
  81914. };
  81915. HDRTools.readStringLine = function (uint8array, startIndex) {
  81916. var line = "";
  81917. var character = "";
  81918. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81919. character = String.fromCharCode(uint8array[i]);
  81920. if (character == "\n") {
  81921. break;
  81922. }
  81923. line += character;
  81924. }
  81925. return line;
  81926. };
  81927. /**
  81928. * Reads header information from an RGBE texture stored in a native array.
  81929. * More information on this format are available here:
  81930. * https://en.wikipedia.org/wiki/RGBE_image_format
  81931. *
  81932. * @param uint8array The binary file stored in native array.
  81933. * @return The header information.
  81934. */
  81935. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81936. var height = 0;
  81937. var width = 0;
  81938. var line = this.readStringLine(uint8array, 0);
  81939. if (line[0] != '#' || line[1] != '?') {
  81940. throw "Bad HDR Format.";
  81941. }
  81942. var endOfHeader = false;
  81943. var findFormat = false;
  81944. var lineIndex = 0;
  81945. do {
  81946. lineIndex += (line.length + 1);
  81947. line = this.readStringLine(uint8array, lineIndex);
  81948. if (line == "FORMAT=32-bit_rle_rgbe") {
  81949. findFormat = true;
  81950. }
  81951. else if (line.length == 0) {
  81952. endOfHeader = true;
  81953. }
  81954. } while (!endOfHeader);
  81955. if (!findFormat) {
  81956. throw "HDR Bad header format, unsupported FORMAT";
  81957. }
  81958. lineIndex += (line.length + 1);
  81959. line = this.readStringLine(uint8array, lineIndex);
  81960. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81961. var match = sizeRegexp.exec(line);
  81962. // TODO. Support +Y and -X if needed.
  81963. if (!match || match.length < 3) {
  81964. throw "HDR Bad header format, no size";
  81965. }
  81966. width = parseInt(match[2]);
  81967. height = parseInt(match[1]);
  81968. if (width < 8 || width > 0x7fff) {
  81969. throw "HDR Bad header format, unsupported size";
  81970. }
  81971. lineIndex += (line.length + 1);
  81972. return {
  81973. height: height,
  81974. width: width,
  81975. dataPosition: lineIndex
  81976. };
  81977. };
  81978. /**
  81979. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81980. * This RGBE texture needs to store the information as a panorama.
  81981. *
  81982. * More information on this format are available here:
  81983. * https://en.wikipedia.org/wiki/RGBE_image_format
  81984. *
  81985. * @param buffer The binary file stored in an array buffer.
  81986. * @param size The expected size of the extracted cubemap.
  81987. * @return The Cube Map information.
  81988. */
  81989. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81990. var uint8array = new Uint8Array(buffer);
  81991. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81992. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81993. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81994. return cubeMapData;
  81995. };
  81996. /**
  81997. * Returns the pixels data extracted from an RGBE texture.
  81998. * This pixels will be stored left to right up to down in the R G B order in one array.
  81999. *
  82000. * More information on this format are available here:
  82001. * https://en.wikipedia.org/wiki/RGBE_image_format
  82002. *
  82003. * @param uint8array The binary file stored in an array buffer.
  82004. * @param hdrInfo The header information of the file.
  82005. * @return The pixels data in RGB right to left up to down order.
  82006. */
  82007. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82008. // Keep for multi format supports.
  82009. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82010. };
  82011. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82012. var num_scanlines = hdrInfo.height;
  82013. var scanline_width = hdrInfo.width;
  82014. var a, b, c, d, count;
  82015. var dataIndex = hdrInfo.dataPosition;
  82016. var index = 0, endIndex = 0, i = 0;
  82017. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82018. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82019. // 3 channels of 4 bytes per pixel in float.
  82020. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82021. var resultArray = new Float32Array(resultBuffer);
  82022. // read in each successive scanline
  82023. while (num_scanlines > 0) {
  82024. a = uint8array[dataIndex++];
  82025. b = uint8array[dataIndex++];
  82026. c = uint8array[dataIndex++];
  82027. d = uint8array[dataIndex++];
  82028. if (a != 2 || b != 2 || (c & 0x80)) {
  82029. // this file is not run length encoded
  82030. throw "HDR Bad header format, not RLE";
  82031. }
  82032. if (((c << 8) | d) != scanline_width) {
  82033. throw "HDR Bad header format, wrong scan line width";
  82034. }
  82035. index = 0;
  82036. // read each of the four channels for the scanline into the buffer
  82037. for (i = 0; i < 4; i++) {
  82038. endIndex = (i + 1) * scanline_width;
  82039. while (index < endIndex) {
  82040. a = uint8array[dataIndex++];
  82041. b = uint8array[dataIndex++];
  82042. if (a > 128) {
  82043. // a run of the same value
  82044. count = a - 128;
  82045. if ((count == 0) || (count > endIndex - index)) {
  82046. throw "HDR Bad Format, bad scanline data (run)";
  82047. }
  82048. while (count-- > 0) {
  82049. scanLineArray[index++] = b;
  82050. }
  82051. }
  82052. else {
  82053. // a non-run
  82054. count = a;
  82055. if ((count == 0) || (count > endIndex - index)) {
  82056. throw "HDR Bad Format, bad scanline data (non-run)";
  82057. }
  82058. scanLineArray[index++] = b;
  82059. if (--count > 0) {
  82060. for (var j = 0; j < count; j++) {
  82061. scanLineArray[index++] = uint8array[dataIndex++];
  82062. }
  82063. }
  82064. }
  82065. }
  82066. }
  82067. // now convert data from buffer into floats
  82068. for (i = 0; i < scanline_width; i++) {
  82069. a = scanLineArray[i];
  82070. b = scanLineArray[i + scanline_width];
  82071. c = scanLineArray[i + 2 * scanline_width];
  82072. d = scanLineArray[i + 3 * scanline_width];
  82073. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82074. }
  82075. num_scanlines--;
  82076. }
  82077. return resultArray;
  82078. };
  82079. return HDRTools;
  82080. }());
  82081. BABYLON.HDRTools = HDRTools;
  82082. })(BABYLON || (BABYLON = {}));
  82083. //# sourceMappingURL=babylon.hdr.js.map
  82084. var BABYLON;
  82085. (function (BABYLON) {
  82086. /**
  82087. * Sets of helpers addressing the serialization and deserialization of environment texture
  82088. * stored in a BabylonJS env file.
  82089. * Those files are usually stored as .env files.
  82090. */
  82091. var EnvironmentTextureTools = /** @class */ (function () {
  82092. function EnvironmentTextureTools() {
  82093. }
  82094. /**
  82095. * Gets the environment info from an env file.
  82096. * @param data The array buffer containing the .env bytes.
  82097. * @returns the environment file info (the json header) if successfully parsed.
  82098. */
  82099. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82100. var dataView = new DataView(data);
  82101. var pos = 0;
  82102. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82103. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82104. BABYLON.Tools.Error('Not a babylon environment map');
  82105. return null;
  82106. }
  82107. }
  82108. // Read json manifest - collect characters up to null terminator
  82109. var manifestString = '';
  82110. var charCode = 0x00;
  82111. while ((charCode = dataView.getUint8(pos++))) {
  82112. manifestString += String.fromCharCode(charCode);
  82113. }
  82114. var manifest = JSON.parse(manifestString);
  82115. if (manifest.specular) {
  82116. // Extend the header with the position of the payload.
  82117. manifest.specular.specularDataPosition = pos;
  82118. }
  82119. return manifest;
  82120. };
  82121. /**
  82122. * Creates an environment texture from a loaded cube texture.
  82123. * @param texture defines the cube texture to convert in env file
  82124. * @return a promise containing the environment data if succesfull.
  82125. */
  82126. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82127. var _this = this;
  82128. var internalTexture = texture.getInternalTexture();
  82129. if (!internalTexture) {
  82130. return Promise.reject("The cube texture is invalid.");
  82131. }
  82132. if (!texture._prefiltered) {
  82133. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82134. }
  82135. var engine = internalTexture.getEngine();
  82136. if (engine && engine.premultipliedAlpha) {
  82137. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82138. }
  82139. var canvas = engine.getRenderingCanvas();
  82140. if (!canvas) {
  82141. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82142. }
  82143. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82144. if (!engine.getCaps().textureFloatRender) {
  82145. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82146. if (!engine.getCaps().textureHalfFloatRender) {
  82147. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82148. }
  82149. }
  82150. var cubeWidth = internalTexture.width;
  82151. var hostingScene = new BABYLON.Scene(engine);
  82152. var specularTextures = {};
  82153. var promises = [];
  82154. // Read and collect all mipmaps data from the cube.
  82155. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82156. mipmapsCount = Math.round(mipmapsCount);
  82157. var _loop_1 = function (i) {
  82158. var faceWidth = Math.pow(2, mipmapsCount - i);
  82159. var _loop_2 = function (face) {
  82160. var data = texture.readPixels(face, i);
  82161. // Creates a temp texture with the face data.
  82162. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82163. // And rgbdEncode them.
  82164. var promise = new Promise(function (resolve, reject) {
  82165. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82166. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82167. rgbdPostProcess.onApply = function (effect) {
  82168. effect._bindTexture("textureSampler", tempTexture);
  82169. };
  82170. // As the process needs to happen on the main canvas, keep track of the current size
  82171. var currentW = engine.getRenderWidth();
  82172. var currentH = engine.getRenderHeight();
  82173. // Set the desired size for the texture
  82174. engine.setSize(faceWidth, faceWidth);
  82175. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82176. // Reading datas from WebGL
  82177. canvas.toBlob(function (blob) {
  82178. var fileReader = new FileReader();
  82179. fileReader.onload = function (event) {
  82180. var arrayBuffer = event.target.result;
  82181. specularTextures[i * 6 + face] = arrayBuffer;
  82182. resolve();
  82183. };
  82184. fileReader.readAsArrayBuffer(blob);
  82185. });
  82186. // Reapply the previous canvas size
  82187. engine.setSize(currentW, currentH);
  82188. });
  82189. });
  82190. promises.push(promise);
  82191. };
  82192. // All faces of the cube.
  82193. for (var face = 0; face < 6; face++) {
  82194. _loop_2(face);
  82195. }
  82196. };
  82197. for (var i = 0; i <= mipmapsCount; i++) {
  82198. _loop_1(i);
  82199. }
  82200. // Once all the textures haves been collected as RGBD stored in PNGs
  82201. return Promise.all(promises).then(function () {
  82202. // We can delete the hosting scene keeping track of all the creation objects
  82203. hostingScene.dispose();
  82204. // Creates the json header for the env texture
  82205. var info = {
  82206. version: 1,
  82207. width: cubeWidth,
  82208. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82209. specular: {
  82210. mipmaps: []
  82211. }
  82212. };
  82213. // Sets the specular image data information
  82214. var position = 0;
  82215. for (var i = 0; i <= mipmapsCount; i++) {
  82216. for (var face = 0; face < 6; face++) {
  82217. var byteLength = specularTextures[i * 6 + face].byteLength;
  82218. info.specular.mipmaps.push({
  82219. length: byteLength,
  82220. position: position
  82221. });
  82222. position += byteLength;
  82223. }
  82224. }
  82225. // Encode the JSON as an array buffer
  82226. var infoString = JSON.stringify(info);
  82227. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82228. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82229. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82230. infoView[i] = infoString.charCodeAt(i);
  82231. }
  82232. // Ends up with a null terminator for easier parsing
  82233. infoView[infoString.length] = 0x00;
  82234. // Computes the final required size and creates the storage
  82235. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82236. var finalBuffer = new ArrayBuffer(totalSize);
  82237. var finalBufferView = new Uint8Array(finalBuffer);
  82238. var dataView = new DataView(finalBuffer);
  82239. // Copy the magic bytes identifying the file in
  82240. var pos = 0;
  82241. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82242. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82243. }
  82244. // Add the json info
  82245. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82246. pos += infoBuffer.byteLength;
  82247. // Finally inserts the texture data
  82248. for (var i = 0; i <= mipmapsCount; i++) {
  82249. for (var face = 0; face < 6; face++) {
  82250. var dataBuffer = specularTextures[i * 6 + face];
  82251. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82252. pos += dataBuffer.byteLength;
  82253. }
  82254. }
  82255. // Voila
  82256. return finalBuffer;
  82257. });
  82258. };
  82259. /**
  82260. * Creates a JSON representation of the spherical data.
  82261. * @param texture defines the texture containing the polynomials
  82262. * @return the JSON representation of the spherical info
  82263. */
  82264. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82265. var polynmials = texture.sphericalPolynomial;
  82266. if (polynmials == null) {
  82267. return null;
  82268. }
  82269. return {
  82270. polynomials: true,
  82271. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82272. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82273. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82274. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82275. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82276. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82277. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82278. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82279. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82280. };
  82281. };
  82282. /**
  82283. * Uploads the texture info contained in the env file to te GPU.
  82284. * @param texture defines the internal texture to upload to
  82285. * @param arrayBuffer defines the buffer cotaining the data to load
  82286. * @param info defines the texture info retrieved through the GetEnvInfo method
  82287. * @returns a promise
  82288. */
  82289. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82290. if (info.version !== 1) {
  82291. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82292. }
  82293. var specularInfo = info.specular;
  82294. if (!specularInfo) {
  82295. // Nothing else parsed so far
  82296. return Promise.resolve();
  82297. }
  82298. // Double checks the enclosed info
  82299. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82300. mipmapsCount = Math.round(mipmapsCount) + 1;
  82301. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82302. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82303. }
  82304. // Gets everything ready.
  82305. var engine = texture.getEngine();
  82306. var expandTexture = false;
  82307. var generateNonLODTextures = false;
  82308. var rgbdPostProcess = null;
  82309. var cubeRtt = null;
  82310. var lodTextures = null;
  82311. var caps = engine.getCaps();
  82312. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82313. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82314. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82315. // Add extra process if texture lod is not supported
  82316. if (!caps.textureLOD) {
  82317. expandTexture = false;
  82318. generateNonLODTextures = true;
  82319. lodTextures = {};
  82320. }
  82321. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82322. else if (engine.webGLVersion < 2) {
  82323. expandTexture = false;
  82324. }
  82325. // If half float available we can uncompress the texture
  82326. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82327. expandTexture = true;
  82328. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82329. }
  82330. // If full float available we can uncompress the texture
  82331. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82332. expandTexture = true;
  82333. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82334. }
  82335. // Expand the texture if possible
  82336. if (expandTexture) {
  82337. // Simply run through the decode PP
  82338. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82339. texture._isRGBD = false;
  82340. texture.invertY = false;
  82341. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82342. generateDepthBuffer: false,
  82343. generateMipMaps: true,
  82344. generateStencilBuffer: false,
  82345. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82346. type: texture.type,
  82347. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82348. });
  82349. }
  82350. else {
  82351. texture._isRGBD = true;
  82352. texture.invertY = true;
  82353. // In case of missing support, applies the same patch than DDS files.
  82354. if (generateNonLODTextures) {
  82355. var mipSlices = 3;
  82356. var scale = texture._lodGenerationScale;
  82357. var offset = texture._lodGenerationOffset;
  82358. for (var i = 0; i < mipSlices; i++) {
  82359. //compute LOD from even spacing in smoothness (matching shader calculation)
  82360. var smoothness = i / (mipSlices - 1);
  82361. var roughness = 1 - smoothness;
  82362. var minLODIndex = offset; // roughness = 0
  82363. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82364. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82365. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82366. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82367. glTextureFromLod.isCube = true;
  82368. glTextureFromLod.invertY = true;
  82369. glTextureFromLod.generateMipMaps = false;
  82370. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82371. // Wrap in a base texture for easy binding.
  82372. var lodTexture = new BABYLON.BaseTexture(null);
  82373. lodTexture.isCube = true;
  82374. lodTexture._texture = glTextureFromLod;
  82375. lodTextures[mipmapIndex] = lodTexture;
  82376. switch (i) {
  82377. case 0:
  82378. texture._lodTextureLow = lodTexture;
  82379. break;
  82380. case 1:
  82381. texture._lodTextureMid = lodTexture;
  82382. break;
  82383. case 2:
  82384. texture._lodTextureHigh = lodTexture;
  82385. break;
  82386. }
  82387. }
  82388. }
  82389. }
  82390. var promises = [];
  82391. var _loop_3 = function (i) {
  82392. var _loop_4 = function (face) {
  82393. // Retrieves the face data
  82394. var imageData = specularInfo.mipmaps[i * 6 + face];
  82395. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82396. // Constructs an image element from bytes
  82397. var blob = new Blob([bytes], { type: 'image/png' });
  82398. var url = URL.createObjectURL(blob);
  82399. var image = new Image();
  82400. image.src = url;
  82401. // Enqueue promise to upload to the texture.
  82402. var promise = new Promise(function (resolve, reject) {
  82403. ;
  82404. image.onload = function () {
  82405. if (expandTexture) {
  82406. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82407. reject(message);
  82408. }, image);
  82409. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82410. // Uncompress the data to a RTT
  82411. rgbdPostProcess.onApply = function (effect) {
  82412. effect._bindTexture("textureSampler", tempTexture_1);
  82413. effect.setFloat2("scale", 1, 1);
  82414. };
  82415. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82416. // Cleanup
  82417. engine.restoreDefaultFramebuffer();
  82418. tempTexture_1.dispose();
  82419. window.URL.revokeObjectURL(url);
  82420. resolve();
  82421. });
  82422. }
  82423. else {
  82424. engine._uploadImageToTexture(texture, face, i, image);
  82425. // Upload the face to the none lod texture support
  82426. if (generateNonLODTextures) {
  82427. var lodTexture = lodTextures[i];
  82428. if (lodTexture) {
  82429. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82430. }
  82431. }
  82432. resolve();
  82433. }
  82434. };
  82435. image.onerror = function (error) {
  82436. reject(error);
  82437. };
  82438. });
  82439. promises.push(promise);
  82440. };
  82441. // All faces
  82442. for (var face = 0; face < 6; face++) {
  82443. _loop_4(face);
  82444. }
  82445. };
  82446. // All mipmaps
  82447. for (var i = 0; i < mipmapsCount; i++) {
  82448. _loop_3(i);
  82449. }
  82450. // Once all done, finishes the cleanup and return
  82451. return Promise.all(promises).then(function () {
  82452. // Relase temp RTT.
  82453. if (cubeRtt) {
  82454. engine._releaseFramebufferObjects(cubeRtt);
  82455. cubeRtt._swapAndDie(texture);
  82456. }
  82457. // Relase temp Post Process.
  82458. if (rgbdPostProcess) {
  82459. rgbdPostProcess.dispose();
  82460. }
  82461. // Flag internal texture as ready in case they are in use.
  82462. if (generateNonLODTextures) {
  82463. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82464. texture._lodTextureHigh._texture.isReady = true;
  82465. }
  82466. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82467. texture._lodTextureMid._texture.isReady = true;
  82468. }
  82469. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82470. texture._lodTextureLow._texture.isReady = true;
  82471. }
  82472. }
  82473. });
  82474. };
  82475. /**
  82476. * Uploads spherical polynomials information to the texture.
  82477. * @param texture defines the texture we are trying to upload the information to
  82478. * @param arrayBuffer defines the array buffer holding the data
  82479. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82480. */
  82481. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82482. if (info.version !== 1) {
  82483. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82484. }
  82485. var irradianceInfo = info.irradiance;
  82486. if (!irradianceInfo) {
  82487. return;
  82488. }
  82489. //harmonics now represent radiance
  82490. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82491. if (irradianceInfo.polynomials) {
  82492. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82493. }
  82494. else {
  82495. // convert From SH to SP.
  82496. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82497. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82498. }
  82499. };
  82500. /**
  82501. * Upload spherical polynomial coefficients to the texture
  82502. * @param polynmials Spherical polynmial coefficients (9)
  82503. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82504. */
  82505. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82506. outPolynomialCoefficents.x.x = polynmials.x[0];
  82507. outPolynomialCoefficents.x.y = polynmials.x[1];
  82508. outPolynomialCoefficents.x.z = polynmials.x[2];
  82509. outPolynomialCoefficents.y.x = polynmials.y[0];
  82510. outPolynomialCoefficents.y.y = polynmials.y[1];
  82511. outPolynomialCoefficents.y.z = polynmials.y[2];
  82512. outPolynomialCoefficents.z.x = polynmials.z[0];
  82513. outPolynomialCoefficents.z.y = polynmials.z[1];
  82514. outPolynomialCoefficents.z.z = polynmials.z[2];
  82515. //xx
  82516. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82517. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82518. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82519. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82520. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82521. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82522. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82523. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82524. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82525. //yz
  82526. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82527. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82528. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82529. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82530. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82531. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82532. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82533. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82534. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82535. };
  82536. /**
  82537. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82538. * L = (1/pi) * E * rho
  82539. *
  82540. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82541. * @param harmonics Spherical harmonic coefficients (9)
  82542. */
  82543. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82544. var scaleFactor = 1 / Math.PI;
  82545. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82546. // (The pixel shader must apply albedo after texture fetches, etc).
  82547. harmonics.l00[0] *= scaleFactor;
  82548. harmonics.l00[1] *= scaleFactor;
  82549. harmonics.l00[2] *= scaleFactor;
  82550. harmonics.l1_1[0] *= scaleFactor;
  82551. harmonics.l1_1[1] *= scaleFactor;
  82552. harmonics.l1_1[2] *= scaleFactor;
  82553. harmonics.l10[0] *= scaleFactor;
  82554. harmonics.l10[1] *= scaleFactor;
  82555. harmonics.l10[2] *= scaleFactor;
  82556. harmonics.l11[0] *= scaleFactor;
  82557. harmonics.l11[1] *= scaleFactor;
  82558. harmonics.l11[2] *= scaleFactor;
  82559. harmonics.l2_2[0] *= scaleFactor;
  82560. harmonics.l2_2[1] *= scaleFactor;
  82561. harmonics.l2_2[2] *= scaleFactor;
  82562. harmonics.l2_1[0] *= scaleFactor;
  82563. harmonics.l2_1[1] *= scaleFactor;
  82564. harmonics.l2_1[2] *= scaleFactor;
  82565. harmonics.l20[0] *= scaleFactor;
  82566. harmonics.l20[1] *= scaleFactor;
  82567. harmonics.l20[2] *= scaleFactor;
  82568. harmonics.l21[0] *= scaleFactor;
  82569. harmonics.l21[1] *= scaleFactor;
  82570. harmonics.l21[2] *= scaleFactor;
  82571. harmonics.l22[0] *= scaleFactor;
  82572. harmonics.l22[1] *= scaleFactor;
  82573. harmonics.l22[2] *= scaleFactor;
  82574. };
  82575. /**
  82576. * Convert spherical harmonics to spherical polynomial coefficients
  82577. * @param harmonics Spherical harmonic coefficients (9)
  82578. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82579. */
  82580. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82581. var rPi = 1 / Math.PI;
  82582. //x
  82583. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82584. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82585. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82586. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82587. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82588. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82589. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82590. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82591. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82592. //xx
  82593. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82594. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82595. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82596. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82597. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82598. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82599. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82600. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82601. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82602. //yz
  82603. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82604. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82605. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82606. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82607. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82608. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82609. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82610. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82611. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82612. };
  82613. /**
  82614. * Magic number identifying the env file.
  82615. */
  82616. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82617. return EnvironmentTextureTools;
  82618. }());
  82619. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82620. })(BABYLON || (BABYLON = {}));
  82621. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82622. var BABYLON;
  82623. (function (BABYLON) {
  82624. /**
  82625. * This represents a texture coming from an HDR input.
  82626. *
  82627. * The only supported format is currently panorama picture stored in RGBE format.
  82628. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82629. */
  82630. var HDRCubeTexture = /** @class */ (function (_super) {
  82631. __extends(HDRCubeTexture, _super);
  82632. /**
  82633. * Instantiates an HDRTexture from the following parameters.
  82634. *
  82635. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82636. * @param scene The scene the texture will be used in
  82637. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82638. * @param noMipmap Forces to not generate the mipmap if true
  82639. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82640. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  82641. * @param reserved Reserved flag for internal use.
  82642. */
  82643. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82644. if (noMipmap === void 0) { noMipmap = false; }
  82645. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82646. if (gammaSpace === void 0) { gammaSpace = false; }
  82647. if (reserved === void 0) { reserved = false; }
  82648. if (onLoad === void 0) { onLoad = null; }
  82649. if (onError === void 0) { onError = null; }
  82650. var _this = _super.call(this, scene) || this;
  82651. _this._generateHarmonics = true;
  82652. _this._onLoad = null;
  82653. _this._onError = null;
  82654. /**
  82655. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82656. */
  82657. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82658. _this._isBlocking = true;
  82659. _this._rotationY = 0;
  82660. /**
  82661. * Gets or sets the center of the bounding box associated with the cube texture
  82662. * It must define where the camera used to render the texture was set
  82663. */
  82664. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82665. if (!url) {
  82666. return _this;
  82667. }
  82668. _this.name = url;
  82669. _this.url = url;
  82670. _this.hasAlpha = false;
  82671. _this.isCube = true;
  82672. _this._textureMatrix = BABYLON.Matrix.Identity();
  82673. _this._onLoad = onLoad;
  82674. _this._onError = onError;
  82675. _this.gammaSpace = gammaSpace;
  82676. _this._noMipmap = noMipmap;
  82677. _this._size = size;
  82678. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82679. if (!_this._texture) {
  82680. if (!scene.useDelayedTextureLoading) {
  82681. _this.loadTexture();
  82682. }
  82683. else {
  82684. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82685. }
  82686. }
  82687. return _this;
  82688. }
  82689. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82690. /**
  82691. * Gets wether or not the texture is blocking during loading.
  82692. */
  82693. get: function () {
  82694. return this._isBlocking;
  82695. },
  82696. /**
  82697. * Sets wether or not the texture is blocking during loading.
  82698. */
  82699. set: function (value) {
  82700. this._isBlocking = value;
  82701. },
  82702. enumerable: true,
  82703. configurable: true
  82704. });
  82705. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82706. /**
  82707. * Gets texture matrix rotation angle around Y axis radians.
  82708. */
  82709. get: function () {
  82710. return this._rotationY;
  82711. },
  82712. /**
  82713. * Sets texture matrix rotation angle around Y axis in radians.
  82714. */
  82715. set: function (value) {
  82716. this._rotationY = value;
  82717. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82718. },
  82719. enumerable: true,
  82720. configurable: true
  82721. });
  82722. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82723. get: function () {
  82724. return this._boundingBoxSize;
  82725. },
  82726. /**
  82727. * Gets or sets the size of the bounding box associated with the cube texture
  82728. * When defined, the cubemap will switch to local mode
  82729. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82730. * @example https://www.babylonjs-playground.com/#RNASML
  82731. */
  82732. set: function (value) {
  82733. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82734. return;
  82735. }
  82736. this._boundingBoxSize = value;
  82737. var scene = this.getScene();
  82738. if (scene) {
  82739. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82740. }
  82741. },
  82742. enumerable: true,
  82743. configurable: true
  82744. });
  82745. /**
  82746. * Occurs when the file is raw .hdr file.
  82747. */
  82748. HDRCubeTexture.prototype.loadTexture = function () {
  82749. var _this = this;
  82750. var callback = function (buffer) {
  82751. _this.lodGenerationOffset = 0.0;
  82752. _this.lodGenerationScale = 0.8;
  82753. var scene = _this.getScene();
  82754. if (!scene) {
  82755. return null;
  82756. }
  82757. // Extract the raw linear data.
  82758. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82759. // Generate harmonics if needed.
  82760. if (_this._generateHarmonics) {
  82761. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82762. _this.sphericalPolynomial = sphericalPolynomial;
  82763. }
  82764. var results = [];
  82765. var byteArray = null;
  82766. // Push each faces.
  82767. for (var j = 0; j < 6; j++) {
  82768. // Create uintarray fallback.
  82769. if (!scene.getEngine().getCaps().textureFloat) {
  82770. // 3 channels of 1 bytes per pixel in bytes.
  82771. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82772. byteArray = new Uint8Array(byteBuffer);
  82773. }
  82774. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82775. // If special cases.
  82776. if (_this.gammaSpace || byteArray) {
  82777. for (var i = 0; i < _this._size * _this._size; i++) {
  82778. // Put in gamma space if requested.
  82779. if (_this.gammaSpace) {
  82780. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82781. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82782. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82783. }
  82784. // Convert to int texture for fallback.
  82785. if (byteArray) {
  82786. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82787. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82788. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82789. // May use luminance instead if the result is not accurate.
  82790. var max = Math.max(Math.max(r, g), b);
  82791. if (max > 255) {
  82792. var scale = 255 / max;
  82793. r *= scale;
  82794. g *= scale;
  82795. b *= scale;
  82796. }
  82797. byteArray[(i * 3) + 0] = r;
  82798. byteArray[(i * 3) + 1] = g;
  82799. byteArray[(i * 3) + 2] = b;
  82800. }
  82801. }
  82802. }
  82803. if (byteArray) {
  82804. results.push(byteArray);
  82805. }
  82806. else {
  82807. results.push(dataFace);
  82808. }
  82809. }
  82810. return results;
  82811. };
  82812. var scene = this.getScene();
  82813. if (scene) {
  82814. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  82815. }
  82816. };
  82817. HDRCubeTexture.prototype.clone = function () {
  82818. var scene = this.getScene();
  82819. if (!scene) {
  82820. return this;
  82821. }
  82822. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82823. // Base texture
  82824. newTexture.level = this.level;
  82825. newTexture.wrapU = this.wrapU;
  82826. newTexture.wrapV = this.wrapV;
  82827. newTexture.coordinatesIndex = this.coordinatesIndex;
  82828. newTexture.coordinatesMode = this.coordinatesMode;
  82829. return newTexture;
  82830. };
  82831. // Methods
  82832. HDRCubeTexture.prototype.delayLoad = function () {
  82833. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82834. return;
  82835. }
  82836. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82837. this._texture = this._getFromCache(this.url, this._noMipmap);
  82838. if (!this._texture) {
  82839. this.loadTexture();
  82840. }
  82841. };
  82842. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82843. return this._textureMatrix;
  82844. };
  82845. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82846. this._textureMatrix = value;
  82847. };
  82848. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82849. var texture = null;
  82850. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82851. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82852. texture.name = parsedTexture.name;
  82853. texture.hasAlpha = parsedTexture.hasAlpha;
  82854. texture.level = parsedTexture.level;
  82855. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82856. texture.isBlocking = parsedTexture.isBlocking;
  82857. }
  82858. if (texture) {
  82859. if (parsedTexture.boundingBoxPosition) {
  82860. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82861. }
  82862. if (parsedTexture.boundingBoxSize) {
  82863. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82864. }
  82865. if (parsedTexture.rotationY) {
  82866. texture.rotationY = parsedTexture.rotationY;
  82867. }
  82868. }
  82869. return texture;
  82870. };
  82871. HDRCubeTexture.prototype.serialize = function () {
  82872. if (!this.name) {
  82873. return null;
  82874. }
  82875. var serializationObject = {};
  82876. serializationObject.name = this.name;
  82877. serializationObject.hasAlpha = this.hasAlpha;
  82878. serializationObject.isCube = true;
  82879. serializationObject.level = this.level;
  82880. serializationObject.size = this._size;
  82881. serializationObject.coordinatesMode = this.coordinatesMode;
  82882. serializationObject.useInGammaSpace = this.gammaSpace;
  82883. serializationObject.generateHarmonics = this._generateHarmonics;
  82884. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82885. serializationObject.noMipmap = this._noMipmap;
  82886. serializationObject.isBlocking = this._isBlocking;
  82887. serializationObject.rotationY = this._rotationY;
  82888. return serializationObject;
  82889. };
  82890. HDRCubeTexture._facesMapping = [
  82891. "right",
  82892. "left",
  82893. "up",
  82894. "down",
  82895. "front",
  82896. "back"
  82897. ];
  82898. return HDRCubeTexture;
  82899. }(BABYLON.BaseTexture));
  82900. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82901. })(BABYLON || (BABYLON = {}));
  82902. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82903. var BABYLON;
  82904. (function (BABYLON) {
  82905. var IndexedVector2 = /** @class */ (function (_super) {
  82906. __extends(IndexedVector2, _super);
  82907. function IndexedVector2(original, index) {
  82908. var _this = _super.call(this, original.x, original.y) || this;
  82909. _this.index = index;
  82910. return _this;
  82911. }
  82912. return IndexedVector2;
  82913. }(BABYLON.Vector2));
  82914. var PolygonPoints = /** @class */ (function () {
  82915. function PolygonPoints() {
  82916. this.elements = new Array();
  82917. }
  82918. PolygonPoints.prototype.add = function (originalPoints) {
  82919. var _this = this;
  82920. var result = new Array();
  82921. originalPoints.forEach(function (point) {
  82922. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82923. var newPoint = new IndexedVector2(point, _this.elements.length);
  82924. result.push(newPoint);
  82925. _this.elements.push(newPoint);
  82926. }
  82927. });
  82928. return result;
  82929. };
  82930. PolygonPoints.prototype.computeBounds = function () {
  82931. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82932. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82933. this.elements.forEach(function (point) {
  82934. // x
  82935. if (point.x < lmin.x) {
  82936. lmin.x = point.x;
  82937. }
  82938. else if (point.x > lmax.x) {
  82939. lmax.x = point.x;
  82940. }
  82941. // y
  82942. if (point.y < lmin.y) {
  82943. lmin.y = point.y;
  82944. }
  82945. else if (point.y > lmax.y) {
  82946. lmax.y = point.y;
  82947. }
  82948. });
  82949. return {
  82950. min: lmin,
  82951. max: lmax,
  82952. width: lmax.x - lmin.x,
  82953. height: lmax.y - lmin.y
  82954. };
  82955. };
  82956. return PolygonPoints;
  82957. }());
  82958. var Polygon = /** @class */ (function () {
  82959. function Polygon() {
  82960. }
  82961. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82962. return [
  82963. new BABYLON.Vector2(xmin, ymin),
  82964. new BABYLON.Vector2(xmax, ymin),
  82965. new BABYLON.Vector2(xmax, ymax),
  82966. new BABYLON.Vector2(xmin, ymax)
  82967. ];
  82968. };
  82969. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82970. if (cx === void 0) { cx = 0; }
  82971. if (cy === void 0) { cy = 0; }
  82972. if (numberOfSides === void 0) { numberOfSides = 32; }
  82973. var result = new Array();
  82974. var angle = 0;
  82975. var increment = (Math.PI * 2) / numberOfSides;
  82976. for (var i = 0; i < numberOfSides; i++) {
  82977. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82978. angle -= increment;
  82979. }
  82980. return result;
  82981. };
  82982. Polygon.Parse = function (input) {
  82983. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82984. var i, result = [];
  82985. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82986. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82987. }
  82988. return result;
  82989. };
  82990. Polygon.StartingAt = function (x, y) {
  82991. return BABYLON.Path2.StartingAt(x, y);
  82992. };
  82993. return Polygon;
  82994. }());
  82995. BABYLON.Polygon = Polygon;
  82996. var PolygonMeshBuilder = /** @class */ (function () {
  82997. function PolygonMeshBuilder(name, contours, scene) {
  82998. this._points = new PolygonPoints();
  82999. this._outlinepoints = new PolygonPoints();
  83000. this._holes = new Array();
  83001. this._epoints = new Array();
  83002. this._eholes = new Array();
  83003. this._name = name;
  83004. this._scene = scene;
  83005. var points;
  83006. if (contours instanceof BABYLON.Path2) {
  83007. points = contours.getPoints();
  83008. }
  83009. else {
  83010. points = contours;
  83011. }
  83012. this._addToepoint(points);
  83013. this._points.add(points);
  83014. this._outlinepoints.add(points);
  83015. if (typeof earcut === 'undefined') {
  83016. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83017. }
  83018. }
  83019. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83020. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83021. var p = points_1[_i];
  83022. this._epoints.push(p.x, p.y);
  83023. }
  83024. };
  83025. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83026. this._points.add(hole);
  83027. var holepoints = new PolygonPoints();
  83028. holepoints.add(hole);
  83029. this._holes.push(holepoints);
  83030. this._eholes.push(this._epoints.length / 2);
  83031. this._addToepoint(hole);
  83032. return this;
  83033. };
  83034. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83035. var _this = this;
  83036. if (updatable === void 0) { updatable = false; }
  83037. if (depth === void 0) { depth = 0; }
  83038. var result = new BABYLON.Mesh(this._name, this._scene);
  83039. var normals = new Array();
  83040. var positions = new Array();
  83041. var uvs = new Array();
  83042. var bounds = this._points.computeBounds();
  83043. this._points.elements.forEach(function (p) {
  83044. normals.push(0, 1.0, 0);
  83045. positions.push(p.x, 0, p.y);
  83046. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83047. });
  83048. var indices = new Array();
  83049. var res = earcut(this._epoints, this._eholes, 2);
  83050. for (var i = 0; i < res.length; i++) {
  83051. indices.push(res[i]);
  83052. }
  83053. if (depth > 0) {
  83054. var positionscount = (positions.length / 3); //get the current pointcount
  83055. this._points.elements.forEach(function (p) {
  83056. normals.push(0, -1.0, 0);
  83057. positions.push(p.x, -depth, p.y);
  83058. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83059. });
  83060. var totalCount = indices.length;
  83061. for (var i = 0; i < totalCount; i += 3) {
  83062. var i0 = indices[i + 0];
  83063. var i1 = indices[i + 1];
  83064. var i2 = indices[i + 2];
  83065. indices.push(i2 + positionscount);
  83066. indices.push(i1 + positionscount);
  83067. indices.push(i0 + positionscount);
  83068. }
  83069. //Add the sides
  83070. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83071. this._holes.forEach(function (hole) {
  83072. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83073. });
  83074. }
  83075. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83076. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83077. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83078. result.setIndices(indices);
  83079. return result;
  83080. };
  83081. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83082. var StartIndex = positions.length / 3;
  83083. var ulength = 0;
  83084. for (var i = 0; i < points.elements.length; i++) {
  83085. var p = points.elements[i];
  83086. var p1;
  83087. if ((i + 1) > points.elements.length - 1) {
  83088. p1 = points.elements[0];
  83089. }
  83090. else {
  83091. p1 = points.elements[i + 1];
  83092. }
  83093. positions.push(p.x, 0, p.y);
  83094. positions.push(p.x, -depth, p.y);
  83095. positions.push(p1.x, 0, p1.y);
  83096. positions.push(p1.x, -depth, p1.y);
  83097. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83098. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83099. var v3 = v2.subtract(v1);
  83100. var v4 = new BABYLON.Vector3(0, 1, 0);
  83101. var vn = BABYLON.Vector3.Cross(v3, v4);
  83102. vn = vn.normalize();
  83103. uvs.push(ulength / bounds.width, 0);
  83104. uvs.push(ulength / bounds.width, 1);
  83105. ulength += v3.length();
  83106. uvs.push((ulength / bounds.width), 0);
  83107. uvs.push((ulength / bounds.width), 1);
  83108. if (!flip) {
  83109. normals.push(-vn.x, -vn.y, -vn.z);
  83110. normals.push(-vn.x, -vn.y, -vn.z);
  83111. normals.push(-vn.x, -vn.y, -vn.z);
  83112. normals.push(-vn.x, -vn.y, -vn.z);
  83113. indices.push(StartIndex);
  83114. indices.push(StartIndex + 1);
  83115. indices.push(StartIndex + 2);
  83116. indices.push(StartIndex + 1);
  83117. indices.push(StartIndex + 3);
  83118. indices.push(StartIndex + 2);
  83119. }
  83120. else {
  83121. normals.push(vn.x, vn.y, vn.z);
  83122. normals.push(vn.x, vn.y, vn.z);
  83123. normals.push(vn.x, vn.y, vn.z);
  83124. normals.push(vn.x, vn.y, vn.z);
  83125. indices.push(StartIndex);
  83126. indices.push(StartIndex + 2);
  83127. indices.push(StartIndex + 1);
  83128. indices.push(StartIndex + 1);
  83129. indices.push(StartIndex + 2);
  83130. indices.push(StartIndex + 3);
  83131. }
  83132. StartIndex += 4;
  83133. }
  83134. ;
  83135. };
  83136. return PolygonMeshBuilder;
  83137. }());
  83138. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83139. })(BABYLON || (BABYLON = {}));
  83140. //# sourceMappingURL=babylon.polygonMesh.js.map
  83141. var BABYLON;
  83142. (function (BABYLON) {
  83143. // Unique ID when we import meshes from Babylon to CSG
  83144. var currentCSGMeshId = 0;
  83145. // # class Vertex
  83146. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83147. // one to provide additional features like texture coordinates and vertex
  83148. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83149. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83150. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83151. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83152. // is not used anywhere else.
  83153. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83154. var Vertex = /** @class */ (function () {
  83155. function Vertex(pos, normal, uv) {
  83156. this.pos = pos;
  83157. this.normal = normal;
  83158. this.uv = uv;
  83159. }
  83160. Vertex.prototype.clone = function () {
  83161. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83162. };
  83163. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83164. // orientation of a polygon is flipped.
  83165. Vertex.prototype.flip = function () {
  83166. this.normal = this.normal.scale(-1);
  83167. };
  83168. // Create a new vertex between this vertex and `other` by linearly
  83169. // interpolating all properties using a parameter of `t`. Subclasses should
  83170. // override this to interpolate additional properties.
  83171. Vertex.prototype.interpolate = function (other, t) {
  83172. 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));
  83173. };
  83174. return Vertex;
  83175. }());
  83176. // # class Plane
  83177. // Represents a plane in 3D space.
  83178. var Plane = /** @class */ (function () {
  83179. function Plane(normal, w) {
  83180. this.normal = normal;
  83181. this.w = w;
  83182. }
  83183. Plane.FromPoints = function (a, b, c) {
  83184. var v0 = c.subtract(a);
  83185. var v1 = b.subtract(a);
  83186. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83187. return null;
  83188. }
  83189. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83190. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83191. };
  83192. Plane.prototype.clone = function () {
  83193. return new Plane(this.normal.clone(), this.w);
  83194. };
  83195. Plane.prototype.flip = function () {
  83196. this.normal.scaleInPlace(-1);
  83197. this.w = -this.w;
  83198. };
  83199. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83200. // fragments in the appropriate lists. Coplanar polygons go into either
  83201. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83202. // respect to this plane. Polygons in front or in back of this plane go into
  83203. // either `front` or `back`.
  83204. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83205. var COPLANAR = 0;
  83206. var FRONT = 1;
  83207. var BACK = 2;
  83208. var SPANNING = 3;
  83209. // Classify each point as well as the entire polygon into one of the above
  83210. // four classes.
  83211. var polygonType = 0;
  83212. var types = [];
  83213. var i;
  83214. var t;
  83215. for (i = 0; i < polygon.vertices.length; i++) {
  83216. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83217. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83218. polygonType |= type;
  83219. types.push(type);
  83220. }
  83221. // Put the polygon in the correct list, splitting it when necessary.
  83222. switch (polygonType) {
  83223. case COPLANAR:
  83224. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83225. break;
  83226. case FRONT:
  83227. front.push(polygon);
  83228. break;
  83229. case BACK:
  83230. back.push(polygon);
  83231. break;
  83232. case SPANNING:
  83233. var f = [], b = [];
  83234. for (i = 0; i < polygon.vertices.length; i++) {
  83235. var j = (i + 1) % polygon.vertices.length;
  83236. var ti = types[i], tj = types[j];
  83237. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83238. if (ti !== BACK)
  83239. f.push(vi);
  83240. if (ti !== FRONT)
  83241. b.push(ti !== BACK ? vi.clone() : vi);
  83242. if ((ti | tj) === SPANNING) {
  83243. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83244. var v = vi.interpolate(vj, t);
  83245. f.push(v);
  83246. b.push(v.clone());
  83247. }
  83248. }
  83249. var poly;
  83250. if (f.length >= 3) {
  83251. poly = new Polygon(f, polygon.shared);
  83252. if (poly.plane)
  83253. front.push(poly);
  83254. }
  83255. if (b.length >= 3) {
  83256. poly = new Polygon(b, polygon.shared);
  83257. if (poly.plane)
  83258. back.push(poly);
  83259. }
  83260. break;
  83261. }
  83262. };
  83263. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83264. // point is on the plane.
  83265. Plane.EPSILON = 1e-5;
  83266. return Plane;
  83267. }());
  83268. // # class Polygon
  83269. // Represents a convex polygon. The vertices used to initialize a polygon must
  83270. // be coplanar and form a convex loop.
  83271. //
  83272. // Each convex polygon has a `shared` property, which is shared between all
  83273. // polygons that are clones of each other or were split from the same polygon.
  83274. // This can be used to define per-polygon properties (such as surface color).
  83275. var Polygon = /** @class */ (function () {
  83276. function Polygon(vertices, shared) {
  83277. this.vertices = vertices;
  83278. this.shared = shared;
  83279. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83280. }
  83281. Polygon.prototype.clone = function () {
  83282. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83283. return new Polygon(vertices, this.shared);
  83284. };
  83285. Polygon.prototype.flip = function () {
  83286. this.vertices.reverse().map(function (v) { v.flip(); });
  83287. this.plane.flip();
  83288. };
  83289. return Polygon;
  83290. }());
  83291. // # class Node
  83292. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83293. // by picking a polygon to split along. That polygon (and all other coplanar
  83294. // polygons) are added directly to that node and the other polygons are added to
  83295. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83296. // no distinction between internal and leaf nodes.
  83297. var Node = /** @class */ (function () {
  83298. function Node(polygons) {
  83299. this.plane = null;
  83300. this.front = null;
  83301. this.back = null;
  83302. this.polygons = new Array();
  83303. if (polygons) {
  83304. this.build(polygons);
  83305. }
  83306. }
  83307. Node.prototype.clone = function () {
  83308. var node = new Node();
  83309. node.plane = this.plane && this.plane.clone();
  83310. node.front = this.front && this.front.clone();
  83311. node.back = this.back && this.back.clone();
  83312. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83313. return node;
  83314. };
  83315. // Convert solid space to empty space and empty space to solid space.
  83316. Node.prototype.invert = function () {
  83317. for (var i = 0; i < this.polygons.length; i++) {
  83318. this.polygons[i].flip();
  83319. }
  83320. if (this.plane) {
  83321. this.plane.flip();
  83322. }
  83323. if (this.front) {
  83324. this.front.invert();
  83325. }
  83326. if (this.back) {
  83327. this.back.invert();
  83328. }
  83329. var temp = this.front;
  83330. this.front = this.back;
  83331. this.back = temp;
  83332. };
  83333. // Recursively remove all polygons in `polygons` that are inside this BSP
  83334. // tree.
  83335. Node.prototype.clipPolygons = function (polygons) {
  83336. if (!this.plane)
  83337. return polygons.slice();
  83338. var front = new Array(), back = new Array();
  83339. for (var i = 0; i < polygons.length; i++) {
  83340. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83341. }
  83342. if (this.front) {
  83343. front = this.front.clipPolygons(front);
  83344. }
  83345. if (this.back) {
  83346. back = this.back.clipPolygons(back);
  83347. }
  83348. else {
  83349. back = [];
  83350. }
  83351. return front.concat(back);
  83352. };
  83353. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83354. // `bsp`.
  83355. Node.prototype.clipTo = function (bsp) {
  83356. this.polygons = bsp.clipPolygons(this.polygons);
  83357. if (this.front)
  83358. this.front.clipTo(bsp);
  83359. if (this.back)
  83360. this.back.clipTo(bsp);
  83361. };
  83362. // Return a list of all polygons in this BSP tree.
  83363. Node.prototype.allPolygons = function () {
  83364. var polygons = this.polygons.slice();
  83365. if (this.front)
  83366. polygons = polygons.concat(this.front.allPolygons());
  83367. if (this.back)
  83368. polygons = polygons.concat(this.back.allPolygons());
  83369. return polygons;
  83370. };
  83371. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83372. // new polygons are filtered down to the bottom of the tree and become new
  83373. // nodes there. Each set of polygons is partitioned using the first polygon
  83374. // (no heuristic is used to pick a good split).
  83375. Node.prototype.build = function (polygons) {
  83376. if (!polygons.length)
  83377. return;
  83378. if (!this.plane)
  83379. this.plane = polygons[0].plane.clone();
  83380. var front = new Array(), back = new Array();
  83381. for (var i = 0; i < polygons.length; i++) {
  83382. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83383. }
  83384. if (front.length) {
  83385. if (!this.front)
  83386. this.front = new Node();
  83387. this.front.build(front);
  83388. }
  83389. if (back.length) {
  83390. if (!this.back)
  83391. this.back = new Node();
  83392. this.back.build(back);
  83393. }
  83394. };
  83395. return Node;
  83396. }());
  83397. var CSG = /** @class */ (function () {
  83398. function CSG() {
  83399. this.polygons = new Array();
  83400. }
  83401. // Convert BABYLON.Mesh to BABYLON.CSG
  83402. CSG.FromMesh = function (mesh) {
  83403. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83404. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83405. if (mesh instanceof BABYLON.Mesh) {
  83406. mesh.computeWorldMatrix(true);
  83407. matrix = mesh.getWorldMatrix();
  83408. meshPosition = mesh.position.clone();
  83409. meshRotation = mesh.rotation.clone();
  83410. if (mesh.rotationQuaternion) {
  83411. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83412. }
  83413. meshScaling = mesh.scaling.clone();
  83414. }
  83415. else {
  83416. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83417. }
  83418. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83419. var subMeshes = mesh.subMeshes;
  83420. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83421. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83422. vertices = [];
  83423. for (var j = 0; j < 3; j++) {
  83424. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83425. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83426. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83427. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83428. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83429. vertex = new Vertex(position, normal, uv);
  83430. vertices.push(vertex);
  83431. }
  83432. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83433. // To handle the case of degenerated triangle
  83434. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83435. if (polygon.plane)
  83436. polygons.push(polygon);
  83437. }
  83438. }
  83439. var csg = CSG.FromPolygons(polygons);
  83440. csg.matrix = matrix;
  83441. csg.position = meshPosition;
  83442. csg.rotation = meshRotation;
  83443. csg.scaling = meshScaling;
  83444. csg.rotationQuaternion = meshRotationQuaternion;
  83445. currentCSGMeshId++;
  83446. return csg;
  83447. };
  83448. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83449. CSG.FromPolygons = function (polygons) {
  83450. var csg = new CSG();
  83451. csg.polygons = polygons;
  83452. return csg;
  83453. };
  83454. CSG.prototype.clone = function () {
  83455. var csg = new CSG();
  83456. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83457. csg.copyTransformAttributes(this);
  83458. return csg;
  83459. };
  83460. CSG.prototype.union = function (csg) {
  83461. var a = new Node(this.clone().polygons);
  83462. var b = new Node(csg.clone().polygons);
  83463. a.clipTo(b);
  83464. b.clipTo(a);
  83465. b.invert();
  83466. b.clipTo(a);
  83467. b.invert();
  83468. a.build(b.allPolygons());
  83469. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83470. };
  83471. CSG.prototype.unionInPlace = function (csg) {
  83472. var a = new Node(this.polygons);
  83473. var b = new Node(csg.polygons);
  83474. a.clipTo(b);
  83475. b.clipTo(a);
  83476. b.invert();
  83477. b.clipTo(a);
  83478. b.invert();
  83479. a.build(b.allPolygons());
  83480. this.polygons = a.allPolygons();
  83481. };
  83482. CSG.prototype.subtract = function (csg) {
  83483. var a = new Node(this.clone().polygons);
  83484. var b = new Node(csg.clone().polygons);
  83485. a.invert();
  83486. a.clipTo(b);
  83487. b.clipTo(a);
  83488. b.invert();
  83489. b.clipTo(a);
  83490. b.invert();
  83491. a.build(b.allPolygons());
  83492. a.invert();
  83493. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83494. };
  83495. CSG.prototype.subtractInPlace = function (csg) {
  83496. var a = new Node(this.polygons);
  83497. var b = new Node(csg.polygons);
  83498. a.invert();
  83499. a.clipTo(b);
  83500. b.clipTo(a);
  83501. b.invert();
  83502. b.clipTo(a);
  83503. b.invert();
  83504. a.build(b.allPolygons());
  83505. a.invert();
  83506. this.polygons = a.allPolygons();
  83507. };
  83508. CSG.prototype.intersect = function (csg) {
  83509. var a = new Node(this.clone().polygons);
  83510. var b = new Node(csg.clone().polygons);
  83511. a.invert();
  83512. b.clipTo(a);
  83513. b.invert();
  83514. a.clipTo(b);
  83515. b.clipTo(a);
  83516. a.build(b.allPolygons());
  83517. a.invert();
  83518. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83519. };
  83520. CSG.prototype.intersectInPlace = function (csg) {
  83521. var a = new Node(this.polygons);
  83522. var b = new Node(csg.polygons);
  83523. a.invert();
  83524. b.clipTo(a);
  83525. b.invert();
  83526. a.clipTo(b);
  83527. b.clipTo(a);
  83528. a.build(b.allPolygons());
  83529. a.invert();
  83530. this.polygons = a.allPolygons();
  83531. };
  83532. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83533. // not modified.
  83534. CSG.prototype.inverse = function () {
  83535. var csg = this.clone();
  83536. csg.inverseInPlace();
  83537. return csg;
  83538. };
  83539. CSG.prototype.inverseInPlace = function () {
  83540. this.polygons.map(function (p) { p.flip(); });
  83541. };
  83542. // This is used to keep meshes transformations so they can be restored
  83543. // when we build back a Babylon Mesh
  83544. // NB : All CSG operations are performed in world coordinates
  83545. CSG.prototype.copyTransformAttributes = function (csg) {
  83546. this.matrix = csg.matrix;
  83547. this.position = csg.position;
  83548. this.rotation = csg.rotation;
  83549. this.scaling = csg.scaling;
  83550. this.rotationQuaternion = csg.rotationQuaternion;
  83551. return this;
  83552. };
  83553. // Build Raw mesh from CSG
  83554. // Coordinates here are in world space
  83555. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83556. var matrix = this.matrix.clone();
  83557. matrix.invert();
  83558. 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;
  83559. if (keepSubMeshes) {
  83560. // Sort Polygons, since subMeshes are indices range
  83561. polygons.sort(function (a, b) {
  83562. if (a.shared.meshId === b.shared.meshId) {
  83563. return a.shared.subMeshId - b.shared.subMeshId;
  83564. }
  83565. else {
  83566. return a.shared.meshId - b.shared.meshId;
  83567. }
  83568. });
  83569. }
  83570. for (var i = 0, il = polygons.length; i < il; i++) {
  83571. polygon = polygons[i];
  83572. // Building SubMeshes
  83573. if (!subMesh_dict[polygon.shared.meshId]) {
  83574. subMesh_dict[polygon.shared.meshId] = {};
  83575. }
  83576. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83577. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83578. indexStart: +Infinity,
  83579. indexEnd: -Infinity,
  83580. materialIndex: polygon.shared.materialIndex
  83581. };
  83582. }
  83583. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83584. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83585. polygonIndices[0] = 0;
  83586. polygonIndices[1] = j - 1;
  83587. polygonIndices[2] = j;
  83588. for (var k = 0; k < 3; k++) {
  83589. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83590. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83591. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83592. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83593. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83594. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83595. // Check if 2 points can be merged
  83596. if (!(typeof vertex_idx !== 'undefined' &&
  83597. normals[vertex_idx * 3] === localNormal.x &&
  83598. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83599. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83600. uvs[vertex_idx * 2] === uv.x &&
  83601. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83602. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83603. uvs.push(uv.x, uv.y);
  83604. normals.push(normal.x, normal.y, normal.z);
  83605. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83606. }
  83607. indices.push(vertex_idx);
  83608. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83609. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83610. currentIndex++;
  83611. }
  83612. }
  83613. }
  83614. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83615. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83616. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83617. mesh.setIndices(indices, null);
  83618. if (keepSubMeshes) {
  83619. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83620. var materialIndexOffset = 0, materialMaxIndex;
  83621. mesh.subMeshes = new Array();
  83622. for (var m in subMesh_dict) {
  83623. materialMaxIndex = -1;
  83624. for (var sm in subMesh_dict[m]) {
  83625. subMesh_obj = subMesh_dict[m][sm];
  83626. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83627. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83628. }
  83629. materialIndexOffset += ++materialMaxIndex;
  83630. }
  83631. }
  83632. return mesh;
  83633. };
  83634. // Build Mesh from CSG taking material and transforms into account
  83635. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83636. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83637. mesh.material = material;
  83638. mesh.position.copyFrom(this.position);
  83639. mesh.rotation.copyFrom(this.rotation);
  83640. if (this.rotationQuaternion) {
  83641. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83642. }
  83643. mesh.scaling.copyFrom(this.scaling);
  83644. mesh.computeWorldMatrix(true);
  83645. return mesh;
  83646. };
  83647. return CSG;
  83648. }());
  83649. BABYLON.CSG = CSG;
  83650. })(BABYLON || (BABYLON = {}));
  83651. //# sourceMappingURL=babylon.csg.js.map
  83652. var BABYLON;
  83653. (function (BABYLON) {
  83654. var LensFlare = /** @class */ (function () {
  83655. function LensFlare(size, position, color, imgUrl, system) {
  83656. this.size = size;
  83657. this.position = position;
  83658. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83659. this.color = color || new BABYLON.Color3(1, 1, 1);
  83660. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83661. this._system = system;
  83662. system.lensFlares.push(this);
  83663. }
  83664. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83665. return new LensFlare(size, position, color, imgUrl, system);
  83666. };
  83667. LensFlare.prototype.dispose = function () {
  83668. if (this.texture) {
  83669. this.texture.dispose();
  83670. }
  83671. // Remove from scene
  83672. var index = this._system.lensFlares.indexOf(this);
  83673. this._system.lensFlares.splice(index, 1);
  83674. };
  83675. ;
  83676. return LensFlare;
  83677. }());
  83678. BABYLON.LensFlare = LensFlare;
  83679. })(BABYLON || (BABYLON = {}));
  83680. //# sourceMappingURL=babylon.lensFlare.js.map
  83681. var BABYLON;
  83682. (function (BABYLON) {
  83683. var LensFlareSystem = /** @class */ (function () {
  83684. function LensFlareSystem(name, emitter, scene) {
  83685. this.name = name;
  83686. this.lensFlares = new Array();
  83687. this.borderLimit = 300;
  83688. this.viewportBorder = 0;
  83689. this.layerMask = 0x0FFFFFFF;
  83690. this._vertexBuffers = {};
  83691. this._isEnabled = true;
  83692. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83693. this._emitter = emitter;
  83694. this.id = name;
  83695. scene.lensFlareSystems.push(this);
  83696. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83697. var engine = scene.getEngine();
  83698. // VBO
  83699. var vertices = [];
  83700. vertices.push(1, 1);
  83701. vertices.push(-1, 1);
  83702. vertices.push(-1, -1);
  83703. vertices.push(1, -1);
  83704. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83705. // Indices
  83706. var indices = [];
  83707. indices.push(0);
  83708. indices.push(1);
  83709. indices.push(2);
  83710. indices.push(0);
  83711. indices.push(2);
  83712. indices.push(3);
  83713. this._indexBuffer = engine.createIndexBuffer(indices);
  83714. // Effects
  83715. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83716. }
  83717. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83718. get: function () {
  83719. return this._isEnabled;
  83720. },
  83721. set: function (value) {
  83722. this._isEnabled = value;
  83723. },
  83724. enumerable: true,
  83725. configurable: true
  83726. });
  83727. LensFlareSystem.prototype.getScene = function () {
  83728. return this._scene;
  83729. };
  83730. LensFlareSystem.prototype.getEmitter = function () {
  83731. return this._emitter;
  83732. };
  83733. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83734. this._emitter = newEmitter;
  83735. };
  83736. LensFlareSystem.prototype.getEmitterPosition = function () {
  83737. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83738. };
  83739. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83740. var position = this.getEmitterPosition();
  83741. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83742. this._positionX = position.x;
  83743. this._positionY = position.y;
  83744. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83745. if (this.viewportBorder > 0) {
  83746. globalViewport.x -= this.viewportBorder;
  83747. globalViewport.y -= this.viewportBorder;
  83748. globalViewport.width += this.viewportBorder * 2;
  83749. globalViewport.height += this.viewportBorder * 2;
  83750. position.x += this.viewportBorder;
  83751. position.y += this.viewportBorder;
  83752. this._positionX += this.viewportBorder;
  83753. this._positionY += this.viewportBorder;
  83754. }
  83755. if (position.z > 0) {
  83756. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83757. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83758. return true;
  83759. }
  83760. return true;
  83761. }
  83762. return false;
  83763. };
  83764. LensFlareSystem.prototype._isVisible = function () {
  83765. if (!this._isEnabled || !this._scene.activeCamera) {
  83766. return false;
  83767. }
  83768. var emitterPosition = this.getEmitterPosition();
  83769. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83770. var distance = direction.length();
  83771. direction.normalize();
  83772. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83773. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83774. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83775. };
  83776. LensFlareSystem.prototype.render = function () {
  83777. if (!this._effect.isReady() || !this._scene.activeCamera)
  83778. return false;
  83779. var engine = this._scene.getEngine();
  83780. var viewport = this._scene.activeCamera.viewport;
  83781. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83782. // Position
  83783. if (!this.computeEffectivePosition(globalViewport)) {
  83784. return false;
  83785. }
  83786. // Visibility
  83787. if (!this._isVisible()) {
  83788. return false;
  83789. }
  83790. // Intensity
  83791. var awayX;
  83792. var awayY;
  83793. if (this._positionX < this.borderLimit + globalViewport.x) {
  83794. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83795. }
  83796. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83797. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83798. }
  83799. else {
  83800. awayX = 0;
  83801. }
  83802. if (this._positionY < this.borderLimit + globalViewport.y) {
  83803. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83804. }
  83805. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83806. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83807. }
  83808. else {
  83809. awayY = 0;
  83810. }
  83811. var away = (awayX > awayY) ? awayX : awayY;
  83812. away -= this.viewportBorder;
  83813. if (away > this.borderLimit) {
  83814. away = this.borderLimit;
  83815. }
  83816. var intensity = 1.0 - (away / this.borderLimit);
  83817. if (intensity < 0) {
  83818. return false;
  83819. }
  83820. if (intensity > 1.0) {
  83821. intensity = 1.0;
  83822. }
  83823. if (this.viewportBorder > 0) {
  83824. globalViewport.x += this.viewportBorder;
  83825. globalViewport.y += this.viewportBorder;
  83826. globalViewport.width -= this.viewportBorder * 2;
  83827. globalViewport.height -= this.viewportBorder * 2;
  83828. this._positionX -= this.viewportBorder;
  83829. this._positionY -= this.viewportBorder;
  83830. }
  83831. // Position
  83832. var centerX = globalViewport.x + globalViewport.width / 2;
  83833. var centerY = globalViewport.y + globalViewport.height / 2;
  83834. var distX = centerX - this._positionX;
  83835. var distY = centerY - this._positionY;
  83836. // Effects
  83837. engine.enableEffect(this._effect);
  83838. engine.setState(false);
  83839. engine.setDepthBuffer(false);
  83840. // VBOs
  83841. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83842. // Flares
  83843. for (var index = 0; index < this.lensFlares.length; index++) {
  83844. var flare = this.lensFlares[index];
  83845. engine.setAlphaMode(flare.alphaMode);
  83846. var x = centerX - (distX * flare.position);
  83847. var y = centerY - (distY * flare.position);
  83848. var cw = flare.size;
  83849. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83850. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83851. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83852. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83853. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83854. // Texture
  83855. this._effect.setTexture("textureSampler", flare.texture);
  83856. // Color
  83857. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83858. // Draw order
  83859. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83860. }
  83861. engine.setDepthBuffer(true);
  83862. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83863. return true;
  83864. };
  83865. LensFlareSystem.prototype.dispose = function () {
  83866. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83867. if (vertexBuffer) {
  83868. vertexBuffer.dispose();
  83869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83870. }
  83871. if (this._indexBuffer) {
  83872. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83873. this._indexBuffer = null;
  83874. }
  83875. while (this.lensFlares.length) {
  83876. this.lensFlares[0].dispose();
  83877. }
  83878. // Remove from scene
  83879. var index = this._scene.lensFlareSystems.indexOf(this);
  83880. this._scene.lensFlareSystems.splice(index, 1);
  83881. };
  83882. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83883. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83884. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83885. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83886. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83887. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83888. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83889. var parsedFlare = parsedLensFlareSystem.flares[index];
  83890. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83891. }
  83892. return lensFlareSystem;
  83893. };
  83894. LensFlareSystem.prototype.serialize = function () {
  83895. var serializationObject = {};
  83896. serializationObject.id = this.id;
  83897. serializationObject.name = this.name;
  83898. serializationObject.emitterId = this.getEmitter().id;
  83899. serializationObject.borderLimit = this.borderLimit;
  83900. serializationObject.flares = [];
  83901. for (var index = 0; index < this.lensFlares.length; index++) {
  83902. var flare = this.lensFlares[index];
  83903. serializationObject.flares.push({
  83904. size: flare.size,
  83905. position: flare.position,
  83906. color: flare.color.asArray(),
  83907. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83908. });
  83909. }
  83910. return serializationObject;
  83911. };
  83912. return LensFlareSystem;
  83913. }());
  83914. BABYLON.LensFlareSystem = LensFlareSystem;
  83915. })(BABYLON || (BABYLON = {}));
  83916. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83917. var BABYLON;
  83918. (function (BABYLON) {
  83919. /**
  83920. * This is a holder class for the physics joint created by the physics plugin.
  83921. * It holds a set of functions to control the underlying joint.
  83922. */
  83923. var PhysicsJoint = /** @class */ (function () {
  83924. function PhysicsJoint(type, jointData) {
  83925. this.type = type;
  83926. this.jointData = jointData;
  83927. jointData.nativeParams = jointData.nativeParams || {};
  83928. }
  83929. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83930. get: function () {
  83931. return this._physicsJoint;
  83932. },
  83933. set: function (newJoint) {
  83934. if (this._physicsJoint) {
  83935. //remove from the wolrd
  83936. }
  83937. this._physicsJoint = newJoint;
  83938. },
  83939. enumerable: true,
  83940. configurable: true
  83941. });
  83942. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83943. set: function (physicsPlugin) {
  83944. this._physicsPlugin = physicsPlugin;
  83945. },
  83946. enumerable: true,
  83947. configurable: true
  83948. });
  83949. /**
  83950. * Execute a function that is physics-plugin specific.
  83951. * @param {Function} func the function that will be executed.
  83952. * It accepts two parameters: the physics world and the physics joint.
  83953. */
  83954. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83955. func(this._physicsPlugin.world, this._physicsJoint);
  83956. };
  83957. //TODO check if the native joints are the same
  83958. //Joint Types
  83959. PhysicsJoint.DistanceJoint = 0;
  83960. PhysicsJoint.HingeJoint = 1;
  83961. PhysicsJoint.BallAndSocketJoint = 2;
  83962. PhysicsJoint.WheelJoint = 3;
  83963. PhysicsJoint.SliderJoint = 4;
  83964. //OIMO
  83965. PhysicsJoint.PrismaticJoint = 5;
  83966. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83967. PhysicsJoint.UniversalJoint = 6;
  83968. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83969. //Cannon
  83970. //Similar to a Ball-Joint. Different in params
  83971. PhysicsJoint.PointToPointJoint = 8;
  83972. //Cannon only at the moment
  83973. PhysicsJoint.SpringJoint = 9;
  83974. PhysicsJoint.LockJoint = 10;
  83975. return PhysicsJoint;
  83976. }());
  83977. BABYLON.PhysicsJoint = PhysicsJoint;
  83978. /**
  83979. * A class representing a physics distance joint.
  83980. */
  83981. var DistanceJoint = /** @class */ (function (_super) {
  83982. __extends(DistanceJoint, _super);
  83983. function DistanceJoint(jointData) {
  83984. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83985. }
  83986. /**
  83987. * Update the predefined distance.
  83988. */
  83989. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83990. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83991. };
  83992. return DistanceJoint;
  83993. }(PhysicsJoint));
  83994. BABYLON.DistanceJoint = DistanceJoint;
  83995. var MotorEnabledJoint = /** @class */ (function (_super) {
  83996. __extends(MotorEnabledJoint, _super);
  83997. function MotorEnabledJoint(type, jointData) {
  83998. return _super.call(this, type, jointData) || this;
  83999. }
  84000. /**
  84001. * Set the motor values.
  84002. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84003. * @param {number} force the force to apply
  84004. * @param {number} maxForce max force for this motor.
  84005. */
  84006. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84007. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84008. };
  84009. /**
  84010. * Set the motor's limits.
  84011. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84012. */
  84013. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84014. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84015. };
  84016. return MotorEnabledJoint;
  84017. }(PhysicsJoint));
  84018. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84019. /**
  84020. * This class represents a single hinge physics joint
  84021. */
  84022. var HingeJoint = /** @class */ (function (_super) {
  84023. __extends(HingeJoint, _super);
  84024. function HingeJoint(jointData) {
  84025. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84026. }
  84027. /**
  84028. * Set the motor values.
  84029. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84030. * @param {number} force the force to apply
  84031. * @param {number} maxForce max force for this motor.
  84032. */
  84033. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84034. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84035. };
  84036. /**
  84037. * Set the motor's limits.
  84038. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84039. */
  84040. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84041. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84042. };
  84043. return HingeJoint;
  84044. }(MotorEnabledJoint));
  84045. BABYLON.HingeJoint = HingeJoint;
  84046. /**
  84047. * This class represents a dual hinge physics joint (same as wheel joint)
  84048. */
  84049. var Hinge2Joint = /** @class */ (function (_super) {
  84050. __extends(Hinge2Joint, _super);
  84051. function Hinge2Joint(jointData) {
  84052. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84053. }
  84054. /**
  84055. * Set the motor values.
  84056. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84057. * @param {number} force the force to apply
  84058. * @param {number} maxForce max force for this motor.
  84059. * @param {motorIndex} the motor's index, 0 or 1.
  84060. */
  84061. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84062. if (motorIndex === void 0) { motorIndex = 0; }
  84063. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84064. };
  84065. /**
  84066. * Set the motor limits.
  84067. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84068. * @param {number} upperLimit the upper limit
  84069. * @param {number} lowerLimit lower limit
  84070. * @param {motorIndex} the motor's index, 0 or 1.
  84071. */
  84072. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84073. if (motorIndex === void 0) { motorIndex = 0; }
  84074. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84075. };
  84076. return Hinge2Joint;
  84077. }(MotorEnabledJoint));
  84078. BABYLON.Hinge2Joint = Hinge2Joint;
  84079. })(BABYLON || (BABYLON = {}));
  84080. //# sourceMappingURL=babylon.physicsJoint.js.map
  84081. var BABYLON;
  84082. (function (BABYLON) {
  84083. var PhysicsImpostor = /** @class */ (function () {
  84084. function PhysicsImpostor(object, type, _options, _scene) {
  84085. if (_options === void 0) { _options = { mass: 0 }; }
  84086. var _this = this;
  84087. this.object = object;
  84088. this.type = type;
  84089. this._options = _options;
  84090. this._scene = _scene;
  84091. this._bodyUpdateRequired = false;
  84092. this._onBeforePhysicsStepCallbacks = new Array();
  84093. this._onAfterPhysicsStepCallbacks = new Array();
  84094. this._onPhysicsCollideCallbacks = [];
  84095. this._deltaPosition = BABYLON.Vector3.Zero();
  84096. this._isDisposed = false;
  84097. //temp variables for parent rotation calculations
  84098. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84099. this._tmpQuat = new BABYLON.Quaternion();
  84100. this._tmpQuat2 = new BABYLON.Quaternion();
  84101. /**
  84102. * this function is executed by the physics engine.
  84103. */
  84104. this.beforeStep = function () {
  84105. if (!_this._physicsEngine) {
  84106. return;
  84107. }
  84108. _this.object.translate(_this._deltaPosition, -1);
  84109. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84110. _this.object.computeWorldMatrix(false);
  84111. if (_this.object.parent && _this.object.rotationQuaternion) {
  84112. _this.getParentsRotation();
  84113. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84114. }
  84115. else {
  84116. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84117. }
  84118. if (!_this._options.disableBidirectionalTransformation) {
  84119. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84120. }
  84121. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84122. func(_this);
  84123. });
  84124. };
  84125. /**
  84126. * this function is executed by the physics engine.
  84127. */
  84128. this.afterStep = function () {
  84129. if (!_this._physicsEngine) {
  84130. return;
  84131. }
  84132. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84133. func(_this);
  84134. });
  84135. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84136. // object has now its world rotation. needs to be converted to local.
  84137. if (_this.object.parent && _this.object.rotationQuaternion) {
  84138. _this.getParentsRotation();
  84139. _this._tmpQuat.conjugateInPlace();
  84140. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84141. }
  84142. // take the position set and make it the absolute position of this object.
  84143. _this.object.setAbsolutePosition(_this.object.position);
  84144. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84145. _this.object.translate(_this._deltaPosition, 1);
  84146. };
  84147. /**
  84148. * Legacy collision detection event support
  84149. */
  84150. this.onCollideEvent = null;
  84151. //event and body object due to cannon's event-based architecture.
  84152. this.onCollide = function (e) {
  84153. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84154. return;
  84155. }
  84156. if (!_this._physicsEngine) {
  84157. return;
  84158. }
  84159. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84160. if (otherImpostor) {
  84161. // Legacy collision detection event support
  84162. if (_this.onCollideEvent) {
  84163. _this.onCollideEvent(_this, otherImpostor);
  84164. }
  84165. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84166. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84167. }).forEach(function (obj) {
  84168. obj.callback(_this, otherImpostor);
  84169. });
  84170. }
  84171. };
  84172. //sanity check!
  84173. if (!this.object) {
  84174. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84175. return;
  84176. }
  84177. //legacy support for old syntax.
  84178. if (!this._scene && object.getScene) {
  84179. this._scene = object.getScene();
  84180. }
  84181. if (!this._scene) {
  84182. return;
  84183. }
  84184. this._physicsEngine = this._scene.getPhysicsEngine();
  84185. if (!this._physicsEngine) {
  84186. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84187. }
  84188. else {
  84189. //set the object's quaternion, if not set
  84190. if (!this.object.rotationQuaternion) {
  84191. if (this.object.rotation) {
  84192. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84193. }
  84194. else {
  84195. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84196. }
  84197. }
  84198. //default options params
  84199. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84200. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84201. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84202. this._joints = [];
  84203. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84204. if (!this.object.parent || this._options.ignoreParent) {
  84205. this._init();
  84206. }
  84207. else if (this.object.parent.physicsImpostor) {
  84208. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84209. }
  84210. }
  84211. }
  84212. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84213. get: function () {
  84214. return this._isDisposed;
  84215. },
  84216. enumerable: true,
  84217. configurable: true
  84218. });
  84219. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84220. get: function () {
  84221. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84222. },
  84223. set: function (value) {
  84224. this.setMass(value);
  84225. },
  84226. enumerable: true,
  84227. configurable: true
  84228. });
  84229. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84230. get: function () {
  84231. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84232. },
  84233. set: function (value) {
  84234. if (!this._physicsEngine) {
  84235. return;
  84236. }
  84237. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84238. },
  84239. enumerable: true,
  84240. configurable: true
  84241. });
  84242. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84243. get: function () {
  84244. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84245. },
  84246. set: function (value) {
  84247. if (!this._physicsEngine) {
  84248. return;
  84249. }
  84250. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84251. },
  84252. enumerable: true,
  84253. configurable: true
  84254. });
  84255. /**
  84256. * This function will completly initialize this impostor.
  84257. * It will create a new body - but only if this mesh has no parent.
  84258. * If it has, this impostor will not be used other than to define the impostor
  84259. * of the child mesh.
  84260. */
  84261. PhysicsImpostor.prototype._init = function () {
  84262. if (!this._physicsEngine) {
  84263. return;
  84264. }
  84265. this._physicsEngine.removeImpostor(this);
  84266. this.physicsBody = null;
  84267. this._parent = this._parent || this._getPhysicsParent();
  84268. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84269. this._physicsEngine.addImpostor(this);
  84270. }
  84271. };
  84272. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84273. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84274. var parentMesh = this.object.parent;
  84275. return parentMesh.physicsImpostor;
  84276. }
  84277. return null;
  84278. };
  84279. /**
  84280. * Should a new body be generated.
  84281. */
  84282. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84283. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84284. };
  84285. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84286. this.forceUpdate();
  84287. };
  84288. /**
  84289. * Force a regeneration of this or the parent's impostor's body.
  84290. * Use under cautious - This will remove all joints already implemented.
  84291. */
  84292. PhysicsImpostor.prototype.forceUpdate = function () {
  84293. this._init();
  84294. if (this.parent && !this._options.ignoreParent) {
  84295. this.parent.forceUpdate();
  84296. }
  84297. };
  84298. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84299. /*public get mesh(): AbstractMesh {
  84300. return this._mesh;
  84301. }*/
  84302. /**
  84303. * Gets the body that holds this impostor. Either its own, or its parent.
  84304. */
  84305. get: function () {
  84306. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84307. },
  84308. /**
  84309. * Set the physics body. Used mainly by the physics engine/plugin
  84310. */
  84311. set: function (physicsBody) {
  84312. if (this._physicsBody && this._physicsEngine) {
  84313. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84314. }
  84315. this._physicsBody = physicsBody;
  84316. this.resetUpdateFlags();
  84317. },
  84318. enumerable: true,
  84319. configurable: true
  84320. });
  84321. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84322. get: function () {
  84323. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84324. },
  84325. set: function (value) {
  84326. this._parent = value;
  84327. },
  84328. enumerable: true,
  84329. configurable: true
  84330. });
  84331. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84332. this._bodyUpdateRequired = false;
  84333. };
  84334. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84335. if (this.object.getBoundingInfo) {
  84336. var q = this.object.rotationQuaternion;
  84337. //reset rotation
  84338. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84339. //calculate the world matrix with no rotation
  84340. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84341. var boundingInfo = this.object.getBoundingInfo();
  84342. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84343. //bring back the rotation
  84344. this.object.rotationQuaternion = q;
  84345. //calculate the world matrix with the new rotation
  84346. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84347. return size;
  84348. }
  84349. else {
  84350. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84351. }
  84352. };
  84353. PhysicsImpostor.prototype.getObjectCenter = function () {
  84354. if (this.object.getBoundingInfo) {
  84355. var boundingInfo = this.object.getBoundingInfo();
  84356. return boundingInfo.boundingBox.centerWorld;
  84357. }
  84358. else {
  84359. return this.object.position;
  84360. }
  84361. };
  84362. /**
  84363. * Get a specific parametes from the options parameter.
  84364. */
  84365. PhysicsImpostor.prototype.getParam = function (paramName) {
  84366. return this._options[paramName];
  84367. };
  84368. /**
  84369. * Sets a specific parameter in the options given to the physics plugin
  84370. */
  84371. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84372. this._options[paramName] = value;
  84373. this._bodyUpdateRequired = true;
  84374. };
  84375. /**
  84376. * Specifically change the body's mass option. Won't recreate the physics body object
  84377. */
  84378. PhysicsImpostor.prototype.setMass = function (mass) {
  84379. if (this.getParam("mass") !== mass) {
  84380. this.setParam("mass", mass);
  84381. }
  84382. if (this._physicsEngine) {
  84383. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84384. }
  84385. };
  84386. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84387. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84388. };
  84389. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84390. if (this._physicsEngine) {
  84391. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84392. }
  84393. };
  84394. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84395. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84396. };
  84397. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84398. if (this._physicsEngine) {
  84399. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84400. }
  84401. };
  84402. /**
  84403. * Execute a function with the physics plugin native code.
  84404. * Provide a function the will have two variables - the world object and the physics body object.
  84405. */
  84406. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84407. if (this._physicsEngine) {
  84408. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84409. }
  84410. };
  84411. /**
  84412. * Register a function that will be executed before the physics world is stepping forward.
  84413. */
  84414. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84415. this._onBeforePhysicsStepCallbacks.push(func);
  84416. };
  84417. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84418. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84419. if (index > -1) {
  84420. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84421. }
  84422. else {
  84423. BABYLON.Tools.Warn("Function to remove was not found");
  84424. }
  84425. };
  84426. /**
  84427. * Register a function that will be executed after the physics step
  84428. */
  84429. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84430. this._onAfterPhysicsStepCallbacks.push(func);
  84431. };
  84432. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84433. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84434. if (index > -1) {
  84435. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84436. }
  84437. else {
  84438. BABYLON.Tools.Warn("Function to remove was not found");
  84439. }
  84440. };
  84441. /**
  84442. * register a function that will be executed when this impostor collides against a different body.
  84443. */
  84444. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84445. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84446. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84447. };
  84448. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84449. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84450. var index = -1;
  84451. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84452. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84453. // chcek the arrays match
  84454. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84455. return collidedAgainstList.indexOf(impostor) > -1;
  84456. });
  84457. if (sameList) {
  84458. index = idx;
  84459. }
  84460. return sameList;
  84461. }
  84462. return false;
  84463. });
  84464. if (found) {
  84465. this._onPhysicsCollideCallbacks.splice(index, 1);
  84466. }
  84467. else {
  84468. BABYLON.Tools.Warn("Function to remove was not found");
  84469. }
  84470. };
  84471. PhysicsImpostor.prototype.getParentsRotation = function () {
  84472. var parent = this.object.parent;
  84473. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84474. while (parent) {
  84475. if (parent.rotationQuaternion) {
  84476. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84477. }
  84478. else {
  84479. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84480. }
  84481. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84482. parent = parent.parent;
  84483. }
  84484. return this._tmpQuat;
  84485. };
  84486. /**
  84487. * Apply a force
  84488. */
  84489. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84490. if (this._physicsEngine) {
  84491. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84492. }
  84493. return this;
  84494. };
  84495. /**
  84496. * Apply an impulse
  84497. */
  84498. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84499. if (this._physicsEngine) {
  84500. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84501. }
  84502. return this;
  84503. };
  84504. /**
  84505. * A help function to create a joint.
  84506. */
  84507. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84508. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84509. this.addJoint(otherImpostor, joint);
  84510. return this;
  84511. };
  84512. /**
  84513. * Add a joint to this impostor with a different impostor.
  84514. */
  84515. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84516. this._joints.push({
  84517. otherImpostor: otherImpostor,
  84518. joint: joint
  84519. });
  84520. if (this._physicsEngine) {
  84521. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84522. }
  84523. return this;
  84524. };
  84525. /**
  84526. * Will keep this body still, in a sleep mode.
  84527. */
  84528. PhysicsImpostor.prototype.sleep = function () {
  84529. if (this._physicsEngine) {
  84530. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84531. }
  84532. return this;
  84533. };
  84534. /**
  84535. * Wake the body up.
  84536. */
  84537. PhysicsImpostor.prototype.wakeUp = function () {
  84538. if (this._physicsEngine) {
  84539. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84540. }
  84541. return this;
  84542. };
  84543. PhysicsImpostor.prototype.clone = function (newObject) {
  84544. if (!newObject)
  84545. return null;
  84546. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84547. };
  84548. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84549. var _this = this;
  84550. //no dispose if no physics engine is available.
  84551. if (!this._physicsEngine) {
  84552. return;
  84553. }
  84554. this._joints.forEach(function (j) {
  84555. if (_this._physicsEngine) {
  84556. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84557. }
  84558. });
  84559. //dispose the physics body
  84560. this._physicsEngine.removeImpostor(this);
  84561. if (this.parent) {
  84562. this.parent.forceUpdate();
  84563. }
  84564. else {
  84565. /*this._object.getChildMeshes().forEach(function(mesh) {
  84566. if (mesh.physicsImpostor) {
  84567. if (disposeChildren) {
  84568. mesh.physicsImpostor.dispose();
  84569. mesh.physicsImpostor = null;
  84570. }
  84571. }
  84572. })*/
  84573. }
  84574. this._isDisposed = true;
  84575. };
  84576. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84577. this._deltaPosition.copyFrom(position);
  84578. };
  84579. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84580. if (!this._deltaRotation) {
  84581. this._deltaRotation = new BABYLON.Quaternion();
  84582. }
  84583. this._deltaRotation.copyFrom(rotation);
  84584. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84585. };
  84586. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84587. if (this._physicsEngine) {
  84588. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84589. }
  84590. return this;
  84591. };
  84592. PhysicsImpostor.prototype.getRadius = function () {
  84593. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84594. };
  84595. /**
  84596. * Sync a bone with this impostor
  84597. * @param bone The bone to sync to the impostor.
  84598. * @param boneMesh The mesh that the bone is influencing.
  84599. * @param jointPivot The pivot of the joint / bone in local space.
  84600. * @param distToJoint Optional distance from the impostor to the joint.
  84601. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84602. */
  84603. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84604. var tempVec = PhysicsImpostor._tmpVecs[0];
  84605. var mesh = this.object;
  84606. if (mesh.rotationQuaternion) {
  84607. if (adjustRotation) {
  84608. var tempQuat = PhysicsImpostor._tmpQuat;
  84609. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84610. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84611. }
  84612. else {
  84613. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84614. }
  84615. }
  84616. tempVec.x = 0;
  84617. tempVec.y = 0;
  84618. tempVec.z = 0;
  84619. if (jointPivot) {
  84620. tempVec.x = jointPivot.x;
  84621. tempVec.y = jointPivot.y;
  84622. tempVec.z = jointPivot.z;
  84623. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84624. if (distToJoint === undefined || distToJoint === null) {
  84625. distToJoint = jointPivot.length();
  84626. }
  84627. tempVec.x *= distToJoint;
  84628. tempVec.y *= distToJoint;
  84629. tempVec.z *= distToJoint;
  84630. }
  84631. if (bone.getParent()) {
  84632. tempVec.addInPlace(mesh.getAbsolutePosition());
  84633. bone.setAbsolutePosition(tempVec, boneMesh);
  84634. }
  84635. else {
  84636. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84637. boneMesh.position.x -= tempVec.x;
  84638. boneMesh.position.y -= tempVec.y;
  84639. boneMesh.position.z -= tempVec.z;
  84640. }
  84641. };
  84642. /**
  84643. * Sync impostor to a bone
  84644. * @param bone The bone that the impostor will be synced to.
  84645. * @param boneMesh The mesh that the bone is influencing.
  84646. * @param jointPivot The pivot of the joint / bone in local space.
  84647. * @param distToJoint Optional distance from the impostor to the joint.
  84648. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84649. * @param boneAxis Optional vector3 axis the bone is aligned with
  84650. */
  84651. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84652. var mesh = this.object;
  84653. if (mesh.rotationQuaternion) {
  84654. if (adjustRotation) {
  84655. var tempQuat = PhysicsImpostor._tmpQuat;
  84656. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84657. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84658. }
  84659. else {
  84660. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84661. }
  84662. }
  84663. var pos = PhysicsImpostor._tmpVecs[0];
  84664. var boneDir = PhysicsImpostor._tmpVecs[1];
  84665. if (!boneAxis) {
  84666. boneAxis = PhysicsImpostor._tmpVecs[2];
  84667. boneAxis.x = 0;
  84668. boneAxis.y = 1;
  84669. boneAxis.z = 0;
  84670. }
  84671. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84672. bone.getAbsolutePositionToRef(boneMesh, pos);
  84673. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84674. distToJoint = jointPivot.length();
  84675. }
  84676. if (distToJoint !== undefined && distToJoint !== null) {
  84677. pos.x += boneDir.x * distToJoint;
  84678. pos.y += boneDir.y * distToJoint;
  84679. pos.z += boneDir.z * distToJoint;
  84680. }
  84681. mesh.setAbsolutePosition(pos);
  84682. };
  84683. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84684. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84685. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84686. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84687. //Impostor types
  84688. PhysicsImpostor.NoImpostor = 0;
  84689. PhysicsImpostor.SphereImpostor = 1;
  84690. PhysicsImpostor.BoxImpostor = 2;
  84691. PhysicsImpostor.PlaneImpostor = 3;
  84692. PhysicsImpostor.MeshImpostor = 4;
  84693. PhysicsImpostor.CylinderImpostor = 7;
  84694. PhysicsImpostor.ParticleImpostor = 8;
  84695. PhysicsImpostor.HeightmapImpostor = 9;
  84696. return PhysicsImpostor;
  84697. }());
  84698. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84699. })(BABYLON || (BABYLON = {}));
  84700. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84701. var BABYLON;
  84702. (function (BABYLON) {
  84703. var PhysicsEngine = /** @class */ (function () {
  84704. function PhysicsEngine(gravity, _physicsPlugin) {
  84705. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84706. this._physicsPlugin = _physicsPlugin;
  84707. //new methods and parameters
  84708. this._impostors = [];
  84709. this._joints = [];
  84710. if (!this._physicsPlugin.isSupported()) {
  84711. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84712. + "Please make sure it is included.");
  84713. }
  84714. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84715. this.setGravity(gravity);
  84716. this.setTimeStep();
  84717. }
  84718. PhysicsEngine.prototype.setGravity = function (gravity) {
  84719. this.gravity = gravity;
  84720. this._physicsPlugin.setGravity(this.gravity);
  84721. };
  84722. /**
  84723. * Set the time step of the physics engine.
  84724. * default is 1/60.
  84725. * To slow it down, enter 1/600 for example.
  84726. * To speed it up, 1/30
  84727. * @param {number} newTimeStep the new timestep to apply to this world.
  84728. */
  84729. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84730. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84731. this._physicsPlugin.setTimeStep(newTimeStep);
  84732. };
  84733. /**
  84734. * Get the time step of the physics engine.
  84735. */
  84736. PhysicsEngine.prototype.getTimeStep = function () {
  84737. return this._physicsPlugin.getTimeStep();
  84738. };
  84739. PhysicsEngine.prototype.dispose = function () {
  84740. this._impostors.forEach(function (impostor) {
  84741. impostor.dispose();
  84742. });
  84743. this._physicsPlugin.dispose();
  84744. };
  84745. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84746. return this._physicsPlugin.name;
  84747. };
  84748. /**
  84749. * Adding a new impostor for the impostor tracking.
  84750. * This will be done by the impostor itself.
  84751. * @param {PhysicsImpostor} impostor the impostor to add
  84752. */
  84753. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84754. impostor.uniqueId = this._impostors.push(impostor);
  84755. //if no parent, generate the body
  84756. if (!impostor.parent) {
  84757. this._physicsPlugin.generatePhysicsBody(impostor);
  84758. }
  84759. };
  84760. /**
  84761. * Remove an impostor from the engine.
  84762. * This impostor and its mesh will not longer be updated by the physics engine.
  84763. * @param {PhysicsImpostor} impostor the impostor to remove
  84764. */
  84765. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84766. var index = this._impostors.indexOf(impostor);
  84767. if (index > -1) {
  84768. var removed = this._impostors.splice(index, 1);
  84769. //Is it needed?
  84770. if (removed.length) {
  84771. //this will also remove it from the world.
  84772. removed[0].physicsBody = null;
  84773. }
  84774. }
  84775. };
  84776. /**
  84777. * Add a joint to the physics engine
  84778. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84779. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84780. * @param {PhysicsJoint} the joint that will connect both impostors.
  84781. */
  84782. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84783. var impostorJoint = {
  84784. mainImpostor: mainImpostor,
  84785. connectedImpostor: connectedImpostor,
  84786. joint: joint
  84787. };
  84788. joint.physicsPlugin = this._physicsPlugin;
  84789. this._joints.push(impostorJoint);
  84790. this._physicsPlugin.generateJoint(impostorJoint);
  84791. };
  84792. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84793. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84794. return (impostorJoint.connectedImpostor === connectedImpostor
  84795. && impostorJoint.joint === joint
  84796. && impostorJoint.mainImpostor === mainImpostor);
  84797. });
  84798. if (matchingJoints.length) {
  84799. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84800. //TODO remove it from the list as well
  84801. }
  84802. };
  84803. /**
  84804. * Called by the scene. no need to call it.
  84805. */
  84806. PhysicsEngine.prototype._step = function (delta) {
  84807. var _this = this;
  84808. //check if any mesh has no body / requires an update
  84809. this._impostors.forEach(function (impostor) {
  84810. if (impostor.isBodyInitRequired()) {
  84811. _this._physicsPlugin.generatePhysicsBody(impostor);
  84812. }
  84813. });
  84814. if (delta > 0.1) {
  84815. delta = 0.1;
  84816. }
  84817. else if (delta <= 0) {
  84818. delta = 1.0 / 60.0;
  84819. }
  84820. this._physicsPlugin.executeStep(delta, this._impostors);
  84821. };
  84822. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84823. return this._physicsPlugin;
  84824. };
  84825. PhysicsEngine.prototype.getImpostors = function () {
  84826. return this._impostors;
  84827. };
  84828. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84829. for (var i = 0; i < this._impostors.length; ++i) {
  84830. if (this._impostors[i].object === object) {
  84831. return this._impostors[i];
  84832. }
  84833. }
  84834. return null;
  84835. };
  84836. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84837. for (var i = 0; i < this._impostors.length; ++i) {
  84838. if (this._impostors[i].physicsBody === body) {
  84839. return this._impostors[i];
  84840. }
  84841. }
  84842. return null;
  84843. };
  84844. // Statics
  84845. PhysicsEngine.Epsilon = 0.001;
  84846. return PhysicsEngine;
  84847. }());
  84848. BABYLON.PhysicsEngine = PhysicsEngine;
  84849. })(BABYLON || (BABYLON = {}));
  84850. //# sourceMappingURL=babylon.physicsEngine.js.map
  84851. var BABYLON;
  84852. (function (BABYLON) {
  84853. var PhysicsHelper = /** @class */ (function () {
  84854. function PhysicsHelper(scene) {
  84855. this._scene = scene;
  84856. this._physicsEngine = this._scene.getPhysicsEngine();
  84857. if (!this._physicsEngine) {
  84858. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84859. }
  84860. }
  84861. /**
  84862. * @param {Vector3} origin the origin of the explosion
  84863. * @param {number} radius the explosion radius
  84864. * @param {number} strength the explosion strength
  84865. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84866. */
  84867. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84868. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84869. if (!this._physicsEngine) {
  84870. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84871. return null;
  84872. }
  84873. var impostors = this._physicsEngine.getImpostors();
  84874. if (impostors.length === 0) {
  84875. return null;
  84876. }
  84877. var event = new PhysicsRadialExplosionEvent(this._scene);
  84878. impostors.forEach(function (impostor) {
  84879. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84880. if (!impostorForceAndContactPoint) {
  84881. return;
  84882. }
  84883. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84884. });
  84885. event.dispose(false);
  84886. return event;
  84887. };
  84888. /**
  84889. * @param {Vector3} origin the origin of the explosion
  84890. * @param {number} radius the explosion radius
  84891. * @param {number} strength the explosion strength
  84892. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84893. */
  84894. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84895. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84896. if (!this._physicsEngine) {
  84897. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84898. return null;
  84899. }
  84900. var impostors = this._physicsEngine.getImpostors();
  84901. if (impostors.length === 0) {
  84902. return null;
  84903. }
  84904. var event = new PhysicsRadialExplosionEvent(this._scene);
  84905. impostors.forEach(function (impostor) {
  84906. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84907. if (!impostorForceAndContactPoint) {
  84908. return;
  84909. }
  84910. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84911. });
  84912. event.dispose(false);
  84913. return event;
  84914. };
  84915. /**
  84916. * @param {Vector3} origin the origin of the explosion
  84917. * @param {number} radius the explosion radius
  84918. * @param {number} strength the explosion strength
  84919. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84920. */
  84921. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84922. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84923. if (!this._physicsEngine) {
  84924. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84925. return null;
  84926. }
  84927. var impostors = this._physicsEngine.getImpostors();
  84928. if (impostors.length === 0) {
  84929. return null;
  84930. }
  84931. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84932. event.dispose(false);
  84933. return event;
  84934. };
  84935. /**
  84936. * @param {Vector3} origin the origin of the updraft
  84937. * @param {number} radius the radius of the updraft
  84938. * @param {number} strength the strength of the updraft
  84939. * @param {number} height the height of the updraft
  84940. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84941. */
  84942. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84943. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84944. if (!this._physicsEngine) {
  84945. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84946. return null;
  84947. }
  84948. if (this._physicsEngine.getImpostors().length === 0) {
  84949. return null;
  84950. }
  84951. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84952. event.dispose(false);
  84953. return event;
  84954. };
  84955. /**
  84956. * @param {Vector3} origin the of the vortex
  84957. * @param {number} radius the radius of the vortex
  84958. * @param {number} strength the strength of the vortex
  84959. * @param {number} height the height of the vortex
  84960. */
  84961. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84962. if (!this._physicsEngine) {
  84963. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84964. return null;
  84965. }
  84966. if (this._physicsEngine.getImpostors().length === 0) {
  84967. return null;
  84968. }
  84969. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84970. event.dispose(false);
  84971. return event;
  84972. };
  84973. return PhysicsHelper;
  84974. }());
  84975. BABYLON.PhysicsHelper = PhysicsHelper;
  84976. /***** Radial explosion *****/
  84977. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84978. function PhysicsRadialExplosionEvent(scene) {
  84979. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84980. this._rays = [];
  84981. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84982. this._scene = scene;
  84983. }
  84984. /**
  84985. * Returns the data related to the radial explosion event (sphere & rays).
  84986. * @returns {PhysicsRadialExplosionEventData}
  84987. */
  84988. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84989. this._dataFetched = true;
  84990. return {
  84991. sphere: this._sphere,
  84992. rays: this._rays,
  84993. };
  84994. };
  84995. /**
  84996. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84997. * @param impostor
  84998. * @param {Vector3} origin the origin of the explosion
  84999. * @param {number} radius the explosion radius
  85000. * @param {number} strength the explosion strength
  85001. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85002. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85003. */
  85004. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85005. if (impostor.mass === 0) {
  85006. return null;
  85007. }
  85008. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85009. return null;
  85010. }
  85011. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85012. return null;
  85013. }
  85014. var impostorObjectCenter = impostor.getObjectCenter();
  85015. var direction = impostorObjectCenter.subtract(origin);
  85016. var ray = new BABYLON.Ray(origin, direction, radius);
  85017. this._rays.push(ray);
  85018. var hit = ray.intersectsMesh(impostor.object);
  85019. var contactPoint = hit.pickedPoint;
  85020. if (!contactPoint) {
  85021. return null;
  85022. }
  85023. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85024. if (distanceFromOrigin > radius) {
  85025. return null;
  85026. }
  85027. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85028. ? strength
  85029. : strength * (1 - (distanceFromOrigin / radius));
  85030. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85031. return { force: force, contactPoint: contactPoint };
  85032. };
  85033. /**
  85034. * Disposes the sphere.
  85035. * @param {bolean} force
  85036. */
  85037. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85038. var _this = this;
  85039. if (force === void 0) { force = true; }
  85040. if (force) {
  85041. this._sphere.dispose();
  85042. }
  85043. else {
  85044. setTimeout(function () {
  85045. if (!_this._dataFetched) {
  85046. _this._sphere.dispose();
  85047. }
  85048. }, 0);
  85049. }
  85050. };
  85051. /*** Helpers ***/
  85052. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85053. if (!this._sphere) {
  85054. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85055. this._sphere.isVisible = false;
  85056. }
  85057. };
  85058. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85059. var impostorObject = impostor.object;
  85060. this._prepareSphere();
  85061. this._sphere.position = origin;
  85062. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85063. this._sphere._updateBoundingInfo();
  85064. this._sphere.computeWorldMatrix(true);
  85065. return this._sphere.intersectsMesh(impostorObject, true);
  85066. };
  85067. return PhysicsRadialExplosionEvent;
  85068. }());
  85069. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85070. /***** Gravitational Field *****/
  85071. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85072. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85073. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85074. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85075. this._physicsHelper = physicsHelper;
  85076. this._scene = scene;
  85077. this._origin = origin;
  85078. this._radius = radius;
  85079. this._strength = strength;
  85080. this._falloff = falloff;
  85081. this._tickCallback = this._tick.bind(this);
  85082. }
  85083. /**
  85084. * Returns the data related to the gravitational field event (sphere).
  85085. * @returns {PhysicsGravitationalFieldEventData}
  85086. */
  85087. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85088. this._dataFetched = true;
  85089. return {
  85090. sphere: this._sphere,
  85091. };
  85092. };
  85093. /**
  85094. * Enables the gravitational field.
  85095. */
  85096. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85097. this._tickCallback.call(this);
  85098. this._scene.registerBeforeRender(this._tickCallback);
  85099. };
  85100. /**
  85101. * Disables the gravitational field.
  85102. */
  85103. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85104. this._scene.unregisterBeforeRender(this._tickCallback);
  85105. };
  85106. /**
  85107. * Disposes the sphere.
  85108. * @param {bolean} force
  85109. */
  85110. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85111. var _this = this;
  85112. if (force === void 0) { force = true; }
  85113. if (force) {
  85114. this._sphere.dispose();
  85115. }
  85116. else {
  85117. setTimeout(function () {
  85118. if (!_this._dataFetched) {
  85119. _this._sphere.dispose();
  85120. }
  85121. }, 0);
  85122. }
  85123. };
  85124. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85125. // Since the params won't change, we fetch the event only once
  85126. if (this._sphere) {
  85127. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85128. }
  85129. else {
  85130. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85131. if (radialExplosionEvent) {
  85132. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85133. }
  85134. }
  85135. };
  85136. return PhysicsGravitationalFieldEvent;
  85137. }());
  85138. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85139. /***** Updraft *****/
  85140. var PhysicsUpdraftEvent = /** @class */ (function () {
  85141. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85142. this._scene = _scene;
  85143. this._origin = _origin;
  85144. this._radius = _radius;
  85145. this._strength = _strength;
  85146. this._height = _height;
  85147. this._updraftMode = _updraftMode;
  85148. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85149. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85150. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85151. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85152. this._physicsEngine = this._scene.getPhysicsEngine();
  85153. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85154. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85155. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85156. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85157. }
  85158. this._tickCallback = this._tick.bind(this);
  85159. }
  85160. /**
  85161. * Returns the data related to the updraft event (cylinder).
  85162. * @returns {PhysicsUpdraftEventData}
  85163. */
  85164. PhysicsUpdraftEvent.prototype.getData = function () {
  85165. this._dataFetched = true;
  85166. return {
  85167. cylinder: this._cylinder,
  85168. };
  85169. };
  85170. /**
  85171. * Enables the updraft.
  85172. */
  85173. PhysicsUpdraftEvent.prototype.enable = function () {
  85174. this._tickCallback.call(this);
  85175. this._scene.registerBeforeRender(this._tickCallback);
  85176. };
  85177. /**
  85178. * Disables the cortex.
  85179. */
  85180. PhysicsUpdraftEvent.prototype.disable = function () {
  85181. this._scene.unregisterBeforeRender(this._tickCallback);
  85182. };
  85183. /**
  85184. * Disposes the sphere.
  85185. * @param {bolean} force
  85186. */
  85187. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85188. var _this = this;
  85189. if (force === void 0) { force = true; }
  85190. if (force) {
  85191. this._cylinder.dispose();
  85192. }
  85193. else {
  85194. setTimeout(function () {
  85195. if (!_this._dataFetched) {
  85196. _this._cylinder.dispose();
  85197. }
  85198. }, 0);
  85199. }
  85200. };
  85201. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85202. if (impostor.mass === 0) {
  85203. return null;
  85204. }
  85205. if (!this._intersectsWithCylinder(impostor)) {
  85206. return null;
  85207. }
  85208. var impostorObjectCenter = impostor.getObjectCenter();
  85209. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85210. var direction = this._originDirection;
  85211. }
  85212. else {
  85213. var direction = impostorObjectCenter.subtract(this._originTop);
  85214. }
  85215. var multiplier = this._strength * -1;
  85216. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85217. return { force: force, contactPoint: impostorObjectCenter };
  85218. };
  85219. PhysicsUpdraftEvent.prototype._tick = function () {
  85220. var _this = this;
  85221. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85222. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85223. if (!impostorForceAndContactPoint) {
  85224. return;
  85225. }
  85226. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85227. });
  85228. };
  85229. /*** Helpers ***/
  85230. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85231. if (!this._cylinder) {
  85232. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85233. height: this._height,
  85234. diameter: this._radius * 2,
  85235. }, this._scene);
  85236. this._cylinder.isVisible = false;
  85237. }
  85238. };
  85239. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85240. var impostorObject = impostor.object;
  85241. this._prepareCylinder();
  85242. this._cylinder.position = this._cylinderPosition;
  85243. return this._cylinder.intersectsMesh(impostorObject, true);
  85244. };
  85245. return PhysicsUpdraftEvent;
  85246. }());
  85247. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85248. /***** Vortex *****/
  85249. var PhysicsVortexEvent = /** @class */ (function () {
  85250. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85251. this._scene = _scene;
  85252. this._origin = _origin;
  85253. this._radius = _radius;
  85254. this._strength = _strength;
  85255. this._height = _height;
  85256. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85257. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85258. this._updraftMultiplier = 0.02;
  85259. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85260. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85261. this._physicsEngine = this._scene.getPhysicsEngine();
  85262. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85263. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85264. this._tickCallback = this._tick.bind(this);
  85265. }
  85266. /**
  85267. * Returns the data related to the vortex event (cylinder).
  85268. * @returns {PhysicsVortexEventData}
  85269. */
  85270. PhysicsVortexEvent.prototype.getData = function () {
  85271. this._dataFetched = true;
  85272. return {
  85273. cylinder: this._cylinder,
  85274. };
  85275. };
  85276. /**
  85277. * Enables the vortex.
  85278. */
  85279. PhysicsVortexEvent.prototype.enable = function () {
  85280. this._tickCallback.call(this);
  85281. this._scene.registerBeforeRender(this._tickCallback);
  85282. };
  85283. /**
  85284. * Disables the cortex.
  85285. */
  85286. PhysicsVortexEvent.prototype.disable = function () {
  85287. this._scene.unregisterBeforeRender(this._tickCallback);
  85288. };
  85289. /**
  85290. * Disposes the sphere.
  85291. * @param {bolean} force
  85292. */
  85293. PhysicsVortexEvent.prototype.dispose = function (force) {
  85294. var _this = this;
  85295. if (force === void 0) { force = true; }
  85296. if (force) {
  85297. this._cylinder.dispose();
  85298. }
  85299. else {
  85300. setTimeout(function () {
  85301. if (!_this._dataFetched) {
  85302. _this._cylinder.dispose();
  85303. }
  85304. }, 0);
  85305. }
  85306. };
  85307. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85308. if (impostor.mass === 0) {
  85309. return null;
  85310. }
  85311. if (!this._intersectsWithCylinder(impostor)) {
  85312. return null;
  85313. }
  85314. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85315. return null;
  85316. }
  85317. var impostorObjectCenter = impostor.getObjectCenter();
  85318. 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)
  85319. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85320. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85321. var hit = ray.intersectsMesh(impostor.object);
  85322. var contactPoint = hit.pickedPoint;
  85323. if (!contactPoint) {
  85324. return null;
  85325. }
  85326. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85327. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85328. var directionToOrigin = contactPoint.normalize();
  85329. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85330. directionToOrigin = directionToOrigin.negate();
  85331. }
  85332. // TODO: find a more physically based solution
  85333. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85334. var forceX = directionToOrigin.x * this._strength / 8;
  85335. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85336. var forceZ = directionToOrigin.z * this._strength / 8;
  85337. }
  85338. else {
  85339. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85340. var forceY = this._originTop.y * this._updraftMultiplier;
  85341. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85342. }
  85343. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85344. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85345. return { force: force, contactPoint: impostorObjectCenter };
  85346. };
  85347. PhysicsVortexEvent.prototype._tick = function () {
  85348. var _this = this;
  85349. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85350. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85351. if (!impostorForceAndContactPoint) {
  85352. return;
  85353. }
  85354. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85355. });
  85356. };
  85357. /*** Helpers ***/
  85358. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85359. if (!this._cylinder) {
  85360. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85361. height: this._height,
  85362. diameter: this._radius * 2,
  85363. }, this._scene);
  85364. this._cylinder.isVisible = false;
  85365. }
  85366. };
  85367. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85368. var impostorObject = impostor.object;
  85369. this._prepareCylinder();
  85370. this._cylinder.position = this._cylinderPosition;
  85371. return this._cylinder.intersectsMesh(impostorObject, true);
  85372. };
  85373. return PhysicsVortexEvent;
  85374. }());
  85375. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85376. /***** Enums *****/
  85377. /**
  85378. * The strenght of the force in correspondence to the distance of the affected object
  85379. */
  85380. var PhysicsRadialImpulseFalloff;
  85381. (function (PhysicsRadialImpulseFalloff) {
  85382. /** Defines that impulse is constant in strength across it's whole radius */
  85383. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85384. /** DEfines that impulse gets weaker if it's further from the origin */
  85385. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85386. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85387. /**
  85388. * The strenght of the force in correspondence to the distance of the affected object
  85389. */
  85390. var PhysicsUpdraftMode;
  85391. (function (PhysicsUpdraftMode) {
  85392. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85393. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85394. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85395. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85396. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85397. })(BABYLON || (BABYLON = {}));
  85398. //# sourceMappingURL=babylon.physicsHelper.js.map
  85399. var BABYLON;
  85400. (function (BABYLON) {
  85401. var CannonJSPlugin = /** @class */ (function () {
  85402. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85403. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85404. if (iterations === void 0) { iterations = 10; }
  85405. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85406. this.name = "CannonJSPlugin";
  85407. this._physicsMaterials = new Array();
  85408. this._fixedTimeStep = 1 / 60;
  85409. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85410. this.BJSCANNON = CANNON;
  85411. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85412. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85413. this._tmpPosition = BABYLON.Vector3.Zero();
  85414. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85415. this._tmpUnityRotation = new BABYLON.Quaternion();
  85416. if (!this.isSupported()) {
  85417. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85418. return;
  85419. }
  85420. this._extendNamespace();
  85421. this.world = new this.BJSCANNON.World();
  85422. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85423. this.world.solver.iterations = iterations;
  85424. }
  85425. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85426. this.world.gravity.copy(gravity);
  85427. };
  85428. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85429. this._fixedTimeStep = timeStep;
  85430. };
  85431. CannonJSPlugin.prototype.getTimeStep = function () {
  85432. return this._fixedTimeStep;
  85433. };
  85434. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85435. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85436. };
  85437. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85438. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85439. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85440. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85441. };
  85442. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85443. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85444. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85445. impostor.physicsBody.applyForce(impulse, worldPoint);
  85446. };
  85447. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85448. //parent-child relationship. Does this impostor has a parent impostor?
  85449. if (impostor.parent) {
  85450. if (impostor.physicsBody) {
  85451. this.removePhysicsBody(impostor);
  85452. //TODO is that needed?
  85453. impostor.forceUpdate();
  85454. }
  85455. return;
  85456. }
  85457. //should a new body be created for this impostor?
  85458. if (impostor.isBodyInitRequired()) {
  85459. var shape = this._createShape(impostor);
  85460. //unregister events, if body is being changed
  85461. var oldBody = impostor.physicsBody;
  85462. if (oldBody) {
  85463. this.removePhysicsBody(impostor);
  85464. }
  85465. //create the body and material
  85466. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85467. var bodyCreationObject = {
  85468. mass: impostor.getParam("mass"),
  85469. material: material
  85470. };
  85471. // A simple extend, in case native options were used.
  85472. var nativeOptions = impostor.getParam("nativeOptions");
  85473. for (var key in nativeOptions) {
  85474. if (nativeOptions.hasOwnProperty(key)) {
  85475. bodyCreationObject[key] = nativeOptions[key];
  85476. }
  85477. }
  85478. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85479. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85480. this.world.addEventListener("preStep", impostor.beforeStep);
  85481. this.world.addEventListener("postStep", impostor.afterStep);
  85482. impostor.physicsBody.addShape(shape);
  85483. this.world.add(impostor.physicsBody);
  85484. //try to keep the body moving in the right direction by taking old properties.
  85485. //Should be tested!
  85486. if (oldBody) {
  85487. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85488. impostor.physicsBody[param].copy(oldBody[param]);
  85489. });
  85490. }
  85491. this._processChildMeshes(impostor);
  85492. }
  85493. //now update the body's transformation
  85494. this._updatePhysicsBodyTransformation(impostor);
  85495. };
  85496. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85497. var _this = this;
  85498. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85499. var currentRotation = mainImpostor.object.rotationQuaternion;
  85500. if (meshChildren.length) {
  85501. var processMesh = function (localPosition, mesh) {
  85502. if (!currentRotation || !mesh.rotationQuaternion) {
  85503. return;
  85504. }
  85505. var childImpostor = mesh.getPhysicsImpostor();
  85506. if (childImpostor) {
  85507. var parent = childImpostor.parent;
  85508. if (parent !== mainImpostor) {
  85509. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85510. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85511. if (childImpostor.physicsBody) {
  85512. _this.removePhysicsBody(childImpostor);
  85513. childImpostor.physicsBody = null;
  85514. }
  85515. childImpostor.parent = mainImpostor;
  85516. childImpostor.resetUpdateFlags();
  85517. 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));
  85518. //Add the mass of the children.
  85519. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85520. }
  85521. }
  85522. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85523. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85524. };
  85525. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85526. }
  85527. };
  85528. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85529. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85530. this.world.removeEventListener("preStep", impostor.beforeStep);
  85531. this.world.removeEventListener("postStep", impostor.afterStep);
  85532. this.world.remove(impostor.physicsBody);
  85533. };
  85534. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85535. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85536. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85537. if (!mainBody || !connectedBody) {
  85538. return;
  85539. }
  85540. var constraint;
  85541. var jointData = impostorJoint.joint.jointData;
  85542. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85543. var constraintData = {
  85544. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85545. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85546. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85547. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85548. maxForce: jointData.nativeParams.maxForce,
  85549. collideConnected: !!jointData.collision
  85550. };
  85551. switch (impostorJoint.joint.type) {
  85552. case BABYLON.PhysicsJoint.HingeJoint:
  85553. case BABYLON.PhysicsJoint.Hinge2Joint:
  85554. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85555. break;
  85556. case BABYLON.PhysicsJoint.DistanceJoint:
  85557. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85558. break;
  85559. case BABYLON.PhysicsJoint.SpringJoint:
  85560. var springData = jointData;
  85561. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85562. restLength: springData.length,
  85563. stiffness: springData.stiffness,
  85564. damping: springData.damping,
  85565. localAnchorA: constraintData.pivotA,
  85566. localAnchorB: constraintData.pivotB
  85567. });
  85568. break;
  85569. case BABYLON.PhysicsJoint.LockJoint:
  85570. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85571. break;
  85572. case BABYLON.PhysicsJoint.PointToPointJoint:
  85573. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85574. default:
  85575. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85576. break;
  85577. }
  85578. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85579. constraint.collideConnected = !!jointData.collision;
  85580. impostorJoint.joint.physicsJoint = constraint;
  85581. //don't add spring as constraint, as it is not one.
  85582. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85583. this.world.addConstraint(constraint);
  85584. }
  85585. else {
  85586. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85587. constraint.applyForce();
  85588. });
  85589. }
  85590. };
  85591. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85592. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85593. };
  85594. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85595. var index;
  85596. var mat;
  85597. for (index = 0; index < this._physicsMaterials.length; index++) {
  85598. mat = this._physicsMaterials[index];
  85599. if (mat.friction === friction && mat.restitution === restitution) {
  85600. return mat;
  85601. }
  85602. }
  85603. var currentMat = new this.BJSCANNON.Material(name);
  85604. currentMat.friction = friction;
  85605. currentMat.restitution = restitution;
  85606. this._physicsMaterials.push(currentMat);
  85607. return currentMat;
  85608. };
  85609. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85610. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85611. };
  85612. CannonJSPlugin.prototype._createShape = function (impostor) {
  85613. var object = impostor.object;
  85614. var returnValue;
  85615. var extendSize = impostor.getObjectExtendSize();
  85616. switch (impostor.type) {
  85617. case BABYLON.PhysicsImpostor.SphereImpostor:
  85618. var radiusX = extendSize.x;
  85619. var radiusY = extendSize.y;
  85620. var radiusZ = extendSize.z;
  85621. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85622. break;
  85623. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85624. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85625. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85626. break;
  85627. case BABYLON.PhysicsImpostor.BoxImpostor:
  85628. var box = extendSize.scale(0.5);
  85629. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85630. break;
  85631. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85632. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85633. returnValue = new this.BJSCANNON.Plane();
  85634. break;
  85635. case BABYLON.PhysicsImpostor.MeshImpostor:
  85636. // should transform the vertex data to world coordinates!!
  85637. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85638. var rawFaces = object.getIndices ? object.getIndices() : [];
  85639. if (!rawVerts)
  85640. return;
  85641. // get only scale! so the object could transform correctly.
  85642. var oldPosition = object.position.clone();
  85643. var oldRotation = object.rotation && object.rotation.clone();
  85644. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85645. object.position.copyFromFloats(0, 0, 0);
  85646. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85647. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85648. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85649. var transform = object.computeWorldMatrix(true);
  85650. // convert rawVerts to object space
  85651. var temp = new Array();
  85652. var index;
  85653. for (index = 0; index < rawVerts.length; index += 3) {
  85654. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85655. }
  85656. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85657. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85658. //now set back the transformation!
  85659. object.position.copyFrom(oldPosition);
  85660. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85661. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85662. break;
  85663. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85664. var oldPosition2 = object.position.clone();
  85665. var oldRotation2 = object.rotation && object.rotation.clone();
  85666. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85667. object.position.copyFromFloats(0, 0, 0);
  85668. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85669. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85670. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85671. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85672. returnValue = this._createHeightmap(object);
  85673. object.position.copyFrom(oldPosition2);
  85674. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85675. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85676. object.computeWorldMatrix(true);
  85677. break;
  85678. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85679. returnValue = new this.BJSCANNON.Particle();
  85680. break;
  85681. }
  85682. return returnValue;
  85683. };
  85684. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85685. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85686. var transform = object.computeWorldMatrix(true);
  85687. // convert rawVerts to object space
  85688. var temp = new Array();
  85689. var index;
  85690. for (index = 0; index < pos.length; index += 3) {
  85691. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85692. }
  85693. pos = temp;
  85694. var matrix = new Array();
  85695. //For now pointDepth will not be used and will be automatically calculated.
  85696. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85697. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85698. var boundingInfo = object.getBoundingInfo();
  85699. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85700. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85701. var elementSize = dim * 2 / arraySize;
  85702. for (var i = 0; i < pos.length; i = i + 3) {
  85703. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85704. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85705. var y = -pos[i + 2] + minY;
  85706. if (!matrix[x]) {
  85707. matrix[x] = [];
  85708. }
  85709. if (!matrix[x][z]) {
  85710. matrix[x][z] = y;
  85711. }
  85712. matrix[x][z] = Math.max(y, matrix[x][z]);
  85713. }
  85714. for (var x = 0; x <= arraySize; ++x) {
  85715. if (!matrix[x]) {
  85716. var loc = 1;
  85717. while (!matrix[(x + loc) % arraySize]) {
  85718. loc++;
  85719. }
  85720. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85721. //console.log("missing x", x);
  85722. }
  85723. for (var z = 0; z <= arraySize; ++z) {
  85724. if (!matrix[x][z]) {
  85725. var loc = 1;
  85726. var newValue;
  85727. while (newValue === undefined) {
  85728. newValue = matrix[x][(z + loc++) % arraySize];
  85729. }
  85730. matrix[x][z] = newValue;
  85731. }
  85732. }
  85733. }
  85734. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85735. elementSize: elementSize
  85736. });
  85737. //For future reference, needed for body transformation
  85738. shape.minY = minY;
  85739. return shape;
  85740. };
  85741. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85742. var object = impostor.object;
  85743. //make sure it is updated...
  85744. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85745. // The delta between the mesh position and the mesh bounding box center
  85746. var bInfo = object.getBoundingInfo();
  85747. if (!bInfo)
  85748. return;
  85749. var center = impostor.getObjectCenter();
  85750. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85751. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85752. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85753. this._tmpPosition.copyFrom(center);
  85754. var quaternion = object.rotationQuaternion;
  85755. if (!quaternion) {
  85756. return;
  85757. }
  85758. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85759. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85760. //-90 DEG in X, precalculated
  85761. quaternion = quaternion.multiply(this._minus90X);
  85762. //Invert! (Precalculated, 90 deg in X)
  85763. //No need to clone. this will never change.
  85764. impostor.setDeltaRotation(this._plus90X);
  85765. }
  85766. //If it is a heightfield, if should be centered.
  85767. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85768. var mesh = object;
  85769. var boundingInfo = mesh.getBoundingInfo();
  85770. //calculate the correct body position:
  85771. var rotationQuaternion = mesh.rotationQuaternion;
  85772. mesh.rotationQuaternion = this._tmpUnityRotation;
  85773. mesh.computeWorldMatrix(true);
  85774. //get original center with no rotation
  85775. var c = center.clone();
  85776. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85777. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85778. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85779. mesh.setPreTransformMatrix(p);
  85780. mesh.computeWorldMatrix(true);
  85781. //calculate the translation
  85782. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85783. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85784. //add it inverted to the delta
  85785. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85786. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85787. //rotation is back
  85788. mesh.rotationQuaternion = rotationQuaternion;
  85789. mesh.setPreTransformMatrix(oldPivot);
  85790. mesh.computeWorldMatrix(true);
  85791. }
  85792. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85793. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85794. //this._tmpPosition.copyFrom(object.position);
  85795. }
  85796. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85797. //Now update the impostor object
  85798. impostor.physicsBody.position.copy(this._tmpPosition);
  85799. impostor.physicsBody.quaternion.copy(quaternion);
  85800. };
  85801. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85802. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85803. if (impostor.object.rotationQuaternion) {
  85804. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85805. }
  85806. };
  85807. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85808. impostor.physicsBody.position.copy(newPosition);
  85809. impostor.physicsBody.quaternion.copy(newRotation);
  85810. };
  85811. CannonJSPlugin.prototype.isSupported = function () {
  85812. return this.BJSCANNON !== undefined;
  85813. };
  85814. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85815. impostor.physicsBody.velocity.copy(velocity);
  85816. };
  85817. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85818. impostor.physicsBody.angularVelocity.copy(velocity);
  85819. };
  85820. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85821. var v = impostor.physicsBody.velocity;
  85822. if (!v) {
  85823. return null;
  85824. }
  85825. return new BABYLON.Vector3(v.x, v.y, v.z);
  85826. };
  85827. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85828. var v = impostor.physicsBody.angularVelocity;
  85829. if (!v) {
  85830. return null;
  85831. }
  85832. return new BABYLON.Vector3(v.x, v.y, v.z);
  85833. };
  85834. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85835. impostor.physicsBody.mass = mass;
  85836. impostor.physicsBody.updateMassProperties();
  85837. };
  85838. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85839. return impostor.physicsBody.mass;
  85840. };
  85841. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85842. return impostor.physicsBody.material.friction;
  85843. };
  85844. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85845. impostor.physicsBody.material.friction = friction;
  85846. };
  85847. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85848. return impostor.physicsBody.material.restitution;
  85849. };
  85850. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85851. impostor.physicsBody.material.restitution = restitution;
  85852. };
  85853. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85854. impostor.physicsBody.sleep();
  85855. };
  85856. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85857. impostor.physicsBody.wakeUp();
  85858. };
  85859. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85860. joint.physicsJoint.distance = maxDistance;
  85861. };
  85862. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85863. // if (!motorIndex) {
  85864. // joint.physicsJoint.enableMotor();
  85865. // }
  85866. // }
  85867. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85868. // if (!motorIndex) {
  85869. // joint.physicsJoint.disableMotor();
  85870. // }
  85871. // }
  85872. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85873. if (!motorIndex) {
  85874. joint.physicsJoint.enableMotor();
  85875. joint.physicsJoint.setMotorSpeed(speed);
  85876. if (maxForce) {
  85877. this.setLimit(joint, maxForce);
  85878. }
  85879. }
  85880. };
  85881. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85882. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85883. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85884. };
  85885. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85886. var body = impostor.physicsBody;
  85887. mesh.position.x = body.position.x;
  85888. mesh.position.y = body.position.y;
  85889. mesh.position.z = body.position.z;
  85890. if (mesh.rotationQuaternion) {
  85891. mesh.rotationQuaternion.x = body.quaternion.x;
  85892. mesh.rotationQuaternion.y = body.quaternion.y;
  85893. mesh.rotationQuaternion.z = body.quaternion.z;
  85894. mesh.rotationQuaternion.w = body.quaternion.w;
  85895. }
  85896. };
  85897. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85898. var shape = impostor.physicsBody.shapes[0];
  85899. return shape.boundingSphereRadius;
  85900. };
  85901. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85902. var shape = impostor.physicsBody.shapes[0];
  85903. result.x = shape.halfExtents.x * 2;
  85904. result.y = shape.halfExtents.y * 2;
  85905. result.z = shape.halfExtents.z * 2;
  85906. };
  85907. CannonJSPlugin.prototype.dispose = function () {
  85908. };
  85909. CannonJSPlugin.prototype._extendNamespace = function () {
  85910. //this will force cannon to execute at least one step when using interpolation
  85911. var step_tmp1 = new this.BJSCANNON.Vec3();
  85912. var Engine = this.BJSCANNON;
  85913. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85914. maxSubSteps = maxSubSteps || 10;
  85915. timeSinceLastCalled = timeSinceLastCalled || 0;
  85916. if (timeSinceLastCalled === 0) {
  85917. this.internalStep(dt);
  85918. this.time += dt;
  85919. }
  85920. else {
  85921. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85922. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85923. var t0 = performance.now();
  85924. for (var i = 0; i !== internalSteps; i++) {
  85925. this.internalStep(dt);
  85926. if (performance.now() - t0 > dt * 1000) {
  85927. break;
  85928. }
  85929. }
  85930. this.time += timeSinceLastCalled;
  85931. var h = this.time % dt;
  85932. var h_div_dt = h / dt;
  85933. var interpvelo = step_tmp1;
  85934. var bodies = this.bodies;
  85935. for (var j = 0; j !== bodies.length; j++) {
  85936. var b = bodies[j];
  85937. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85938. b.position.vsub(b.previousPosition, interpvelo);
  85939. interpvelo.scale(h_div_dt, interpvelo);
  85940. b.position.vadd(interpvelo, b.interpolatedPosition);
  85941. }
  85942. else {
  85943. b.interpolatedPosition.copy(b.position);
  85944. b.interpolatedQuaternion.copy(b.quaternion);
  85945. }
  85946. }
  85947. }
  85948. };
  85949. };
  85950. return CannonJSPlugin;
  85951. }());
  85952. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85953. })(BABYLON || (BABYLON = {}));
  85954. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85955. var BABYLON;
  85956. (function (BABYLON) {
  85957. var OimoJSPlugin = /** @class */ (function () {
  85958. function OimoJSPlugin(iterations) {
  85959. this.name = "OimoJSPlugin";
  85960. this._tmpImpostorsArray = [];
  85961. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85962. this.BJSOIMO = OIMO;
  85963. this.world = new this.BJSOIMO.World({
  85964. iterations: iterations
  85965. });
  85966. this.world.clear();
  85967. }
  85968. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85969. this.world.gravity.copy(gravity);
  85970. };
  85971. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85972. this.world.timeStep = timeStep;
  85973. };
  85974. OimoJSPlugin.prototype.getTimeStep = function () {
  85975. return this.world.timeStep;
  85976. };
  85977. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85978. var _this = this;
  85979. impostors.forEach(function (impostor) {
  85980. impostor.beforeStep();
  85981. });
  85982. this.world.step();
  85983. impostors.forEach(function (impostor) {
  85984. impostor.afterStep();
  85985. //update the ordered impostors array
  85986. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85987. });
  85988. //check for collisions
  85989. var contact = this.world.contacts;
  85990. while (contact !== null) {
  85991. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85992. contact = contact.next;
  85993. continue;
  85994. }
  85995. //is this body colliding with any other? get the impostor
  85996. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85997. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85998. if (!mainImpostor || !collidingImpostor) {
  85999. contact = contact.next;
  86000. continue;
  86001. }
  86002. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86003. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86004. contact = contact.next;
  86005. }
  86006. };
  86007. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86008. var mass = impostor.physicsBody.mass;
  86009. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86010. };
  86011. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86012. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86013. this.applyImpulse(impostor, force, contactPoint);
  86014. };
  86015. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86016. var _this = this;
  86017. //parent-child relationship. Does this impostor has a parent impostor?
  86018. if (impostor.parent) {
  86019. if (impostor.physicsBody) {
  86020. this.removePhysicsBody(impostor);
  86021. //TODO is that needed?
  86022. impostor.forceUpdate();
  86023. }
  86024. return;
  86025. }
  86026. if (impostor.isBodyInitRequired()) {
  86027. var bodyConfig = {
  86028. name: impostor.uniqueId,
  86029. //Oimo must have mass, also for static objects.
  86030. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86031. size: [],
  86032. type: [],
  86033. pos: [],
  86034. posShape: [],
  86035. rot: [],
  86036. rotShape: [],
  86037. move: impostor.getParam("mass") !== 0,
  86038. density: impostor.getParam("mass"),
  86039. friction: impostor.getParam("friction"),
  86040. restitution: impostor.getParam("restitution"),
  86041. //Supporting older versions of Oimo
  86042. world: this.world
  86043. };
  86044. var impostors = [impostor];
  86045. var addToArray = function (parent) {
  86046. if (!parent.getChildMeshes)
  86047. return;
  86048. parent.getChildMeshes().forEach(function (m) {
  86049. if (m.physicsImpostor) {
  86050. impostors.push(m.physicsImpostor);
  86051. //m.physicsImpostor._init();
  86052. }
  86053. });
  86054. };
  86055. addToArray(impostor.object);
  86056. var checkWithEpsilon_1 = function (value) {
  86057. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86058. };
  86059. impostors.forEach(function (i) {
  86060. if (!i.object.rotationQuaternion) {
  86061. return;
  86062. }
  86063. //get the correct bounding box
  86064. var oldQuaternion = i.object.rotationQuaternion;
  86065. var rot = oldQuaternion.toEulerAngles();
  86066. var extendSize = i.getObjectExtendSize();
  86067. var radToDeg = 57.295779513082320876;
  86068. if (i === impostor) {
  86069. var center = impostor.getObjectCenter();
  86070. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86071. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86072. //Can also use Array.prototype.push.apply
  86073. bodyConfig.pos.push(center.x);
  86074. bodyConfig.pos.push(center.y);
  86075. bodyConfig.pos.push(center.z);
  86076. bodyConfig.posShape.push(0, 0, 0);
  86077. //tmp solution
  86078. bodyConfig.rot.push(rot.x * radToDeg);
  86079. bodyConfig.rot.push(rot.y * radToDeg);
  86080. bodyConfig.rot.push(rot.z * radToDeg);
  86081. bodyConfig.rotShape.push(0, 0, 0);
  86082. }
  86083. else {
  86084. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86085. bodyConfig.posShape.push(localPosition.x);
  86086. bodyConfig.posShape.push(localPosition.y);
  86087. bodyConfig.posShape.push(localPosition.z);
  86088. bodyConfig.pos.push(0, 0, 0);
  86089. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86090. bodyConfig.rot.push(0);
  86091. bodyConfig.rot.push(0);
  86092. bodyConfig.rot.push(0);
  86093. bodyConfig.rotShape.push(rot.x * radToDeg);
  86094. bodyConfig.rotShape.push(rot.y * radToDeg);
  86095. bodyConfig.rotShape.push(rot.z * radToDeg);
  86096. }
  86097. // register mesh
  86098. switch (i.type) {
  86099. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86100. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86101. case BABYLON.PhysicsImpostor.SphereImpostor:
  86102. var radiusX = extendSize.x;
  86103. var radiusY = extendSize.y;
  86104. var radiusZ = extendSize.z;
  86105. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86106. bodyConfig.type.push('sphere');
  86107. //due to the way oimo works with compounds, add 3 times
  86108. bodyConfig.size.push(size);
  86109. bodyConfig.size.push(size);
  86110. bodyConfig.size.push(size);
  86111. break;
  86112. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86113. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86114. var sizeY = checkWithEpsilon_1(extendSize.y);
  86115. bodyConfig.type.push('cylinder');
  86116. bodyConfig.size.push(sizeX);
  86117. bodyConfig.size.push(sizeY);
  86118. //due to the way oimo works with compounds, add one more value.
  86119. bodyConfig.size.push(sizeY);
  86120. break;
  86121. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86122. case BABYLON.PhysicsImpostor.BoxImpostor:
  86123. default:
  86124. var sizeX = checkWithEpsilon_1(extendSize.x);
  86125. var sizeY = checkWithEpsilon_1(extendSize.y);
  86126. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86127. bodyConfig.type.push('box');
  86128. //if (i === impostor) {
  86129. bodyConfig.size.push(sizeX);
  86130. bodyConfig.size.push(sizeY);
  86131. bodyConfig.size.push(sizeZ);
  86132. //} else {
  86133. // bodyConfig.size.push(0,0,0);
  86134. //}
  86135. break;
  86136. }
  86137. //actually not needed, but hey...
  86138. i.object.rotationQuaternion = oldQuaternion;
  86139. });
  86140. impostor.physicsBody = this.world.add(bodyConfig);
  86141. }
  86142. else {
  86143. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86144. }
  86145. impostor.setDeltaPosition(this._tmpPositionVector);
  86146. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86147. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86148. };
  86149. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86150. //impostor.physicsBody.dispose();
  86151. //Same as : (older oimo versions)
  86152. this.world.removeRigidBody(impostor.physicsBody);
  86153. };
  86154. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86155. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86156. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86157. if (!mainBody || !connectedBody) {
  86158. return;
  86159. }
  86160. var jointData = impostorJoint.joint.jointData;
  86161. var options = jointData.nativeParams || {};
  86162. var type;
  86163. var nativeJointData = {
  86164. body1: mainBody,
  86165. body2: connectedBody,
  86166. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86167. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86168. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86169. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86170. min: options.min,
  86171. max: options.max,
  86172. collision: options.collision || jointData.collision,
  86173. spring: options.spring,
  86174. //supporting older version of Oimo
  86175. world: this.world
  86176. };
  86177. switch (impostorJoint.joint.type) {
  86178. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86179. type = "jointBall";
  86180. break;
  86181. case BABYLON.PhysicsJoint.SpringJoint:
  86182. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86183. var springData = jointData;
  86184. nativeJointData.min = springData.length || nativeJointData.min;
  86185. //Max should also be set, just make sure it is at least min
  86186. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86187. case BABYLON.PhysicsJoint.DistanceJoint:
  86188. type = "jointDistance";
  86189. nativeJointData.max = jointData.maxDistance;
  86190. break;
  86191. case BABYLON.PhysicsJoint.PrismaticJoint:
  86192. type = "jointPrisme";
  86193. break;
  86194. case BABYLON.PhysicsJoint.SliderJoint:
  86195. type = "jointSlide";
  86196. break;
  86197. case BABYLON.PhysicsJoint.WheelJoint:
  86198. type = "jointWheel";
  86199. break;
  86200. case BABYLON.PhysicsJoint.HingeJoint:
  86201. default:
  86202. type = "jointHinge";
  86203. break;
  86204. }
  86205. nativeJointData.type = type;
  86206. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86207. };
  86208. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86209. //Bug in Oimo prevents us from disposing a joint in the playground
  86210. //joint.joint.physicsJoint.dispose();
  86211. //So we will bruteforce it!
  86212. try {
  86213. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86214. }
  86215. catch (e) {
  86216. BABYLON.Tools.Warn(e);
  86217. }
  86218. };
  86219. OimoJSPlugin.prototype.isSupported = function () {
  86220. return this.BJSOIMO !== undefined;
  86221. };
  86222. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86223. if (!impostor.physicsBody.sleeping) {
  86224. //TODO check that
  86225. /*if (impostor.physicsBody.shapes.next) {
  86226. var parentShape = this._getLastShape(impostor.physicsBody);
  86227. impostor.object.position.copyFrom(parentShape.position);
  86228. console.log(parentShape.position);
  86229. } else {*/
  86230. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86231. //}
  86232. if (impostor.object.rotationQuaternion) {
  86233. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86234. }
  86235. }
  86236. };
  86237. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86238. var body = impostor.physicsBody;
  86239. body.position.copy(newPosition);
  86240. body.orientation.copy(newRotation);
  86241. body.syncShapes();
  86242. body.awake();
  86243. };
  86244. /*private _getLastShape(body: any): any {
  86245. var lastShape = body.shapes;
  86246. while (lastShape.next) {
  86247. lastShape = lastShape.next;
  86248. }
  86249. return lastShape;
  86250. }*/
  86251. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86252. impostor.physicsBody.linearVelocity.copy(velocity);
  86253. };
  86254. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86255. impostor.physicsBody.angularVelocity.copy(velocity);
  86256. };
  86257. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86258. var v = impostor.physicsBody.linearVelocity;
  86259. if (!v) {
  86260. return null;
  86261. }
  86262. return new BABYLON.Vector3(v.x, v.y, v.z);
  86263. };
  86264. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86265. var v = impostor.physicsBody.angularVelocity;
  86266. if (!v) {
  86267. return null;
  86268. }
  86269. return new BABYLON.Vector3(v.x, v.y, v.z);
  86270. };
  86271. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86272. var staticBody = mass === 0;
  86273. //this will actually set the body's density and not its mass.
  86274. //But this is how oimo treats the mass variable.
  86275. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86276. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86277. };
  86278. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86279. return impostor.physicsBody.shapes.density;
  86280. };
  86281. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86282. return impostor.physicsBody.shapes.friction;
  86283. };
  86284. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86285. impostor.physicsBody.shapes.friction = friction;
  86286. };
  86287. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86288. return impostor.physicsBody.shapes.restitution;
  86289. };
  86290. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86291. impostor.physicsBody.shapes.restitution = restitution;
  86292. };
  86293. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86294. impostor.physicsBody.sleep();
  86295. };
  86296. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86297. impostor.physicsBody.awake();
  86298. };
  86299. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86300. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86301. if (minDistance !== void 0) {
  86302. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86303. }
  86304. };
  86305. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86306. //TODO separate rotational and transational motors.
  86307. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86308. if (motor) {
  86309. motor.setMotor(speed, maxForce);
  86310. }
  86311. };
  86312. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86313. //TODO separate rotational and transational motors.
  86314. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86315. if (motor) {
  86316. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86317. }
  86318. };
  86319. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86320. var body = impostor.physicsBody;
  86321. mesh.position.x = body.position.x;
  86322. mesh.position.y = body.position.y;
  86323. mesh.position.z = body.position.z;
  86324. if (mesh.rotationQuaternion) {
  86325. mesh.rotationQuaternion.x = body.orientation.x;
  86326. mesh.rotationQuaternion.y = body.orientation.y;
  86327. mesh.rotationQuaternion.z = body.orientation.z;
  86328. mesh.rotationQuaternion.w = body.orientation.s;
  86329. }
  86330. };
  86331. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86332. return impostor.physicsBody.shapes.radius;
  86333. };
  86334. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86335. var shape = impostor.physicsBody.shapes;
  86336. result.x = shape.halfWidth * 2;
  86337. result.y = shape.halfHeight * 2;
  86338. result.z = shape.halfDepth * 2;
  86339. };
  86340. OimoJSPlugin.prototype.dispose = function () {
  86341. this.world.clear();
  86342. };
  86343. return OimoJSPlugin;
  86344. }());
  86345. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86346. })(BABYLON || (BABYLON = {}));
  86347. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86348. var BABYLON;
  86349. (function (BABYLON) {
  86350. /*
  86351. * Based on jsTGALoader - Javascript loader for TGA file
  86352. * By Vincent Thibault
  86353. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86354. */
  86355. var TGATools = /** @class */ (function () {
  86356. function TGATools() {
  86357. }
  86358. TGATools.GetTGAHeader = function (data) {
  86359. var offset = 0;
  86360. var header = {
  86361. id_length: data[offset++],
  86362. colormap_type: data[offset++],
  86363. image_type: data[offset++],
  86364. colormap_index: data[offset++] | data[offset++] << 8,
  86365. colormap_length: data[offset++] | data[offset++] << 8,
  86366. colormap_size: data[offset++],
  86367. origin: [
  86368. data[offset++] | data[offset++] << 8,
  86369. data[offset++] | data[offset++] << 8
  86370. ],
  86371. width: data[offset++] | data[offset++] << 8,
  86372. height: data[offset++] | data[offset++] << 8,
  86373. pixel_size: data[offset++],
  86374. flags: data[offset++]
  86375. };
  86376. return header;
  86377. };
  86378. TGATools.UploadContent = function (gl, data) {
  86379. // Not enough data to contain header ?
  86380. if (data.length < 19) {
  86381. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86382. return;
  86383. }
  86384. // Read Header
  86385. var offset = 18;
  86386. var header = TGATools.GetTGAHeader(data);
  86387. // Assume it's a valid Targa file.
  86388. if (header.id_length + offset > data.length) {
  86389. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86390. return;
  86391. }
  86392. // Skip not needed data
  86393. offset += header.id_length;
  86394. var use_rle = false;
  86395. var use_pal = false;
  86396. var use_grey = false;
  86397. // Get some informations.
  86398. switch (header.image_type) {
  86399. case TGATools._TYPE_RLE_INDEXED:
  86400. use_rle = true;
  86401. case TGATools._TYPE_INDEXED:
  86402. use_pal = true;
  86403. break;
  86404. case TGATools._TYPE_RLE_RGB:
  86405. use_rle = true;
  86406. case TGATools._TYPE_RGB:
  86407. // use_rgb = true;
  86408. break;
  86409. case TGATools._TYPE_RLE_GREY:
  86410. use_rle = true;
  86411. case TGATools._TYPE_GREY:
  86412. use_grey = true;
  86413. break;
  86414. }
  86415. var pixel_data;
  86416. // var numAlphaBits = header.flags & 0xf;
  86417. var pixel_size = header.pixel_size >> 3;
  86418. var pixel_total = header.width * header.height * pixel_size;
  86419. // Read palettes
  86420. var palettes;
  86421. if (use_pal) {
  86422. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86423. }
  86424. // Read LRE
  86425. if (use_rle) {
  86426. pixel_data = new Uint8Array(pixel_total);
  86427. var c, count, i;
  86428. var localOffset = 0;
  86429. var pixels = new Uint8Array(pixel_size);
  86430. while (offset < pixel_total && localOffset < pixel_total) {
  86431. c = data[offset++];
  86432. count = (c & 0x7f) + 1;
  86433. // RLE pixels
  86434. if (c & 0x80) {
  86435. // Bind pixel tmp array
  86436. for (i = 0; i < pixel_size; ++i) {
  86437. pixels[i] = data[offset++];
  86438. }
  86439. // Copy pixel array
  86440. for (i = 0; i < count; ++i) {
  86441. pixel_data.set(pixels, localOffset + i * pixel_size);
  86442. }
  86443. localOffset += pixel_size * count;
  86444. }
  86445. // Raw pixels
  86446. else {
  86447. count *= pixel_size;
  86448. for (i = 0; i < count; ++i) {
  86449. pixel_data[localOffset + i] = data[offset++];
  86450. }
  86451. localOffset += count;
  86452. }
  86453. }
  86454. }
  86455. // RAW Pixels
  86456. else {
  86457. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86458. }
  86459. // Load to texture
  86460. var x_start, y_start, x_step, y_step, y_end, x_end;
  86461. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86462. default:
  86463. case TGATools._ORIGIN_UL:
  86464. x_start = 0;
  86465. x_step = 1;
  86466. x_end = header.width;
  86467. y_start = 0;
  86468. y_step = 1;
  86469. y_end = header.height;
  86470. break;
  86471. case TGATools._ORIGIN_BL:
  86472. x_start = 0;
  86473. x_step = 1;
  86474. x_end = header.width;
  86475. y_start = header.height - 1;
  86476. y_step = -1;
  86477. y_end = -1;
  86478. break;
  86479. case TGATools._ORIGIN_UR:
  86480. x_start = header.width - 1;
  86481. x_step = -1;
  86482. x_end = -1;
  86483. y_start = 0;
  86484. y_step = 1;
  86485. y_end = header.height;
  86486. break;
  86487. case TGATools._ORIGIN_BR:
  86488. x_start = header.width - 1;
  86489. x_step = -1;
  86490. x_end = -1;
  86491. y_start = header.height - 1;
  86492. y_step = -1;
  86493. y_end = -1;
  86494. break;
  86495. }
  86496. // Load the specify method
  86497. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86498. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86499. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86500. };
  86501. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86502. var image = pixel_data, colormap = palettes;
  86503. var width = header.width, height = header.height;
  86504. var color, i = 0, x, y;
  86505. var imageData = new Uint8Array(width * height * 4);
  86506. for (y = y_start; y !== y_end; y += y_step) {
  86507. for (x = x_start; x !== x_end; x += x_step, i++) {
  86508. color = image[i];
  86509. imageData[(x + width * y) * 4 + 3] = 255;
  86510. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86511. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86512. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86513. }
  86514. }
  86515. return imageData;
  86516. };
  86517. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86518. var image = pixel_data;
  86519. var width = header.width, height = header.height;
  86520. var color, i = 0, x, y;
  86521. var imageData = new Uint8Array(width * height * 4);
  86522. for (y = y_start; y !== y_end; y += y_step) {
  86523. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86524. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86525. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86526. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86527. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86528. imageData[(x + width * y) * 4 + 0] = r;
  86529. imageData[(x + width * y) * 4 + 1] = g;
  86530. imageData[(x + width * y) * 4 + 2] = b;
  86531. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86532. }
  86533. }
  86534. return imageData;
  86535. };
  86536. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86537. var image = pixel_data;
  86538. var width = header.width, height = header.height;
  86539. var i = 0, x, y;
  86540. var imageData = new Uint8Array(width * height * 4);
  86541. for (y = y_start; y !== y_end; y += y_step) {
  86542. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86543. imageData[(x + width * y) * 4 + 3] = 255;
  86544. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86545. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86546. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86547. }
  86548. }
  86549. return imageData;
  86550. };
  86551. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86552. var image = pixel_data;
  86553. var width = header.width, height = header.height;
  86554. var i = 0, x, y;
  86555. var imageData = new Uint8Array(width * height * 4);
  86556. for (y = y_start; y !== y_end; y += y_step) {
  86557. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86558. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86559. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86560. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86561. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86562. }
  86563. }
  86564. return imageData;
  86565. };
  86566. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86567. var image = pixel_data;
  86568. var width = header.width, height = header.height;
  86569. var color, i = 0, x, y;
  86570. var imageData = new Uint8Array(width * height * 4);
  86571. for (y = y_start; y !== y_end; y += y_step) {
  86572. for (x = x_start; x !== x_end; x += x_step, i++) {
  86573. color = image[i];
  86574. imageData[(x + width * y) * 4 + 0] = color;
  86575. imageData[(x + width * y) * 4 + 1] = color;
  86576. imageData[(x + width * y) * 4 + 2] = color;
  86577. imageData[(x + width * y) * 4 + 3] = 255;
  86578. }
  86579. }
  86580. return imageData;
  86581. };
  86582. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86583. var image = pixel_data;
  86584. var width = header.width, height = header.height;
  86585. var i = 0, x, y;
  86586. var imageData = new Uint8Array(width * height * 4);
  86587. for (y = y_start; y !== y_end; y += y_step) {
  86588. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86589. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86590. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86591. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86592. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86593. }
  86594. }
  86595. return imageData;
  86596. };
  86597. //private static _TYPE_NO_DATA = 0;
  86598. TGATools._TYPE_INDEXED = 1;
  86599. TGATools._TYPE_RGB = 2;
  86600. TGATools._TYPE_GREY = 3;
  86601. TGATools._TYPE_RLE_INDEXED = 9;
  86602. TGATools._TYPE_RLE_RGB = 10;
  86603. TGATools._TYPE_RLE_GREY = 11;
  86604. TGATools._ORIGIN_MASK = 0x30;
  86605. TGATools._ORIGIN_SHIFT = 0x04;
  86606. TGATools._ORIGIN_BL = 0x00;
  86607. TGATools._ORIGIN_BR = 0x01;
  86608. TGATools._ORIGIN_UL = 0x02;
  86609. TGATools._ORIGIN_UR = 0x03;
  86610. return TGATools;
  86611. }());
  86612. BABYLON.TGATools = TGATools;
  86613. })(BABYLON || (BABYLON = {}));
  86614. //# sourceMappingURL=babylon.tga.js.map
  86615. var BABYLON;
  86616. (function (BABYLON) {
  86617. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86618. // All values and structures referenced from:
  86619. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86620. var DDS_MAGIC = 0x20534444;
  86621. var
  86622. //DDSD_CAPS = 0x1,
  86623. //DDSD_HEIGHT = 0x2,
  86624. //DDSD_WIDTH = 0x4,
  86625. //DDSD_PITCH = 0x8,
  86626. //DDSD_PIXELFORMAT = 0x1000,
  86627. DDSD_MIPMAPCOUNT = 0x20000;
  86628. //DDSD_LINEARSIZE = 0x80000,
  86629. //DDSD_DEPTH = 0x800000;
  86630. // var DDSCAPS_COMPLEX = 0x8,
  86631. // DDSCAPS_MIPMAP = 0x400000,
  86632. // DDSCAPS_TEXTURE = 0x1000;
  86633. var DDSCAPS2_CUBEMAP = 0x200;
  86634. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86635. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86636. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86637. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86638. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86639. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86640. // DDSCAPS2_VOLUME = 0x200000;
  86641. var
  86642. //DDPF_ALPHAPIXELS = 0x1,
  86643. //DDPF_ALPHA = 0x2,
  86644. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86645. //DDPF_YUV = 0x200,
  86646. DDPF_LUMINANCE = 0x20000;
  86647. function FourCCToInt32(value) {
  86648. return value.charCodeAt(0) +
  86649. (value.charCodeAt(1) << 8) +
  86650. (value.charCodeAt(2) << 16) +
  86651. (value.charCodeAt(3) << 24);
  86652. }
  86653. function Int32ToFourCC(value) {
  86654. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86655. }
  86656. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86657. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86658. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86659. var FOURCC_DX10 = FourCCToInt32("DX10");
  86660. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86661. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86662. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86663. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86664. var headerLengthInt = 31; // The header length in 32 bit ints
  86665. // Offsets into the header array
  86666. var off_magic = 0;
  86667. var off_size = 1;
  86668. var off_flags = 2;
  86669. var off_height = 3;
  86670. var off_width = 4;
  86671. var off_mipmapCount = 7;
  86672. var off_pfFlags = 20;
  86673. var off_pfFourCC = 21;
  86674. var off_RGBbpp = 22;
  86675. var off_RMask = 23;
  86676. var off_GMask = 24;
  86677. var off_BMask = 25;
  86678. var off_AMask = 26;
  86679. // var off_caps1 = 27;
  86680. var off_caps2 = 28;
  86681. // var off_caps3 = 29;
  86682. // var off_caps4 = 30;
  86683. var off_dxgiFormat = 32;
  86684. ;
  86685. var DDSTools = /** @class */ (function () {
  86686. function DDSTools() {
  86687. }
  86688. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86689. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86690. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86691. var mipmapCount = 1;
  86692. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86693. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86694. }
  86695. var fourCC = header[off_pfFourCC];
  86696. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86697. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86698. switch (fourCC) {
  86699. case FOURCC_D3DFMT_R16G16B16A16F:
  86700. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86701. break;
  86702. case FOURCC_D3DFMT_R32G32B32A32F:
  86703. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86704. break;
  86705. case FOURCC_DX10:
  86706. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86707. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86708. break;
  86709. }
  86710. }
  86711. return {
  86712. width: header[off_width],
  86713. height: header[off_height],
  86714. mipmapCount: mipmapCount,
  86715. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86716. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86717. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86718. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86719. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86720. dxgiFormat: dxgiFormat,
  86721. textureType: textureType
  86722. };
  86723. };
  86724. DDSTools._ToHalfFloat = function (value) {
  86725. if (!DDSTools._FloatView) {
  86726. DDSTools._FloatView = new Float32Array(1);
  86727. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86728. }
  86729. DDSTools._FloatView[0] = value;
  86730. var x = DDSTools._Int32View[0];
  86731. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86732. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86733. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86734. /* If zero, or denormal, or exponent underflows too much for a denormal
  86735. * half, return signed zero. */
  86736. if (e < 103) {
  86737. return bits;
  86738. }
  86739. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86740. if (e > 142) {
  86741. bits |= 0x7c00;
  86742. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86743. * not Inf, so make sure we set one mantissa bit too. */
  86744. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86745. return bits;
  86746. }
  86747. /* If exponent underflows but not too much, return a denormal */
  86748. if (e < 113) {
  86749. m |= 0x0800;
  86750. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86751. * to 1, which is OK. */
  86752. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86753. return bits;
  86754. }
  86755. bits |= ((e - 112) << 10) | (m >> 1);
  86756. bits += m & 1;
  86757. return bits;
  86758. };
  86759. DDSTools._FromHalfFloat = function (value) {
  86760. var s = (value & 0x8000) >> 15;
  86761. var e = (value & 0x7C00) >> 10;
  86762. var f = value & 0x03FF;
  86763. if (e === 0) {
  86764. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86765. }
  86766. else if (e == 0x1F) {
  86767. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86768. }
  86769. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86770. };
  86771. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86772. var destArray = new Float32Array(dataLength);
  86773. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86774. var index = 0;
  86775. for (var y = 0; y < height; y++) {
  86776. for (var x = 0; x < width; x++) {
  86777. var srcPos = (x + y * width) * 4;
  86778. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86779. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86780. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86781. if (DDSTools.StoreLODInAlphaChannel) {
  86782. destArray[index + 3] = lod;
  86783. }
  86784. else {
  86785. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86786. }
  86787. index += 4;
  86788. }
  86789. }
  86790. return destArray;
  86791. };
  86792. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86793. if (DDSTools.StoreLODInAlphaChannel) {
  86794. var destArray = new Uint16Array(dataLength);
  86795. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86796. var index = 0;
  86797. for (var y = 0; y < height; y++) {
  86798. for (var x = 0; x < width; x++) {
  86799. var srcPos = (x + y * width) * 4;
  86800. destArray[index] = srcData[srcPos];
  86801. destArray[index + 1] = srcData[srcPos + 1];
  86802. destArray[index + 2] = srcData[srcPos + 2];
  86803. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86804. index += 4;
  86805. }
  86806. }
  86807. return destArray;
  86808. }
  86809. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86810. };
  86811. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86812. if (DDSTools.StoreLODInAlphaChannel) {
  86813. var destArray = new Float32Array(dataLength);
  86814. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86815. var index = 0;
  86816. for (var y = 0; y < height; y++) {
  86817. for (var x = 0; x < width; x++) {
  86818. var srcPos = (x + y * width) * 4;
  86819. destArray[index] = srcData[srcPos];
  86820. destArray[index + 1] = srcData[srcPos + 1];
  86821. destArray[index + 2] = srcData[srcPos + 2];
  86822. destArray[index + 3] = lod;
  86823. index += 4;
  86824. }
  86825. }
  86826. return destArray;
  86827. }
  86828. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86829. };
  86830. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86831. var destArray = new Uint8Array(dataLength);
  86832. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86833. var index = 0;
  86834. for (var y = 0; y < height; y++) {
  86835. for (var x = 0; x < width; x++) {
  86836. var srcPos = (x + y * width) * 4;
  86837. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86838. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86839. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86840. if (DDSTools.StoreLODInAlphaChannel) {
  86841. destArray[index + 3] = lod;
  86842. }
  86843. else {
  86844. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86845. }
  86846. index += 4;
  86847. }
  86848. }
  86849. return destArray;
  86850. };
  86851. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86852. var destArray = new Uint8Array(dataLength);
  86853. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86854. var index = 0;
  86855. for (var y = 0; y < height; y++) {
  86856. for (var x = 0; x < width; x++) {
  86857. var srcPos = (x + y * width) * 4;
  86858. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86859. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86860. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86861. if (DDSTools.StoreLODInAlphaChannel) {
  86862. destArray[index + 3] = lod;
  86863. }
  86864. else {
  86865. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86866. }
  86867. index += 4;
  86868. }
  86869. }
  86870. return destArray;
  86871. };
  86872. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86873. var byteArray = new Uint8Array(dataLength);
  86874. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86875. var index = 0;
  86876. for (var y = 0; y < height; y++) {
  86877. for (var x = 0; x < width; x++) {
  86878. var srcPos = (x + y * width) * 4;
  86879. byteArray[index] = srcData[srcPos + rOffset];
  86880. byteArray[index + 1] = srcData[srcPos + gOffset];
  86881. byteArray[index + 2] = srcData[srcPos + bOffset];
  86882. byteArray[index + 3] = srcData[srcPos + aOffset];
  86883. index += 4;
  86884. }
  86885. }
  86886. return byteArray;
  86887. };
  86888. DDSTools._ExtractLongWordOrder = function (value) {
  86889. if (value === 0 || value === 255 || value === -16777216) {
  86890. return 0;
  86891. }
  86892. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86893. };
  86894. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86895. var byteArray = new Uint8Array(dataLength);
  86896. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86897. var index = 0;
  86898. for (var y = 0; y < height; y++) {
  86899. for (var x = 0; x < width; x++) {
  86900. var srcPos = (x + y * width) * 3;
  86901. byteArray[index] = srcData[srcPos + rOffset];
  86902. byteArray[index + 1] = srcData[srcPos + gOffset];
  86903. byteArray[index + 2] = srcData[srcPos + bOffset];
  86904. index += 3;
  86905. }
  86906. }
  86907. return byteArray;
  86908. };
  86909. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86910. var byteArray = new Uint8Array(dataLength);
  86911. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86912. var index = 0;
  86913. for (var y = 0; y < height; y++) {
  86914. for (var x = 0; x < width; x++) {
  86915. var srcPos = (x + y * width);
  86916. byteArray[index] = srcData[srcPos];
  86917. index++;
  86918. }
  86919. }
  86920. return byteArray;
  86921. };
  86922. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86923. if (lodIndex === void 0) { lodIndex = -1; }
  86924. var sphericalPolynomialFaces = null;
  86925. if (info.sphericalPolynomial) {
  86926. sphericalPolynomialFaces = new Array();
  86927. }
  86928. var ext = engine.getCaps().s3tc;
  86929. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86930. var fourCC, width, height, dataLength = 0, dataOffset;
  86931. var byteArray, mipmapCount, mip;
  86932. var internalFormat = 0;
  86933. var format = 0;
  86934. var blockBytes = 1;
  86935. if (header[off_magic] !== DDS_MAGIC) {
  86936. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86937. return;
  86938. }
  86939. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86940. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86941. return;
  86942. }
  86943. if (info.isCompressed && !ext) {
  86944. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86945. return;
  86946. }
  86947. var bpp = header[off_RGBbpp];
  86948. dataOffset = header[off_size] + 4;
  86949. var computeFormats = false;
  86950. if (info.isFourCC) {
  86951. fourCC = header[off_pfFourCC];
  86952. switch (fourCC) {
  86953. case FOURCC_DXT1:
  86954. blockBytes = 8;
  86955. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86956. break;
  86957. case FOURCC_DXT3:
  86958. blockBytes = 16;
  86959. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86960. break;
  86961. case FOURCC_DXT5:
  86962. blockBytes = 16;
  86963. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86964. break;
  86965. case FOURCC_D3DFMT_R16G16B16A16F:
  86966. computeFormats = true;
  86967. break;
  86968. case FOURCC_D3DFMT_R32G32B32A32F:
  86969. computeFormats = true;
  86970. break;
  86971. case FOURCC_DX10:
  86972. // There is an additionnal header so dataOffset need to be changed
  86973. dataOffset += 5 * 4; // 5 uints
  86974. var supported = false;
  86975. switch (info.dxgiFormat) {
  86976. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86977. computeFormats = true;
  86978. supported = true;
  86979. break;
  86980. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86981. info.isRGB = true;
  86982. info.isFourCC = false;
  86983. bpp = 32;
  86984. supported = true;
  86985. break;
  86986. }
  86987. if (supported) {
  86988. break;
  86989. }
  86990. default:
  86991. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86992. return;
  86993. }
  86994. }
  86995. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86996. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86997. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86998. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86999. if (computeFormats) {
  87000. format = engine._getWebGLTextureType(info.textureType);
  87001. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87002. }
  87003. mipmapCount = 1;
  87004. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87005. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87006. }
  87007. for (var face = 0; face < faces; face++) {
  87008. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87009. width = header[off_width];
  87010. height = header[off_height];
  87011. for (mip = 0; mip < mipmapCount; ++mip) {
  87012. if (lodIndex === -1 || lodIndex === mip) {
  87013. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87014. var i = (lodIndex === -1) ? mip : 0;
  87015. if (!info.isCompressed && info.isFourCC) {
  87016. dataLength = width * height * 4;
  87017. var floatArray = null;
  87018. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87019. if (bpp === 128) {
  87020. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87021. if (sphericalPolynomialFaces && i == 0) {
  87022. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87023. }
  87024. }
  87025. else if (bpp === 64) {
  87026. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87027. if (sphericalPolynomialFaces && i == 0) {
  87028. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87029. }
  87030. }
  87031. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87032. format = engine._getWebGLTextureType(info.textureType);
  87033. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87034. }
  87035. else {
  87036. if (bpp === 128) {
  87037. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87038. if (sphericalPolynomialFaces && i == 0) {
  87039. sphericalPolynomialFaces.push(floatArray);
  87040. }
  87041. }
  87042. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87043. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87044. if (sphericalPolynomialFaces && i == 0) {
  87045. sphericalPolynomialFaces.push(floatArray);
  87046. }
  87047. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87048. format = engine._getWebGLTextureType(info.textureType);
  87049. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87050. }
  87051. else { // 64
  87052. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87053. if (sphericalPolynomialFaces && i == 0) {
  87054. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87055. }
  87056. }
  87057. }
  87058. if (floatArray) {
  87059. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87060. }
  87061. }
  87062. else if (info.isRGB) {
  87063. if (bpp === 24) {
  87064. dataLength = width * height * 3;
  87065. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87066. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87067. }
  87068. else { // 32
  87069. dataLength = width * height * 4;
  87070. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87071. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87072. }
  87073. }
  87074. else if (info.isLuminance) {
  87075. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87076. var unpaddedRowSize = width;
  87077. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87078. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87079. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87080. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87081. }
  87082. else {
  87083. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87084. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87085. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87086. }
  87087. }
  87088. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87089. width *= 0.5;
  87090. height *= 0.5;
  87091. width = Math.max(1.0, width);
  87092. height = Math.max(1.0, height);
  87093. }
  87094. if (currentFace !== undefined) {
  87095. // Loading a single face
  87096. break;
  87097. }
  87098. }
  87099. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87100. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87101. size: header[off_width],
  87102. right: sphericalPolynomialFaces[0],
  87103. left: sphericalPolynomialFaces[1],
  87104. up: sphericalPolynomialFaces[2],
  87105. down: sphericalPolynomialFaces[3],
  87106. front: sphericalPolynomialFaces[4],
  87107. back: sphericalPolynomialFaces[5],
  87108. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87109. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87110. gammaSpace: false,
  87111. });
  87112. }
  87113. else {
  87114. info.sphericalPolynomial = undefined;
  87115. }
  87116. };
  87117. DDSTools.StoreLODInAlphaChannel = false;
  87118. return DDSTools;
  87119. }());
  87120. BABYLON.DDSTools = DDSTools;
  87121. })(BABYLON || (BABYLON = {}));
  87122. //# sourceMappingURL=babylon.dds.js.map
  87123. var BABYLON;
  87124. (function (BABYLON) {
  87125. /**
  87126. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87127. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87128. */
  87129. var KhronosTextureContainer = /** @class */ (function () {
  87130. /**
  87131. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87132. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87133. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87134. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87135. */
  87136. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87137. this.arrayBuffer = arrayBuffer;
  87138. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87139. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87140. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87141. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87142. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87143. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87144. BABYLON.Tools.Error("texture missing KTX identifier");
  87145. return;
  87146. }
  87147. // load the reset of the header in native 32 bit int
  87148. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87149. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87150. var oppositeEndianess = header[0] === 0x01020304;
  87151. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87152. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87153. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87154. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87155. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87156. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87157. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87158. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87159. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87160. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87161. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87162. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87163. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87164. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87165. if (this.glType !== 0) {
  87166. BABYLON.Tools.Error("only compressed formats currently supported");
  87167. return;
  87168. }
  87169. else {
  87170. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87171. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87172. }
  87173. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87174. BABYLON.Tools.Error("only 2D textures currently supported");
  87175. return;
  87176. }
  87177. if (this.numberOfArrayElements !== 0) {
  87178. BABYLON.Tools.Error("texture arrays not currently supported");
  87179. return;
  87180. }
  87181. if (this.numberOfFaces !== facesExpected) {
  87182. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87183. return;
  87184. }
  87185. // we now have a completely validated file, so could use existence of loadType as success
  87186. // would need to make this more elaborate & adjust checks above to support more than one load type
  87187. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87188. }
  87189. // not as fast hardware based, but will probably never need to use
  87190. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87191. return ((val & 0xFF) << 24)
  87192. | ((val & 0xFF00) << 8)
  87193. | ((val >> 8) & 0xFF00)
  87194. | ((val >> 24) & 0xFF);
  87195. };
  87196. /**
  87197. * It is assumed that the texture has already been created & is currently bound
  87198. */
  87199. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87200. switch (this.loadType) {
  87201. case KhronosTextureContainer.COMPRESSED_2D:
  87202. this._upload2DCompressedLevels(gl, loadMipmaps);
  87203. break;
  87204. case KhronosTextureContainer.TEX_2D:
  87205. case KhronosTextureContainer.COMPRESSED_3D:
  87206. case KhronosTextureContainer.TEX_3D:
  87207. }
  87208. };
  87209. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87210. // initialize width & height for level 1
  87211. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87212. var width = this.pixelWidth;
  87213. var height = this.pixelHeight;
  87214. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87215. for (var level = 0; level < mipmapCount; level++) {
  87216. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87217. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87218. for (var face = 0; face < this.numberOfFaces; face++) {
  87219. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87220. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87221. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87222. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87223. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87224. }
  87225. width = Math.max(1.0, width * 0.5);
  87226. height = Math.max(1.0, height * 0.5);
  87227. }
  87228. };
  87229. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87230. // load types
  87231. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87232. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87233. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87234. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87235. return KhronosTextureContainer;
  87236. }());
  87237. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87238. })(BABYLON || (BABYLON = {}));
  87239. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87240. var BABYLON;
  87241. (function (BABYLON) {
  87242. var Debug;
  87243. (function (Debug) {
  87244. /**
  87245. * Class used to render a debug view of a given skeleton
  87246. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87247. */
  87248. var SkeletonViewer = /** @class */ (function () {
  87249. /**
  87250. * Creates a new SkeletonViewer
  87251. * @param skeleton defines the skeleton to render
  87252. * @param mesh defines the mesh attached to the skeleton
  87253. * @param scene defines the hosting scene
  87254. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87255. * @param renderingGroupId defines the rendering group id to use with the viewer
  87256. */
  87257. function SkeletonViewer(
  87258. /** defines the skeleton to render */
  87259. skeleton,
  87260. /** defines the mesh attached to the skeleton */
  87261. mesh, scene,
  87262. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87263. autoUpdateBonesMatrices,
  87264. /** defines the rendering group id to use with the viewer */
  87265. renderingGroupId) {
  87266. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87267. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87268. this.skeleton = skeleton;
  87269. this.mesh = mesh;
  87270. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87271. this.renderingGroupId = renderingGroupId;
  87272. /** Gets or sets the color used to render the skeleton */
  87273. this.color = BABYLON.Color3.White();
  87274. this._debugLines = new Array();
  87275. this._isEnabled = false;
  87276. this._scene = scene;
  87277. this.update();
  87278. this._renderFunction = this.update.bind(this);
  87279. }
  87280. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87281. get: function () {
  87282. return this._isEnabled;
  87283. },
  87284. /** Gets or sets a boolean indicating if the viewer is enabled */
  87285. set: function (value) {
  87286. if (this._isEnabled === value) {
  87287. return;
  87288. }
  87289. this._isEnabled = value;
  87290. if (value) {
  87291. this._scene.registerBeforeRender(this._renderFunction);
  87292. }
  87293. else {
  87294. this._scene.unregisterBeforeRender(this._renderFunction);
  87295. }
  87296. },
  87297. enumerable: true,
  87298. configurable: true
  87299. });
  87300. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87301. if (x === void 0) { x = 0; }
  87302. if (y === void 0) { y = 0; }
  87303. if (z === void 0) { z = 0; }
  87304. var tmat = BABYLON.Tmp.Matrix[0];
  87305. var parentBone = bone.getParent();
  87306. tmat.copyFrom(bone.getLocalMatrix());
  87307. if (x !== 0 || y !== 0 || z !== 0) {
  87308. var tmat2 = BABYLON.Tmp.Matrix[1];
  87309. BABYLON.Matrix.IdentityToRef(tmat2);
  87310. tmat2.m[12] = x;
  87311. tmat2.m[13] = y;
  87312. tmat2.m[14] = z;
  87313. tmat2.multiplyToRef(tmat, tmat);
  87314. }
  87315. if (parentBone) {
  87316. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87317. }
  87318. tmat.multiplyToRef(meshMat, tmat);
  87319. position.x = tmat.m[12];
  87320. position.y = tmat.m[13];
  87321. position.z = tmat.m[14];
  87322. };
  87323. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87324. var len = bones.length;
  87325. var meshPos = this.mesh.position;
  87326. for (var i = 0; i < len; i++) {
  87327. var bone = bones[i];
  87328. var points = this._debugLines[i];
  87329. if (!points) {
  87330. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87331. this._debugLines[i] = points;
  87332. }
  87333. this._getBonePosition(points[0], bone, meshMat);
  87334. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87335. points[0].subtractInPlace(meshPos);
  87336. points[1].subtractInPlace(meshPos);
  87337. }
  87338. };
  87339. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87340. var len = bones.length;
  87341. var boneNum = 0;
  87342. var meshPos = this.mesh.position;
  87343. for (var i = len - 1; i >= 0; i--) {
  87344. var childBone = bones[i];
  87345. var parentBone = childBone.getParent();
  87346. if (!parentBone) {
  87347. continue;
  87348. }
  87349. var points = this._debugLines[boneNum];
  87350. if (!points) {
  87351. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87352. this._debugLines[boneNum] = points;
  87353. }
  87354. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87355. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87356. points[0].subtractInPlace(meshPos);
  87357. points[1].subtractInPlace(meshPos);
  87358. boneNum++;
  87359. }
  87360. };
  87361. /** Update the viewer to sync with current skeleton state */
  87362. SkeletonViewer.prototype.update = function () {
  87363. if (this.autoUpdateBonesMatrices) {
  87364. this.skeleton.computeAbsoluteTransforms();
  87365. }
  87366. if (this.skeleton.bones[0].length === undefined) {
  87367. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87368. }
  87369. else {
  87370. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87371. }
  87372. if (!this._debugMesh) {
  87373. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87374. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87375. }
  87376. else {
  87377. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87378. }
  87379. this._debugMesh.position.copyFrom(this.mesh.position);
  87380. this._debugMesh.color = this.color;
  87381. };
  87382. /** Release associated resources */
  87383. SkeletonViewer.prototype.dispose = function () {
  87384. if (this._debugMesh) {
  87385. this.isEnabled = false;
  87386. this._debugMesh.dispose();
  87387. this._debugMesh = null;
  87388. }
  87389. };
  87390. return SkeletonViewer;
  87391. }());
  87392. Debug.SkeletonViewer = SkeletonViewer;
  87393. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87394. })(BABYLON || (BABYLON = {}));
  87395. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87396. /**
  87397. * Module Debug contains the (visual) components to debug a scene correctly
  87398. */
  87399. var BABYLON;
  87400. (function (BABYLON) {
  87401. var Debug;
  87402. (function (Debug) {
  87403. /**
  87404. * The Axes viewer will show 3 axes in a specific point in space
  87405. */
  87406. var AxesViewer = /** @class */ (function () {
  87407. /**
  87408. * Creates a new AxesViewer
  87409. * @param scene defines the hosting scene
  87410. * @param scaleLines defines a number used to scale line length (1 by default)
  87411. */
  87412. function AxesViewer(scene, scaleLines) {
  87413. if (scaleLines === void 0) { scaleLines = 1; }
  87414. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87415. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87416. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87417. /**
  87418. * Gets or sets a number used to scale line length
  87419. */
  87420. this.scaleLines = 1;
  87421. this.scaleLines = scaleLines;
  87422. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87423. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87424. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87425. this._xmesh.renderingGroupId = 2;
  87426. this._ymesh.renderingGroupId = 2;
  87427. this._zmesh.renderingGroupId = 2;
  87428. this._xmesh.material.checkReadyOnlyOnce = true;
  87429. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87430. this._ymesh.material.checkReadyOnlyOnce = true;
  87431. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87432. this._zmesh.material.checkReadyOnlyOnce = true;
  87433. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87434. this.scene = scene;
  87435. }
  87436. /**
  87437. * Force the viewer to update
  87438. * @param position defines the position of the viewer
  87439. * @param xaxis defines the x axis of the viewer
  87440. * @param yaxis defines the y axis of the viewer
  87441. * @param zaxis defines the z axis of the viewer
  87442. */
  87443. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87444. var scaleLines = this.scaleLines;
  87445. if (this._xmesh) {
  87446. this._xmesh.position.copyFrom(position);
  87447. }
  87448. if (this._ymesh) {
  87449. this._ymesh.position.copyFrom(position);
  87450. }
  87451. if (this._zmesh) {
  87452. this._zmesh.position.copyFrom(position);
  87453. }
  87454. var point2 = this._xline[1];
  87455. point2.x = xaxis.x * scaleLines;
  87456. point2.y = xaxis.y * scaleLines;
  87457. point2.z = xaxis.z * scaleLines;
  87458. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87459. point2 = this._yline[1];
  87460. point2.x = yaxis.x * scaleLines;
  87461. point2.y = yaxis.y * scaleLines;
  87462. point2.z = yaxis.z * scaleLines;
  87463. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87464. point2 = this._zline[1];
  87465. point2.x = zaxis.x * scaleLines;
  87466. point2.y = zaxis.y * scaleLines;
  87467. point2.z = zaxis.z * scaleLines;
  87468. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87469. };
  87470. /** Releases resources */
  87471. AxesViewer.prototype.dispose = function () {
  87472. if (this._xmesh) {
  87473. this._xmesh.dispose();
  87474. }
  87475. if (this._ymesh) {
  87476. this._ymesh.dispose();
  87477. }
  87478. if (this._zmesh) {
  87479. this._zmesh.dispose();
  87480. }
  87481. this._xmesh = null;
  87482. this._ymesh = null;
  87483. this._zmesh = null;
  87484. this.scene = null;
  87485. };
  87486. return AxesViewer;
  87487. }());
  87488. Debug.AxesViewer = AxesViewer;
  87489. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87490. })(BABYLON || (BABYLON = {}));
  87491. //# sourceMappingURL=babylon.axesViewer.js.map
  87492. var BABYLON;
  87493. (function (BABYLON) {
  87494. var Debug;
  87495. (function (Debug) {
  87496. /**
  87497. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87498. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87499. */
  87500. var BoneAxesViewer = /** @class */ (function (_super) {
  87501. __extends(BoneAxesViewer, _super);
  87502. /**
  87503. * Creates a new BoneAxesViewer
  87504. * @param scene defines the hosting scene
  87505. * @param bone defines the target bone
  87506. * @param mesh defines the target mesh
  87507. * @param scaleLines defines a scaling factor for line length (1 by default)
  87508. */
  87509. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87510. if (scaleLines === void 0) { scaleLines = 1; }
  87511. var _this = _super.call(this, scene, scaleLines) || this;
  87512. /** Gets current position */
  87513. _this.pos = BABYLON.Vector3.Zero();
  87514. /** Gets direction of X axis */
  87515. _this.xaxis = BABYLON.Vector3.Zero();
  87516. /** Gets direction of Y axis */
  87517. _this.yaxis = BABYLON.Vector3.Zero();
  87518. /** Gets direction of Z axis */
  87519. _this.zaxis = BABYLON.Vector3.Zero();
  87520. _this.mesh = mesh;
  87521. _this.bone = bone;
  87522. return _this;
  87523. }
  87524. /**
  87525. * Force the viewer to update
  87526. */
  87527. BoneAxesViewer.prototype.update = function () {
  87528. if (!this.mesh || !this.bone) {
  87529. return;
  87530. }
  87531. var bone = this.bone;
  87532. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87533. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87534. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87535. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87536. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87537. };
  87538. /** Releases resources */
  87539. BoneAxesViewer.prototype.dispose = function () {
  87540. if (this.mesh) {
  87541. this.mesh = null;
  87542. this.bone = null;
  87543. _super.prototype.dispose.call(this);
  87544. }
  87545. };
  87546. return BoneAxesViewer;
  87547. }(Debug.AxesViewer));
  87548. Debug.BoneAxesViewer = BoneAxesViewer;
  87549. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87550. })(BABYLON || (BABYLON = {}));
  87551. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87552. var BABYLON;
  87553. (function (BABYLON) {
  87554. var RayHelper = /** @class */ (function () {
  87555. function RayHelper(ray) {
  87556. this.ray = ray;
  87557. }
  87558. RayHelper.CreateAndShow = function (ray, scene, color) {
  87559. var helper = new RayHelper(ray);
  87560. helper.show(scene, color);
  87561. return helper;
  87562. };
  87563. RayHelper.prototype.show = function (scene, color) {
  87564. if (!this._renderFunction && this.ray) {
  87565. var ray = this.ray;
  87566. this._renderFunction = this._render.bind(this);
  87567. this._scene = scene;
  87568. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87569. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87570. if (this._renderFunction) {
  87571. this._scene.registerBeforeRender(this._renderFunction);
  87572. }
  87573. }
  87574. if (color && this._renderLine) {
  87575. this._renderLine.color.copyFrom(color);
  87576. }
  87577. };
  87578. RayHelper.prototype.hide = function () {
  87579. if (this._renderFunction && this._scene) {
  87580. this._scene.unregisterBeforeRender(this._renderFunction);
  87581. this._scene = null;
  87582. this._renderFunction = null;
  87583. if (this._renderLine) {
  87584. this._renderLine.dispose();
  87585. this._renderLine = null;
  87586. }
  87587. this._renderPoints = [];
  87588. }
  87589. };
  87590. RayHelper.prototype._render = function () {
  87591. var ray = this.ray;
  87592. if (!ray) {
  87593. return;
  87594. }
  87595. var point = this._renderPoints[1];
  87596. var len = Math.min(ray.length, 1000000);
  87597. point.copyFrom(ray.direction);
  87598. point.scaleInPlace(len);
  87599. point.addInPlace(ray.origin);
  87600. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87601. };
  87602. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87603. this._attachedToMesh = mesh;
  87604. var ray = this.ray;
  87605. if (!ray) {
  87606. return;
  87607. }
  87608. if (!ray.direction) {
  87609. ray.direction = BABYLON.Vector3.Zero();
  87610. }
  87611. if (!ray.origin) {
  87612. ray.origin = BABYLON.Vector3.Zero();
  87613. }
  87614. if (length) {
  87615. ray.length = length;
  87616. }
  87617. if (!meshSpaceOrigin) {
  87618. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87619. }
  87620. if (!meshSpaceDirection) {
  87621. // -1 so that this will work with Mesh.lookAt
  87622. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87623. }
  87624. if (!this._meshSpaceDirection) {
  87625. this._meshSpaceDirection = meshSpaceDirection.clone();
  87626. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87627. }
  87628. else {
  87629. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87630. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87631. }
  87632. if (!this._updateToMeshFunction) {
  87633. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87634. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87635. }
  87636. this._updateToMesh();
  87637. };
  87638. RayHelper.prototype.detachFromMesh = function () {
  87639. if (this._attachedToMesh) {
  87640. if (this._updateToMeshFunction) {
  87641. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87642. }
  87643. this._attachedToMesh = null;
  87644. this._updateToMeshFunction = null;
  87645. }
  87646. };
  87647. RayHelper.prototype._updateToMesh = function () {
  87648. var ray = this.ray;
  87649. if (!this._attachedToMesh || !ray) {
  87650. return;
  87651. }
  87652. if (this._attachedToMesh._isDisposed) {
  87653. this.detachFromMesh();
  87654. return;
  87655. }
  87656. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87657. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87658. };
  87659. RayHelper.prototype.dispose = function () {
  87660. this.hide();
  87661. this.detachFromMesh();
  87662. this.ray = null;
  87663. };
  87664. return RayHelper;
  87665. }());
  87666. BABYLON.RayHelper = RayHelper;
  87667. })(BABYLON || (BABYLON = {}));
  87668. //# sourceMappingURL=babylon.rayHelper.js.map
  87669. var BABYLON;
  87670. (function (BABYLON) {
  87671. // load the inspector using require, if not present in the global namespace.
  87672. var DebugLayer = /** @class */ (function () {
  87673. function DebugLayer(scene) {
  87674. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87675. this._scene = scene;
  87676. // load inspector using require, if it doesn't exist on the global namespace.
  87677. }
  87678. /** Creates the inspector window. */
  87679. DebugLayer.prototype._createInspector = function (config) {
  87680. if (config === void 0) { config = {}; }
  87681. var popup = config.popup || false;
  87682. var initialTab = config.initialTab || 0;
  87683. var parentElement = config.parentElement || null;
  87684. if (!this._inspector) {
  87685. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87686. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87687. } // else nothing to do,; instance is already existing
  87688. };
  87689. DebugLayer.prototype.isVisible = function () {
  87690. if (!this._inspector) {
  87691. return false;
  87692. }
  87693. return true;
  87694. };
  87695. DebugLayer.prototype.hide = function () {
  87696. if (this._inspector) {
  87697. try {
  87698. this._inspector.dispose();
  87699. }
  87700. catch (e) {
  87701. // If the inspector has been removed directly from the inspector tool
  87702. }
  87703. this.onPropertyChangedObservable.clear();
  87704. this._inspector = null;
  87705. }
  87706. };
  87707. /**
  87708. *
  87709. * Launch the debugLayer.
  87710. *
  87711. * initialTab:
  87712. * | Value | Tab Name |
  87713. * | --- | --- |
  87714. * | 0 | Scene |
  87715. * | 1 | Console |
  87716. * | 2 | Stats |
  87717. * | 3 | Textures |
  87718. * | 4 | Mesh |
  87719. * | 5 | Light |
  87720. * | 6 | Material |
  87721. * | 7 | GLTF |
  87722. * | 8 | GUI |
  87723. * | 9 | Physics |
  87724. * | 10 | Camera |
  87725. * | 11 | Audio |
  87726. *
  87727. */
  87728. DebugLayer.prototype.show = function (config) {
  87729. if (config === void 0) { config = {}; }
  87730. if (typeof this.BJSINSPECTOR == 'undefined') {
  87731. // Load inspector and add it to the DOM
  87732. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87733. }
  87734. else {
  87735. // Otherwise creates the inspector
  87736. this._createInspector(config);
  87737. this.onPropertyChangedObservable = new BABYLON.Observable();
  87738. }
  87739. };
  87740. /**
  87741. * Gets the active tab
  87742. * @return the index of the active tab or -1 if the inspector is hidden
  87743. */
  87744. DebugLayer.prototype.getActiveTab = function () {
  87745. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87746. };
  87747. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87748. return DebugLayer;
  87749. }());
  87750. BABYLON.DebugLayer = DebugLayer;
  87751. })(BABYLON || (BABYLON = {}));
  87752. //# sourceMappingURL=babylon.debugLayer.js.map
  87753. var BABYLON;
  87754. (function (BABYLON) {
  87755. var Debug;
  87756. (function (Debug) {
  87757. /**
  87758. * Used to show the physics impostor around the specific mesh
  87759. */
  87760. var PhysicsViewer = /** @class */ (function () {
  87761. /**
  87762. * Creates a new PhysicsViewer
  87763. * @param scene defines the hosting scene
  87764. */
  87765. function PhysicsViewer(scene) {
  87766. /** @hidden */
  87767. this._impostors = [];
  87768. /** @hidden */
  87769. this._meshes = [];
  87770. /** @hidden */
  87771. this._numMeshes = 0;
  87772. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87773. var physicEngine = this._scene.getPhysicsEngine();
  87774. if (physicEngine) {
  87775. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87776. }
  87777. }
  87778. /** @hidden */
  87779. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87780. var plugin = this._physicsEnginePlugin;
  87781. for (var i = 0; i < this._numMeshes; i++) {
  87782. var impostor = this._impostors[i];
  87783. if (!impostor) {
  87784. continue;
  87785. }
  87786. if (impostor.isDisposed) {
  87787. this.hideImpostor(this._impostors[i--]);
  87788. }
  87789. else {
  87790. var mesh = this._meshes[i];
  87791. if (mesh && plugin) {
  87792. plugin.syncMeshWithImpostor(mesh, impostor);
  87793. }
  87794. }
  87795. }
  87796. };
  87797. /**
  87798. * Renders a specified physic impostor
  87799. * @param impostor defines the impostor to render
  87800. */
  87801. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87802. if (!this._scene) {
  87803. return;
  87804. }
  87805. for (var i = 0; i < this._numMeshes; i++) {
  87806. if (this._impostors[i] == impostor) {
  87807. return;
  87808. }
  87809. }
  87810. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87811. if (debugMesh) {
  87812. this._impostors[this._numMeshes] = impostor;
  87813. this._meshes[this._numMeshes] = debugMesh;
  87814. if (this._numMeshes === 0) {
  87815. this._renderFunction = this._updateDebugMeshes.bind(this);
  87816. this._scene.registerBeforeRender(this._renderFunction);
  87817. }
  87818. this._numMeshes++;
  87819. }
  87820. };
  87821. /**
  87822. * Hides a specified physic impostor
  87823. * @param impostor defines the impostor to hide
  87824. */
  87825. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87826. if (!impostor || !this._scene) {
  87827. return;
  87828. }
  87829. var removed = false;
  87830. for (var i = 0; i < this._numMeshes; i++) {
  87831. if (this._impostors[i] == impostor) {
  87832. var mesh = this._meshes[i];
  87833. if (!mesh) {
  87834. continue;
  87835. }
  87836. this._scene.removeMesh(mesh);
  87837. mesh.dispose();
  87838. this._numMeshes--;
  87839. if (this._numMeshes > 0) {
  87840. this._meshes[i] = this._meshes[this._numMeshes];
  87841. this._impostors[i] = this._impostors[this._numMeshes];
  87842. this._meshes[this._numMeshes] = null;
  87843. this._impostors[this._numMeshes] = null;
  87844. }
  87845. else {
  87846. this._meshes[0] = null;
  87847. this._impostors[0] = null;
  87848. }
  87849. removed = true;
  87850. break;
  87851. }
  87852. }
  87853. if (removed && this._numMeshes === 0) {
  87854. this._scene.unregisterBeforeRender(this._renderFunction);
  87855. }
  87856. };
  87857. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87858. if (!this._debugMaterial) {
  87859. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87860. this._debugMaterial.wireframe = true;
  87861. }
  87862. return this._debugMaterial;
  87863. };
  87864. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87865. if (!this._debugBoxMesh) {
  87866. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87867. this._debugBoxMesh.renderingGroupId = 1;
  87868. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87869. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87870. scene.removeMesh(this._debugBoxMesh);
  87871. }
  87872. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87873. };
  87874. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87875. if (!this._debugSphereMesh) {
  87876. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87877. this._debugSphereMesh.renderingGroupId = 1;
  87878. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87879. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87880. scene.removeMesh(this._debugSphereMesh);
  87881. }
  87882. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87883. };
  87884. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87885. var mesh = null;
  87886. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87887. mesh = this._getDebugBoxMesh(scene);
  87888. impostor.getBoxSizeToRef(mesh.scaling);
  87889. }
  87890. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87891. mesh = this._getDebugSphereMesh(scene);
  87892. var radius = impostor.getRadius();
  87893. mesh.scaling.x = radius * 2;
  87894. mesh.scaling.y = radius * 2;
  87895. mesh.scaling.z = radius * 2;
  87896. }
  87897. return mesh;
  87898. };
  87899. /** Releases all resources */
  87900. PhysicsViewer.prototype.dispose = function () {
  87901. for (var i = 0; i < this._numMeshes; i++) {
  87902. this.hideImpostor(this._impostors[i]);
  87903. }
  87904. if (this._debugBoxMesh) {
  87905. this._debugBoxMesh.dispose();
  87906. }
  87907. if (this._debugSphereMesh) {
  87908. this._debugSphereMesh.dispose();
  87909. }
  87910. if (this._debugMaterial) {
  87911. this._debugMaterial.dispose();
  87912. }
  87913. this._impostors.length = 0;
  87914. this._scene = null;
  87915. this._physicsEnginePlugin = null;
  87916. };
  87917. return PhysicsViewer;
  87918. }());
  87919. Debug.PhysicsViewer = PhysicsViewer;
  87920. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87921. })(BABYLON || (BABYLON = {}));
  87922. //# sourceMappingURL=babylon.physicsViewer.js.map
  87923. var BABYLON;
  87924. (function (BABYLON) {
  87925. var BoundingBoxRenderer = /** @class */ (function () {
  87926. function BoundingBoxRenderer(scene) {
  87927. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87928. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87929. this.showBackLines = true;
  87930. this.renderList = new BABYLON.SmartArray(32);
  87931. this._vertexBuffers = {};
  87932. this._scene = scene;
  87933. }
  87934. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87935. if (this._colorShader) {
  87936. return;
  87937. }
  87938. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87939. attributes: [BABYLON.VertexBuffer.PositionKind],
  87940. uniforms: ["world", "viewProjection", "color"]
  87941. });
  87942. var engine = this._scene.getEngine();
  87943. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87944. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87945. this._createIndexBuffer();
  87946. };
  87947. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87948. var engine = this._scene.getEngine();
  87949. 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]);
  87950. };
  87951. BoundingBoxRenderer.prototype._rebuild = function () {
  87952. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87953. if (vb) {
  87954. vb._rebuild();
  87955. }
  87956. this._createIndexBuffer();
  87957. };
  87958. BoundingBoxRenderer.prototype.reset = function () {
  87959. this.renderList.reset();
  87960. };
  87961. BoundingBoxRenderer.prototype.render = function () {
  87962. if (this.renderList.length === 0) {
  87963. return;
  87964. }
  87965. this._prepareRessources();
  87966. if (!this._colorShader.isReady()) {
  87967. return;
  87968. }
  87969. var engine = this._scene.getEngine();
  87970. engine.setDepthWrite(false);
  87971. this._colorShader._preBind();
  87972. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87973. var boundingBox = this.renderList.data[boundingBoxIndex];
  87974. var min = boundingBox.minimum;
  87975. var max = boundingBox.maximum;
  87976. var diff = max.subtract(min);
  87977. var median = min.add(diff.scale(0.5));
  87978. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87979. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87980. .multiply(boundingBox.getWorldMatrix());
  87981. // VBOs
  87982. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87983. if (this.showBackLines) {
  87984. // Back
  87985. engine.setDepthFunctionToGreaterOrEqual();
  87986. this._scene.resetCachedMaterial();
  87987. this._colorShader.setColor4("color", this.backColor.toColor4());
  87988. this._colorShader.bind(worldMatrix);
  87989. // Draw order
  87990. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87991. }
  87992. // Front
  87993. engine.setDepthFunctionToLess();
  87994. this._scene.resetCachedMaterial();
  87995. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87996. this._colorShader.bind(worldMatrix);
  87997. // Draw order
  87998. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87999. }
  88000. this._colorShader.unbind();
  88001. engine.setDepthFunctionToLessOrEqual();
  88002. engine.setDepthWrite(true);
  88003. };
  88004. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88005. this._prepareRessources();
  88006. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88007. return;
  88008. }
  88009. var engine = this._scene.getEngine();
  88010. engine.setDepthWrite(false);
  88011. engine.setColorWrite(false);
  88012. this._colorShader._preBind();
  88013. var boundingBox = mesh._boundingInfo.boundingBox;
  88014. var min = boundingBox.minimum;
  88015. var max = boundingBox.maximum;
  88016. var diff = max.subtract(min);
  88017. var median = min.add(diff.scale(0.5));
  88018. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88019. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88020. .multiply(boundingBox.getWorldMatrix());
  88021. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88022. engine.setDepthFunctionToLess();
  88023. this._scene.resetCachedMaterial();
  88024. this._colorShader.bind(worldMatrix);
  88025. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88026. this._colorShader.unbind();
  88027. engine.setDepthFunctionToLessOrEqual();
  88028. engine.setDepthWrite(true);
  88029. engine.setColorWrite(true);
  88030. };
  88031. BoundingBoxRenderer.prototype.dispose = function () {
  88032. if (!this._colorShader) {
  88033. return;
  88034. }
  88035. this.renderList.dispose();
  88036. this._colorShader.dispose();
  88037. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88038. if (buffer) {
  88039. buffer.dispose();
  88040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88041. }
  88042. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88043. };
  88044. return BoundingBoxRenderer;
  88045. }());
  88046. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88047. })(BABYLON || (BABYLON = {}));
  88048. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88049. var BABYLON;
  88050. (function (BABYLON) {
  88051. /**
  88052. * Renders a layer on top of an existing scene
  88053. */
  88054. var UtilityLayerRenderer = /** @class */ (function () {
  88055. /**
  88056. * Instantiates a UtilityLayerRenderer
  88057. * @param originalScene the original scene that will be rendered on top of
  88058. */
  88059. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88060. var _this = this;
  88061. this.originalScene = originalScene;
  88062. this._pointerCaptures = {};
  88063. this._lastPointerEvents = {};
  88064. /**
  88065. * If the utility layer should automatically be rendered on top of existing scene
  88066. */
  88067. this.shouldRender = true;
  88068. /**
  88069. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88070. */
  88071. this.onlyCheckPointerDownEvents = true;
  88072. /**
  88073. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88074. */
  88075. this.processAllEvents = false;
  88076. /**
  88077. * Observable raised when the pointer move from the utility layer scene to the main scene
  88078. */
  88079. this.onPointerOutObservable = new BABYLON.Observable();
  88080. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88081. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88082. originalScene.getEngine().scenes.pop();
  88083. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88084. this.utilityLayerScene.detachControl();
  88085. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88086. if (!_this.processAllEvents) {
  88087. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88088. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88089. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88090. return;
  88091. }
  88092. }
  88093. var pointerEvent = (prePointerInfo.event);
  88094. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88095. return;
  88096. }
  88097. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88098. if (!prePointerInfo.ray && utilityScenePick) {
  88099. prePointerInfo.ray = utilityScenePick.ray;
  88100. }
  88101. // always fire the prepointer oversvable
  88102. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88103. // allow every non pointer down event to flow to the utility layer
  88104. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88105. if (!prePointerInfo.skipOnPointerObservable) {
  88106. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88107. }
  88108. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88109. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88110. }
  88111. return;
  88112. }
  88113. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88114. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88115. if (utilityScenePick && utilityScenePick.hit) {
  88116. if (!prePointerInfo.skipOnPointerObservable) {
  88117. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88118. }
  88119. prePointerInfo.skipOnPointerObservable = true;
  88120. }
  88121. }
  88122. else {
  88123. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88124. var pointerEvent_1 = (prePointerInfo.event);
  88125. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88126. if (originalScenePick && utilityScenePick) {
  88127. // No pick in utility scene
  88128. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88129. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88130. // We touched an utility mesh present in the main scene
  88131. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88132. prePointerInfo.skipOnPointerObservable = true;
  88133. }
  88134. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88135. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88136. }
  88137. }
  88138. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88139. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88140. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88141. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88142. }
  88143. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88144. // We have a pick in both scenes but main is closer than utility
  88145. // We touched an utility mesh present in the main scene
  88146. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88147. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88148. prePointerInfo.skipOnPointerObservable = true;
  88149. }
  88150. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88151. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88152. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88153. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88154. }
  88155. }
  88156. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88157. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88158. }
  88159. }
  88160. }
  88161. });
  88162. // Render directly on top of existing scene without clearing
  88163. this.utilityLayerScene.autoClear = false;
  88164. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88165. if (_this.shouldRender) {
  88166. _this.render();
  88167. }
  88168. });
  88169. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88170. _this.dispose();
  88171. });
  88172. this._updateCamera();
  88173. }
  88174. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88175. if (!prePointerInfo.skipOnPointerObservable) {
  88176. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88177. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88178. }
  88179. };
  88180. /**
  88181. * Renders the utility layers scene on top of the original scene
  88182. */
  88183. UtilityLayerRenderer.prototype.render = function () {
  88184. this._updateCamera();
  88185. this.utilityLayerScene.render(false);
  88186. };
  88187. /**
  88188. * Disposes of the renderer
  88189. */
  88190. UtilityLayerRenderer.prototype.dispose = function () {
  88191. this.onPointerOutObservable.clear();
  88192. if (this._afterRenderObserver) {
  88193. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88194. }
  88195. if (this._sceneDisposeObserver) {
  88196. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88197. }
  88198. if (this._originalPointerObserver) {
  88199. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88200. }
  88201. this.utilityLayerScene.dispose();
  88202. };
  88203. UtilityLayerRenderer.prototype._updateCamera = function () {
  88204. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88205. };
  88206. return UtilityLayerRenderer;
  88207. }());
  88208. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88209. })(BABYLON || (BABYLON = {}));
  88210. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88211. //# sourceMappingURL=babylon.behavior.js.map
  88212. var BABYLON;
  88213. (function (BABYLON) {
  88214. /**
  88215. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88216. */
  88217. var PointerDragBehavior = /** @class */ (function () {
  88218. /**
  88219. * Creates a pointer drag behavior that can be attached to a mesh
  88220. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88221. */
  88222. function PointerDragBehavior(options) {
  88223. this.options = options;
  88224. /**
  88225. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88226. */
  88227. this.currentDraggingPointerID = -1;
  88228. /**
  88229. * If the behavior is currently in a dragging state
  88230. */
  88231. this.dragging = false;
  88232. /**
  88233. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88234. */
  88235. this.dragDeltaRatio = 0.2;
  88236. /**
  88237. * If the drag plane orientation should be updated during the dragging (Default: true)
  88238. */
  88239. this.updateDragPlane = true;
  88240. // Debug mode will display drag planes to help visualize behavior
  88241. this._debugMode = false;
  88242. this._moving = false;
  88243. /**
  88244. * Fires each time the attached mesh is dragged with the pointer
  88245. * * delta between last drag position and current drag position in world space
  88246. * * dragDistance along the drag axis
  88247. * * dragPlaneNormal normal of the current drag plane used during the drag
  88248. * * dragPlanePoint in world space where the drag intersects the drag plane
  88249. */
  88250. this.onDragObservable = new BABYLON.Observable();
  88251. /**
  88252. * Fires each time a drag begins (eg. mouse down on mesh)
  88253. */
  88254. this.onDragStartObservable = new BABYLON.Observable();
  88255. /**
  88256. * Fires each time a drag ends (eg. mouse release after drag)
  88257. */
  88258. this.onDragEndObservable = new BABYLON.Observable();
  88259. /**
  88260. * If the attached mesh should be moved when dragged
  88261. */
  88262. this.moveAttached = true;
  88263. /**
  88264. * If the drag behavior will react to drag events (Default: true)
  88265. */
  88266. this.enabled = true;
  88267. /**
  88268. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88269. */
  88270. this.useObjectOrienationForDragging = true;
  88271. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88272. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88273. // Variables to avoid instantiation in the below method
  88274. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88275. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88276. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88277. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88278. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88279. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88280. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88281. var optionCount = 0;
  88282. if (options === undefined) {
  88283. options = {};
  88284. }
  88285. if (options.dragAxis) {
  88286. optionCount++;
  88287. }
  88288. if (options.dragPlaneNormal) {
  88289. optionCount++;
  88290. }
  88291. if (optionCount > 1) {
  88292. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88293. }
  88294. }
  88295. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88296. /**
  88297. * The name of the behavior
  88298. */
  88299. get: function () {
  88300. return "PointerDrag";
  88301. },
  88302. enumerable: true,
  88303. configurable: true
  88304. });
  88305. /**
  88306. * Initializes the behavior
  88307. */
  88308. PointerDragBehavior.prototype.init = function () { };
  88309. /**
  88310. * Attaches the drag behavior the passed in mesh
  88311. * @param ownerNode The mesh that will be dragged around once attached
  88312. */
  88313. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88314. var _this = this;
  88315. this._scene = ownerNode.getScene();
  88316. this._attachedNode = ownerNode;
  88317. // Initialize drag plane to not interfere with existing scene
  88318. if (!PointerDragBehavior._planeScene) {
  88319. if (this._debugMode) {
  88320. PointerDragBehavior._planeScene = this._scene;
  88321. }
  88322. else {
  88323. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88324. this._scene.getEngine().scenes.pop();
  88325. }
  88326. }
  88327. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88328. // State of the drag
  88329. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88330. var delta = new BABYLON.Vector3(0, 0, 0);
  88331. var dragLength = 0;
  88332. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88333. var pickPredicate = function (m) {
  88334. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88335. };
  88336. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88337. if (!_this.enabled) {
  88338. return;
  88339. }
  88340. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88341. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88342. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88343. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88344. if (pickedPoint) {
  88345. _this.dragging = true;
  88346. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88347. _this.lastDragPosition.copyFrom(pickedPoint);
  88348. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88349. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88350. }
  88351. }
  88352. }
  88353. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88354. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88355. _this.releaseDrag();
  88356. }
  88357. }
  88358. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88359. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88360. _this._moving = true;
  88361. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88362. if (pickedPoint) {
  88363. if (_this.updateDragPlane) {
  88364. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88365. }
  88366. // depending on the drag mode option drag accordingly
  88367. if (_this.options.dragAxis) {
  88368. // Convert local drag axis to world
  88369. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88370. // Project delta drag from the drag plane onto the drag axis
  88371. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88372. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88373. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88374. }
  88375. else {
  88376. dragLength = delta.length();
  88377. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88378. }
  88379. targetPosition.addInPlace(delta);
  88380. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88381. _this.lastDragPosition.copyFrom(pickedPoint);
  88382. }
  88383. }
  88384. }
  88385. });
  88386. this._scene.onBeforeRenderObservable.add(function () {
  88387. if (_this._moving && _this.moveAttached) {
  88388. // Slowly move mesh to avoid jitter
  88389. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88390. _this._tmpVector.scaleInPlace(0.2);
  88391. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88392. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88393. }
  88394. });
  88395. };
  88396. PointerDragBehavior.prototype.releaseDrag = function () {
  88397. this.dragging = false;
  88398. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88399. this.currentDraggingPointerID = -1;
  88400. this._moving = false;
  88401. };
  88402. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88403. var _this = this;
  88404. if (!ray) {
  88405. return null;
  88406. }
  88407. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88408. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88409. return pickResult.pickedPoint;
  88410. }
  88411. else {
  88412. return null;
  88413. }
  88414. };
  88415. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88416. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88417. this._pointA.copyFrom(dragPlanePosition);
  88418. if (this.options.dragAxis) {
  88419. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88420. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88421. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88422. ray.origin.subtractToRef(this._pointA, this._pointC);
  88423. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88424. // Get perpendicular line from direction to camera and drag axis
  88425. this._pointB.subtractToRef(this._pointA, this._lineA);
  88426. this._pointC.subtractToRef(this._pointA, this._lineB);
  88427. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88428. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88429. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88430. this._lookAt.normalize();
  88431. this._dragPlane.position.copyFrom(this._pointA);
  88432. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88433. this._dragPlane.lookAt(this._lookAt);
  88434. }
  88435. else if (this.options.dragPlaneNormal) {
  88436. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88437. this._dragPlane.position.copyFrom(this._pointA);
  88438. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88439. this._dragPlane.lookAt(this._lookAt);
  88440. }
  88441. else {
  88442. this._dragPlane.position.copyFrom(this._pointA);
  88443. this._dragPlane.lookAt(ray.origin);
  88444. }
  88445. this._dragPlane.computeWorldMatrix(true);
  88446. };
  88447. /**
  88448. * Detaches the behavior from the mesh
  88449. */
  88450. PointerDragBehavior.prototype.detach = function () {
  88451. if (this._pointerObserver) {
  88452. this._scene.onPointerObservable.remove(this._pointerObserver);
  88453. }
  88454. };
  88455. return PointerDragBehavior;
  88456. }());
  88457. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88458. })(BABYLON || (BABYLON = {}));
  88459. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88460. var BABYLON;
  88461. (function (BABYLON) {
  88462. /**
  88463. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88464. */
  88465. var MultiPointerScaleBehavior = /** @class */ (function () {
  88466. function MultiPointerScaleBehavior() {
  88467. this._startDistance = 0;
  88468. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88469. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88470. this._sceneRenderObserver = null;
  88471. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88472. this._dragBehaviorA.moveAttached = false;
  88473. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88474. this._dragBehaviorB.moveAttached = false;
  88475. }
  88476. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88477. /**
  88478. * The name of the behavior
  88479. */
  88480. get: function () {
  88481. return "MultiPointerScale";
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. /**
  88487. * Initializes the behavior
  88488. */
  88489. MultiPointerScaleBehavior.prototype.init = function () { };
  88490. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88491. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88492. };
  88493. /**
  88494. * Attaches the scale behavior the passed in mesh
  88495. * @param ownerNode The mesh that will be scaled around once attached
  88496. */
  88497. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88498. var _this = this;
  88499. this._ownerNode = ownerNode;
  88500. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88501. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88502. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88503. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88504. _this._dragBehaviorA.releaseDrag();
  88505. }
  88506. else {
  88507. _this._initialScale.copyFrom(ownerNode.scaling);
  88508. _this._startDistance = _this._getCurrentDistance();
  88509. }
  88510. }
  88511. });
  88512. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88513. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88514. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88515. _this._dragBehaviorB.releaseDrag();
  88516. }
  88517. else {
  88518. _this._initialScale.copyFrom(ownerNode.scaling);
  88519. _this._startDistance = _this._getCurrentDistance();
  88520. }
  88521. }
  88522. });
  88523. // Once both drag behaviors are active scale based on the distance between the two pointers
  88524. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88525. behavior.onDragObservable.add(function () {
  88526. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88527. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88528. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88529. }
  88530. });
  88531. });
  88532. ownerNode.addBehavior(this._dragBehaviorA);
  88533. ownerNode.addBehavior(this._dragBehaviorB);
  88534. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88535. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88536. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88537. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88538. if (change.length() > 0.01) {
  88539. ownerNode.scaling.addInPlace(change);
  88540. }
  88541. }
  88542. });
  88543. };
  88544. /**
  88545. * Detaches the behavior from the mesh
  88546. */
  88547. MultiPointerScaleBehavior.prototype.detach = function () {
  88548. var _this = this;
  88549. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88550. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88551. behavior.onDragStartObservable.clear();
  88552. behavior.onDragObservable.clear();
  88553. _this._ownerNode.removeBehavior(behavior);
  88554. });
  88555. };
  88556. return MultiPointerScaleBehavior;
  88557. }());
  88558. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88559. })(BABYLON || (BABYLON = {}));
  88560. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88561. var BABYLON;
  88562. (function (BABYLON) {
  88563. /**
  88564. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  88565. */
  88566. var SixDofDragBehavior = /** @class */ (function () {
  88567. function SixDofDragBehavior() {
  88568. this._sceneRenderObserver = null;
  88569. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88570. this._moving = false;
  88571. this._startingOrientation = new BABYLON.Quaternion();
  88572. /**
  88573. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  88574. */
  88575. this.zDragFactor = 5;
  88576. /**
  88577. * If the behavior is currently in a dragging state
  88578. */
  88579. this.dragging = false;
  88580. /**
  88581. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88582. */
  88583. this.dragDeltaRatio = 0.2;
  88584. /**
  88585. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88586. */
  88587. this.currentDraggingPointerID = -1;
  88588. }
  88589. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88590. /**
  88591. * The name of the behavior
  88592. */
  88593. get: function () {
  88594. return "SixDofDrag";
  88595. },
  88596. enumerable: true,
  88597. configurable: true
  88598. });
  88599. /**
  88600. * Initializes the behavior
  88601. */
  88602. SixDofDragBehavior.prototype.init = function () { };
  88603. /**
  88604. * Attaches the scale behavior the passed in mesh
  88605. * @param ownerNode The mesh that will be scaled around once attached
  88606. */
  88607. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88608. var _this = this;
  88609. this._ownerNode = ownerNode;
  88610. this._scene = this._ownerNode.getScene();
  88611. if (!SixDofDragBehavior._virtualScene) {
  88612. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88613. this._scene.getEngine().scenes.pop();
  88614. }
  88615. var pickedMesh = null;
  88616. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88617. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88618. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88619. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88620. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88621. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88622. var pickPredicate = function (m) {
  88623. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88624. };
  88625. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88626. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88627. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88628. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88629. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88630. // Set position and orientation of the controller
  88631. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88632. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88633. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88634. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88635. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88636. if (!pickedMesh.rotationQuaternion) {
  88637. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88638. }
  88639. var oldParent = pickedMesh.parent;
  88640. pickedMesh.setParent(null);
  88641. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88642. pickedMesh.setParent(oldParent);
  88643. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88644. // Update state
  88645. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88646. _this.dragging = true;
  88647. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88648. }
  88649. }
  88650. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88651. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88652. _this.dragging = false;
  88653. _this._moving = false;
  88654. _this.currentDraggingPointerID = -1;
  88655. pickedMesh = null;
  88656. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88657. }
  88658. }
  88659. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88660. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88661. // Calculate controller drag distance in controller space
  88662. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88663. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88664. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88665. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88666. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88667. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88668. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88669. if (_this._virtualDragMesh.position.z < 0) {
  88670. _this._virtualDragMesh.position.z = 0;
  88671. }
  88672. // Update the controller position
  88673. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88674. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88675. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88676. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88677. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88678. if (pickedMesh.parent) {
  88679. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88680. }
  88681. if (!_this._moving) {
  88682. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88683. }
  88684. _this._moving = true;
  88685. }
  88686. }
  88687. });
  88688. var tmpQuaternion = new BABYLON.Quaternion();
  88689. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88690. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88691. if (_this.dragging && _this._moving && pickedMesh) {
  88692. // Slowly move mesh to avoid jitter
  88693. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88694. // Get change in rotation
  88695. tmpQuaternion.copyFrom(_this._startingOrientation);
  88696. tmpQuaternion.x = -tmpQuaternion.x;
  88697. tmpQuaternion.y = -tmpQuaternion.y;
  88698. tmpQuaternion.z = -tmpQuaternion.z;
  88699. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88700. // Convert change in rotation to only y axis rotation
  88701. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88702. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88703. // Slowly move mesh to avoid jitter
  88704. var oldParent = pickedMesh.parent;
  88705. pickedMesh.setParent(null);
  88706. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88707. pickedMesh.setParent(oldParent);
  88708. }
  88709. });
  88710. };
  88711. /**
  88712. * Detaches the behavior from the mesh
  88713. */
  88714. SixDofDragBehavior.prototype.detach = function () {
  88715. this._scene.onPointerObservable.remove(this._pointerObserver);
  88716. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88717. this._virtualOriginMesh.dispose();
  88718. this._virtualDragMesh.dispose();
  88719. };
  88720. return SixDofDragBehavior;
  88721. }());
  88722. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88723. })(BABYLON || (BABYLON = {}));
  88724. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88725. var BABYLON;
  88726. (function (BABYLON) {
  88727. /**
  88728. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88729. */
  88730. var Gizmo = /** @class */ (function () {
  88731. /**
  88732. * Creates a gizmo
  88733. * @param gizmoLayer The utility layer the gizmo will be added to
  88734. */
  88735. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88736. var _this = this;
  88737. this.gizmoLayer = gizmoLayer;
  88738. /**
  88739. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88740. */
  88741. this.updateGizmoRotationToMatchAttachedMesh = true;
  88742. /**
  88743. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88744. */
  88745. this.updateGizmoPositionToMatchAttachedMesh = true;
  88746. /**
  88747. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88748. */
  88749. this._updateScale = true;
  88750. this._interactionsEnabled = true;
  88751. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88752. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88753. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88754. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88755. _this._rootMesh.scaling.set(dist, dist, dist);
  88756. }
  88757. if (_this.attachedMesh) {
  88758. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88759. if (!_this._rootMesh.rotationQuaternion) {
  88760. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88761. }
  88762. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88763. }
  88764. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88765. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88766. }
  88767. }
  88768. });
  88769. this.attachedMesh = null;
  88770. }
  88771. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  88772. /**
  88773. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  88774. * * When set, interactions will be enabled
  88775. */
  88776. get: function () {
  88777. return this._attachedMesh;
  88778. },
  88779. set: function (value) {
  88780. this._attachedMesh = value;
  88781. this._rootMesh.setEnabled(value ? true : false);
  88782. this._attachedMeshChanged(value);
  88783. },
  88784. enumerable: true,
  88785. configurable: true
  88786. });
  88787. Gizmo.prototype._attachedMeshChanged = function (value) {
  88788. };
  88789. /**
  88790. * Disposes of the gizmo
  88791. */
  88792. Gizmo.prototype.dispose = function () {
  88793. this._rootMesh.dispose();
  88794. if (this._beforeRenderObserver) {
  88795. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88796. }
  88797. };
  88798. return Gizmo;
  88799. }());
  88800. BABYLON.Gizmo = Gizmo;
  88801. })(BABYLON || (BABYLON = {}));
  88802. //# sourceMappingURL=babylon.gizmo.js.map
  88803. var BABYLON;
  88804. (function (BABYLON) {
  88805. /**
  88806. * Single axis drag gizmo
  88807. */
  88808. var AxisDragGizmo = /** @class */ (function (_super) {
  88809. __extends(AxisDragGizmo, _super);
  88810. /**
  88811. * Creates an AxisDragGizmo
  88812. * @param gizmoLayer The utility layer the gizmo will be added to
  88813. * @param dragAxis The axis which the gizmo will be able to drag on
  88814. * @param color The color of the gizmo
  88815. */
  88816. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88817. var _this = _super.call(this, gizmoLayer) || this;
  88818. _this._pointerObserver = null;
  88819. /**
  88820. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  88821. */
  88822. _this.snapDistance = 0;
  88823. /**
  88824. * Event that fires each time the gizmo snaps to a new location.
  88825. * * snapDistance is the the change in distance
  88826. */
  88827. _this.onSnapObservable = new BABYLON.Observable();
  88828. // Create Material
  88829. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88830. coloredMaterial.disableLighting = true;
  88831. coloredMaterial.emissiveColor = color;
  88832. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88833. hoverMaterial.disableLighting = true;
  88834. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88835. // Build mesh on root node
  88836. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88837. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88838. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88839. arrow.addChild(arrowMesh);
  88840. arrow.addChild(arrowTail);
  88841. // Position arrow pointing in its drag axis
  88842. arrowMesh.scaling.scaleInPlace(0.05);
  88843. arrowMesh.material = coloredMaterial;
  88844. arrowMesh.rotation.x = Math.PI / 2;
  88845. arrowMesh.position.z += 0.3;
  88846. arrowTail.rotation.x = Math.PI / 2;
  88847. arrowTail.material = coloredMaterial;
  88848. arrowTail.position.z += 0.15;
  88849. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88850. _this._rootMesh.addChild(arrow);
  88851. var currentSnapDragDistance = 0;
  88852. var tmpVector = new BABYLON.Vector3();
  88853. var tmpSnapEvent = { snapDistance: 0 };
  88854. // Add drag behavior to handle events when the gizmo is dragged
  88855. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88856. _this._dragBehavior.moveAttached = false;
  88857. _this._rootMesh.addBehavior(_this._dragBehavior);
  88858. _this._dragBehavior.onDragObservable.add(function (event) {
  88859. if (_this.attachedMesh) {
  88860. // Snapping logic
  88861. if (_this.snapDistance == 0) {
  88862. _this.attachedMesh.position.addInPlace(event.delta);
  88863. }
  88864. else {
  88865. currentSnapDragDistance += event.dragDistance;
  88866. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  88867. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  88868. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  88869. event.delta.normalizeToRef(tmpVector);
  88870. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  88871. _this.attachedMesh.position.addInPlace(tmpVector);
  88872. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  88873. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  88874. }
  88875. }
  88876. }
  88877. });
  88878. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88879. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88880. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88881. m.material = hoverMaterial;
  88882. });
  88883. }
  88884. else {
  88885. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88886. m.material = coloredMaterial;
  88887. });
  88888. }
  88889. });
  88890. return _this;
  88891. }
  88892. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  88893. if (this._dragBehavior) {
  88894. this._dragBehavior.enabled = value ? true : false;
  88895. }
  88896. };
  88897. /**
  88898. * Disposes of the gizmo
  88899. */
  88900. AxisDragGizmo.prototype.dispose = function () {
  88901. this.onSnapObservable.clear();
  88902. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88903. this._dragBehavior.detach();
  88904. _super.prototype.dispose.call(this);
  88905. };
  88906. return AxisDragGizmo;
  88907. }(BABYLON.Gizmo));
  88908. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88909. })(BABYLON || (BABYLON = {}));
  88910. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88911. var BABYLON;
  88912. (function (BABYLON) {
  88913. /**
  88914. * Single axis scale gizmo
  88915. */
  88916. var AxisScaleGizmo = /** @class */ (function (_super) {
  88917. __extends(AxisScaleGizmo, _super);
  88918. /**
  88919. * Creates an AxisScaleGizmo
  88920. * @param gizmoLayer The utility layer the gizmo will be added to
  88921. * @param dragAxis The axis which the gizmo will be able to scale on
  88922. * @param color The color of the gizmo
  88923. */
  88924. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88925. var _this = _super.call(this, gizmoLayer) || this;
  88926. _this._pointerObserver = null;
  88927. /**
  88928. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  88929. */
  88930. _this.snapDistance = 0;
  88931. /**
  88932. * Event that fires each time the gizmo snaps to a new location.
  88933. * * snapDistance is the the change in distance
  88934. */
  88935. _this.onSnapObservable = new BABYLON.Observable();
  88936. // Create Material
  88937. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88938. coloredMaterial.disableLighting = true;
  88939. coloredMaterial.emissiveColor = color;
  88940. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88941. hoverMaterial.disableLighting = true;
  88942. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88943. // Build mesh on root node
  88944. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88945. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  88946. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88947. arrow.addChild(arrowMesh);
  88948. arrow.addChild(arrowTail);
  88949. // Position arrow pointing in its drag axis
  88950. arrowMesh.scaling.scaleInPlace(0.1);
  88951. arrowMesh.material = coloredMaterial;
  88952. arrowMesh.rotation.x = Math.PI / 2;
  88953. arrowMesh.position.z += 0.3;
  88954. arrowTail.rotation.x = Math.PI / 2;
  88955. arrowTail.material = coloredMaterial;
  88956. arrowTail.position.z += 0.15;
  88957. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88958. _this._rootMesh.addChild(arrow);
  88959. // Add drag behavior to handle events when the gizmo is dragged
  88960. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88961. _this._dragBehavior.moveAttached = false;
  88962. _this._rootMesh.addBehavior(_this._dragBehavior);
  88963. var currentSnapDragDistance = 0;
  88964. var tmpVector = new BABYLON.Vector3();
  88965. var tmpSnapEvent = { snapDistance: 0 };
  88966. _this._dragBehavior.onDragObservable.add(function (event) {
  88967. if (_this.attachedMesh) {
  88968. // Snapping logic
  88969. var snapped = false;
  88970. var dragSteps = 0;
  88971. if (_this.snapDistance == 0) {
  88972. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  88973. }
  88974. else {
  88975. currentSnapDragDistance += event.dragDistance;
  88976. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  88977. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  88978. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  88979. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  88980. snapped = true;
  88981. }
  88982. else {
  88983. tmpVector.scaleInPlace(0);
  88984. }
  88985. }
  88986. var invertCount = 0;
  88987. if (_this.attachedMesh.scaling["x"] < 0) {
  88988. invertCount++;
  88989. }
  88990. if (_this.attachedMesh.scaling["y"] < 0) {
  88991. invertCount++;
  88992. }
  88993. if (_this.attachedMesh.scaling["z"] < 0) {
  88994. invertCount++;
  88995. }
  88996. if (invertCount % 2 == 0) {
  88997. _this.attachedMesh.scaling.addInPlace(tmpVector);
  88998. }
  88999. else {
  89000. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89001. }
  89002. if (snapped) {
  89003. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89004. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89005. }
  89006. }
  89007. });
  89008. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89009. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89010. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89011. m.material = hoverMaterial;
  89012. });
  89013. }
  89014. else {
  89015. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89016. m.material = coloredMaterial;
  89017. });
  89018. }
  89019. });
  89020. return _this;
  89021. }
  89022. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89023. if (this._dragBehavior) {
  89024. this._dragBehavior.enabled = value ? true : false;
  89025. }
  89026. };
  89027. /**
  89028. * Disposes of the gizmo
  89029. */
  89030. AxisScaleGizmo.prototype.dispose = function () {
  89031. this.onSnapObservable.clear();
  89032. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89033. this._dragBehavior.detach();
  89034. _super.prototype.dispose.call(this);
  89035. };
  89036. return AxisScaleGizmo;
  89037. }(BABYLON.Gizmo));
  89038. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89039. })(BABYLON || (BABYLON = {}));
  89040. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89041. var BABYLON;
  89042. (function (BABYLON) {
  89043. /**
  89044. * Single plane rotation gizmo
  89045. */
  89046. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89047. __extends(PlaneRotationGizmo, _super);
  89048. /**
  89049. * Creates a PlaneRotationGizmo
  89050. * @param gizmoLayer The utility layer the gizmo will be added to
  89051. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89052. * @param color The color of the gizmo
  89053. */
  89054. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  89055. var _this = _super.call(this, gizmoLayer) || this;
  89056. _this._pointerObserver = null;
  89057. /**
  89058. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89059. */
  89060. _this.snapDistance = 0;
  89061. /**
  89062. * Event that fires each time the gizmo snaps to a new location.
  89063. * * snapDistance is the the change in distance
  89064. */
  89065. _this.onSnapObservable = new BABYLON.Observable();
  89066. // Create Material
  89067. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89068. coloredMaterial.disableLighting = true;
  89069. coloredMaterial.emissiveColor = color;
  89070. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89071. hoverMaterial.disableLighting = true;
  89072. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89073. // Build mesh on root node
  89074. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89075. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89076. // Position arrow pointing in its drag axis
  89077. rotationMesh.scaling.scaleInPlace(0.1);
  89078. rotationMesh.material = coloredMaterial;
  89079. rotationMesh.rotation.x = Math.PI / 2;
  89080. parentMesh.addChild(rotationMesh);
  89081. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89082. _this._rootMesh.addChild(parentMesh);
  89083. // Add drag behavior to handle events when the gizmo is dragged
  89084. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89085. _this._dragBehavior.moveAttached = false;
  89086. _this._rootMesh.addBehavior(_this._dragBehavior);
  89087. var lastDragPosition = null;
  89088. _this._dragBehavior.onDragStartObservable.add(function (e) {
  89089. if (_this.attachedMesh) {
  89090. lastDragPosition = e.dragPlanePoint;
  89091. }
  89092. });
  89093. var rotationMatrix = new BABYLON.Matrix();
  89094. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89095. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89096. var tmpSnapEvent = { snapDistance: 0 };
  89097. var currentSnapDragDistance = 0;
  89098. _this._dragBehavior.onDragObservable.add(function (event) {
  89099. if (_this.attachedMesh && lastDragPosition) {
  89100. if (!_this.attachedMesh.rotationQuaternion) {
  89101. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89102. }
  89103. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89104. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89105. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89106. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89107. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89108. var angle = Math.atan2(cross.length(), dot);
  89109. planeNormalTowardsCamera.copyFrom(planeNormal);
  89110. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89111. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89112. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89113. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89114. }
  89115. // Flip up vector depending on which side the camera is on
  89116. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89117. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89118. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89119. planeNormalTowardsCamera.scaleInPlace(-1);
  89120. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89121. }
  89122. }
  89123. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89124. if (halfCircleSide)
  89125. angle = -angle;
  89126. // Snapping logic
  89127. var snapped = false;
  89128. if (_this.snapDistance != 0) {
  89129. currentSnapDragDistance += angle;
  89130. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89131. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89132. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89133. angle = _this.snapDistance * dragSteps;
  89134. snapped = true;
  89135. }
  89136. else {
  89137. angle = 0;
  89138. }
  89139. }
  89140. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89141. var quaternionCoefficient = Math.sin(angle / 2);
  89142. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89143. // Rotate selected mesh quaternion over fixed axis
  89144. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89145. lastDragPosition = event.dragPlanePoint;
  89146. if (snapped) {
  89147. tmpSnapEvent.snapDistance = angle;
  89148. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89149. }
  89150. }
  89151. });
  89152. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89153. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89154. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89155. m.material = hoverMaterial;
  89156. });
  89157. }
  89158. else {
  89159. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89160. m.material = coloredMaterial;
  89161. });
  89162. }
  89163. });
  89164. return _this;
  89165. }
  89166. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89167. if (this._dragBehavior) {
  89168. this._dragBehavior.enabled = value ? true : false;
  89169. }
  89170. };
  89171. /**
  89172. * Disposes of the gizmo
  89173. */
  89174. PlaneRotationGizmo.prototype.dispose = function () {
  89175. this.onSnapObservable.clear();
  89176. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89177. this._dragBehavior.detach();
  89178. _super.prototype.dispose.call(this);
  89179. };
  89180. return PlaneRotationGizmo;
  89181. }(BABYLON.Gizmo));
  89182. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89183. })(BABYLON || (BABYLON = {}));
  89184. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89185. var BABYLON;
  89186. (function (BABYLON) {
  89187. /**
  89188. * Gizmo that enables dragging a mesh along 3 axis
  89189. */
  89190. var PositionGizmo = /** @class */ (function (_super) {
  89191. __extends(PositionGizmo, _super);
  89192. /**
  89193. * Creates a PositionGizmo
  89194. * @param gizmoLayer The utility layer the gizmo will be added to
  89195. */
  89196. function PositionGizmo(gizmoLayer) {
  89197. var _this = _super.call(this, gizmoLayer) || this;
  89198. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89199. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89200. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89201. _this.attachedMesh = null;
  89202. return _this;
  89203. }
  89204. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89205. set: function (mesh) {
  89206. if (this._xDrag) {
  89207. this._xDrag.attachedMesh = mesh;
  89208. this._yDrag.attachedMesh = mesh;
  89209. this._zDrag.attachedMesh = mesh;
  89210. }
  89211. },
  89212. enumerable: true,
  89213. configurable: true
  89214. });
  89215. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89216. get: function () {
  89217. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89218. },
  89219. set: function (value) {
  89220. if (this._xDrag) {
  89221. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89222. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89223. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89224. }
  89225. },
  89226. enumerable: true,
  89227. configurable: true
  89228. });
  89229. /**
  89230. * Disposes of the gizmo
  89231. */
  89232. PositionGizmo.prototype.dispose = function () {
  89233. this._xDrag.dispose();
  89234. this._yDrag.dispose();
  89235. this._zDrag.dispose();
  89236. };
  89237. return PositionGizmo;
  89238. }(BABYLON.Gizmo));
  89239. BABYLON.PositionGizmo = PositionGizmo;
  89240. })(BABYLON || (BABYLON = {}));
  89241. //# sourceMappingURL=babylon.positionGizmo.js.map
  89242. var BABYLON;
  89243. (function (BABYLON) {
  89244. /**
  89245. * Gizmo that enables rotating a mesh along 3 axis
  89246. */
  89247. var RotationGizmo = /** @class */ (function (_super) {
  89248. __extends(RotationGizmo, _super);
  89249. /**
  89250. * Creates a RotationGizmo
  89251. * @param gizmoLayer The utility layer the gizmo will be added to
  89252. */
  89253. function RotationGizmo(gizmoLayer) {
  89254. var _this = _super.call(this, gizmoLayer) || this;
  89255. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89256. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89257. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89258. _this.attachedMesh = null;
  89259. return _this;
  89260. }
  89261. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89262. set: function (mesh) {
  89263. if (this._xDrag) {
  89264. this._xDrag.attachedMesh = mesh;
  89265. this._yDrag.attachedMesh = mesh;
  89266. this._zDrag.attachedMesh = mesh;
  89267. }
  89268. },
  89269. enumerable: true,
  89270. configurable: true
  89271. });
  89272. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89273. get: function () {
  89274. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89275. },
  89276. set: function (value) {
  89277. if (this._xDrag) {
  89278. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89279. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89280. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89281. }
  89282. },
  89283. enumerable: true,
  89284. configurable: true
  89285. });
  89286. /**
  89287. * Disposes of the gizmo
  89288. */
  89289. RotationGizmo.prototype.dispose = function () {
  89290. this._xDrag.dispose();
  89291. this._yDrag.dispose();
  89292. this._zDrag.dispose();
  89293. };
  89294. return RotationGizmo;
  89295. }(BABYLON.Gizmo));
  89296. BABYLON.RotationGizmo = RotationGizmo;
  89297. })(BABYLON || (BABYLON = {}));
  89298. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89299. var BABYLON;
  89300. (function (BABYLON) {
  89301. /**
  89302. * Gizmo that enables scaling a mesh along 3 axis
  89303. */
  89304. var ScaleGizmo = /** @class */ (function (_super) {
  89305. __extends(ScaleGizmo, _super);
  89306. /**
  89307. * Creates a ScaleGizmo
  89308. * @param gizmoLayer The utility layer the gizmo will be added to
  89309. */
  89310. function ScaleGizmo(gizmoLayer) {
  89311. var _this = _super.call(this, gizmoLayer) || this;
  89312. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89313. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89314. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89315. _this.attachedMesh = null;
  89316. return _this;
  89317. }
  89318. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89319. set: function (mesh) {
  89320. if (this._xDrag) {
  89321. this._xDrag.attachedMesh = mesh;
  89322. this._yDrag.attachedMesh = mesh;
  89323. this._zDrag.attachedMesh = mesh;
  89324. }
  89325. },
  89326. enumerable: true,
  89327. configurable: true
  89328. });
  89329. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89330. get: function () {
  89331. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89332. },
  89333. set: function (value) {
  89334. if (this._xDrag) {
  89335. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89336. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89337. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89338. }
  89339. },
  89340. enumerable: true,
  89341. configurable: true
  89342. });
  89343. /**
  89344. * Disposes of the gizmo
  89345. */
  89346. ScaleGizmo.prototype.dispose = function () {
  89347. this._xDrag.dispose();
  89348. this._yDrag.dispose();
  89349. this._zDrag.dispose();
  89350. };
  89351. return ScaleGizmo;
  89352. }(BABYLON.Gizmo));
  89353. BABYLON.ScaleGizmo = ScaleGizmo;
  89354. })(BABYLON || (BABYLON = {}));
  89355. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89356. var BABYLON;
  89357. (function (BABYLON) {
  89358. /**
  89359. * Bounding box gizmo
  89360. */
  89361. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89362. __extends(BoundingBoxGizmo, _super);
  89363. /**
  89364. * Creates an BoundingBoxGizmo
  89365. * @param gizmoLayer The utility layer the gizmo will be added to
  89366. * @param color The color of the gizmo
  89367. */
  89368. function BoundingBoxGizmo(gizmoLayer, color) {
  89369. var _this = _super.call(this, gizmoLayer) || this;
  89370. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89371. _this._renderObserver = null;
  89372. _this._pointerObserver = null;
  89373. _this._scaleDragSpeed = 0.2;
  89374. _this._tmpQuaternion = new BABYLON.Quaternion();
  89375. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89376. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89377. _this._updateScale = false;
  89378. // Create Materials
  89379. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89380. coloredMaterial.disableLighting = true;
  89381. coloredMaterial.emissiveColor = color;
  89382. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89383. hoverColoredMaterial.disableLighting = true;
  89384. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89385. // Build bounding box out of lines
  89386. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89387. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89388. var lines = [];
  89389. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89390. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89391. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89392. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89393. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89394. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89395. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89396. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89397. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89398. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89399. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89400. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89401. lines.forEach(function (l) {
  89402. l.color = color;
  89403. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89404. l.isPickable = false;
  89405. _this._lineBoundingBox.addChild(l);
  89406. });
  89407. _this._rootMesh.addChild(_this._lineBoundingBox);
  89408. // Create rotation spheres
  89409. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89410. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89411. var _loop_1 = function (i_1) {
  89412. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  89413. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89414. sphere.material = coloredMaterial;
  89415. // Drag behavior
  89416. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89417. _dragBehavior.moveAttached = false;
  89418. _dragBehavior.updateDragPlane = false;
  89419. sphere.addBehavior(_dragBehavior);
  89420. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89421. var totalTurnAmountOfDrag = 0;
  89422. _dragBehavior.onDragStartObservable.add(function (event) {
  89423. startingTurnDirection.copyFrom(sphere.forward);
  89424. totalTurnAmountOfDrag = 0;
  89425. });
  89426. _dragBehavior.onDragObservable.add(function (event) {
  89427. if (_this.attachedMesh) {
  89428. var worldDragDirection = startingTurnDirection;
  89429. // Project the world right on to the drag plane
  89430. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89431. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89432. // project drag delta on to the resulting drag axis and rotate based on that
  89433. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89434. // Rotate based on axis
  89435. if (!_this.attachedMesh.rotationQuaternion) {
  89436. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89437. }
  89438. // Do not allow the object to turn more than a full circle
  89439. totalTurnAmountOfDrag += projectDist;
  89440. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89441. if (i_1 >= 8) {
  89442. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89443. }
  89444. else if (i_1 >= 4) {
  89445. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89446. }
  89447. else {
  89448. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89449. }
  89450. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89451. }
  89452. }
  89453. });
  89454. // Selection/deselection
  89455. _dragBehavior.onDragStartObservable.add(function () {
  89456. _this._selectNode(sphere);
  89457. });
  89458. _dragBehavior.onDragEndObservable.add(function () {
  89459. _this._selectNode(null);
  89460. });
  89461. this_1._rotateSpheresParent.addChild(sphere);
  89462. };
  89463. var this_1 = this, _dragBehavior;
  89464. for (var i_1 = 0; i_1 < 12; i_1++) {
  89465. _loop_1(i_1);
  89466. }
  89467. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89468. // Create scale cubes
  89469. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89470. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89471. for (var i = 0; i < 2; i++) {
  89472. for (var j = 0; j < 2; j++) {
  89473. var _loop_2 = function () {
  89474. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89475. box.material = coloredMaterial;
  89476. // Dragging logic
  89477. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89478. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89479. _dragBehavior.moveAttached = false;
  89480. box.addBehavior(_dragBehavior);
  89481. _dragBehavior.onDragObservable.add(function (event) {
  89482. if (_this.attachedMesh) {
  89483. // Current boudning box dimensions
  89484. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89485. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89486. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89487. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89488. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89489. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89490. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89491. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89492. // Update scale and position
  89493. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89494. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89495. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89496. }
  89497. });
  89498. // Selection/deselection
  89499. _dragBehavior.onDragStartObservable.add(function () {
  89500. _this._selectNode(box);
  89501. });
  89502. _dragBehavior.onDragEndObservable.add(function () {
  89503. _this._selectNode(null);
  89504. });
  89505. this_2._scaleBoxesParent.addChild(box);
  89506. };
  89507. var this_2 = this, _dragBehavior;
  89508. for (var k = 0; k < 2; k++) {
  89509. _loop_2();
  89510. }
  89511. }
  89512. }
  89513. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89514. // Hover color change
  89515. var pointerIds = new Array();
  89516. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89517. if (!pointerIds[pointerInfo.event.pointerId]) {
  89518. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89519. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89520. pointerIds[pointerInfo.event.pointerId] = mesh;
  89521. mesh.material = hoverColoredMaterial;
  89522. }
  89523. });
  89524. }
  89525. else {
  89526. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89527. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89528. delete pointerIds[pointerInfo.event.pointerId];
  89529. }
  89530. }
  89531. });
  89532. // Update bounding box positions
  89533. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89534. _this._updateBoundingBox();
  89535. });
  89536. _this._updateBoundingBox();
  89537. return _this;
  89538. }
  89539. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89540. this._rotateSpheresParent.getChildMeshes()
  89541. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89542. m.isVisible = (!selectedMesh || m == selectedMesh);
  89543. });
  89544. };
  89545. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89546. if (this.attachedMesh) {
  89547. // Update bounding dimensions/positions
  89548. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89549. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89550. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89551. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89552. }
  89553. // Update rotation sphere locations
  89554. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89555. for (var i = 0; i < 3; i++) {
  89556. for (var j = 0; j < 2; j++) {
  89557. for (var k = 0; k < 2; k++) {
  89558. var index = ((i * 4) + (j * 2)) + k;
  89559. if (i == 0) {
  89560. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89561. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89562. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89563. }
  89564. if (i == 1) {
  89565. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89566. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89567. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89568. }
  89569. if (i == 2) {
  89570. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89571. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89572. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89573. }
  89574. }
  89575. }
  89576. }
  89577. // Update scale box locations
  89578. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89579. for (var i = 0; i < 2; i++) {
  89580. for (var j = 0; j < 2; j++) {
  89581. for (var k = 0; k < 2; k++) {
  89582. var index = ((i * 4) + (j * 2)) + k;
  89583. if (scaleBoxes[index]) {
  89584. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89585. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89586. }
  89587. }
  89588. }
  89589. }
  89590. };
  89591. /**
  89592. * Enables rotation on the specified axis and disables rotation on the others
  89593. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  89594. */
  89595. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  89596. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  89597. if (i < 4) {
  89598. m.setEnabled(axis.indexOf("x") != -1);
  89599. }
  89600. else if (i < 8) {
  89601. m.setEnabled(axis.indexOf("y") != -1);
  89602. }
  89603. else {
  89604. m.setEnabled(axis.indexOf("z") != -1);
  89605. }
  89606. });
  89607. };
  89608. /**
  89609. * Disposes of the gizmo
  89610. */
  89611. BoundingBoxGizmo.prototype.dispose = function () {
  89612. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89613. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89614. this._lineBoundingBox.dispose();
  89615. this._rotateSpheresParent.dispose();
  89616. this._scaleBoxesParent.dispose();
  89617. _super.prototype.dispose.call(this);
  89618. };
  89619. return BoundingBoxGizmo;
  89620. }(BABYLON.Gizmo));
  89621. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89622. })(BABYLON || (BABYLON = {}));
  89623. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89624. var BABYLON;
  89625. (function (BABYLON) {
  89626. /**
  89627. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89628. */
  89629. var GizmoManager = /** @class */ (function () {
  89630. /**
  89631. * Instatiates a gizmo manager
  89632. * @param scene the scene to overlay the gizmos on top of
  89633. * @param options If only a single gizmo should exist at one time
  89634. */
  89635. function GizmoManager(scene, options) {
  89636. var _this = this;
  89637. this.scene = scene;
  89638. // Set of gizmos that are currently in the scene for each mesh
  89639. this._gizmoSet = {};
  89640. this._pointerObserver = null;
  89641. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89642. // Options parsing
  89643. if (!options) {
  89644. options = {};
  89645. }
  89646. if (options.singleGizmo === undefined) {
  89647. options.singleGizmo = true;
  89648. }
  89649. // Instatiate/dispose gizmos based on pointer actions
  89650. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89651. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89652. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89653. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89654. if (options.singleGizmo) {
  89655. _this._clearGizmos();
  89656. }
  89657. // Enable gizmo when mesh is selected
  89658. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89659. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89660. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89661. }
  89662. else {
  89663. if (!options.singleGizmo) {
  89664. // Disable gizmo when clicked again
  89665. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89666. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89667. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89668. }
  89669. }
  89670. }
  89671. else {
  89672. if (options.singleGizmo) {
  89673. // Disable gizmo when clicked away
  89674. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89675. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89676. if (gizmoPick && !gizmoPick.hit) {
  89677. _this._clearGizmos();
  89678. }
  89679. }
  89680. }
  89681. }
  89682. }
  89683. });
  89684. }
  89685. /**
  89686. * Disposes of the gizmo manager
  89687. */
  89688. GizmoManager.prototype.dispose = function () {
  89689. this.scene.onPointerObservable.remove(this._pointerObserver);
  89690. this._clearGizmos();
  89691. this._gizmoLayer.dispose();
  89692. };
  89693. GizmoManager.prototype._clearGizmos = function () {
  89694. for (var key in this._gizmoSet) {
  89695. if (this._gizmoSet.hasOwnProperty(key)) {
  89696. this._gizmoSet[key].positionGizmo.dispose();
  89697. this._gizmoSet[key].rotationGizmo.dispose();
  89698. delete this._gizmoSet[key];
  89699. }
  89700. }
  89701. };
  89702. return GizmoManager;
  89703. }());
  89704. BABYLON.GizmoManager = GizmoManager;
  89705. })(BABYLON || (BABYLON = {}));
  89706. //# sourceMappingURL=babylon.gizmoManager.js.map
  89707. var BABYLON;
  89708. (function (BABYLON) {
  89709. /**
  89710. * Defines a target to use with MorphTargetManager
  89711. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89712. */
  89713. var MorphTarget = /** @class */ (function () {
  89714. /**
  89715. * Creates a new MorphTarget
  89716. * @param name defines the name of the target
  89717. * @param influence defines the influence to use
  89718. */
  89719. function MorphTarget(
  89720. /** defines the name of the target */
  89721. name, influence, scene) {
  89722. if (influence === void 0) { influence = 0; }
  89723. if (scene === void 0) { scene = null; }
  89724. this.name = name;
  89725. /**
  89726. * Gets or sets the list of animations
  89727. */
  89728. this.animations = new Array();
  89729. this._positions = null;
  89730. this._normals = null;
  89731. this._tangents = null;
  89732. /**
  89733. * Observable raised when the influence changes
  89734. */
  89735. this.onInfluenceChanged = new BABYLON.Observable();
  89736. this._animationPropertiesOverride = null;
  89737. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89738. this.influence = influence;
  89739. }
  89740. Object.defineProperty(MorphTarget.prototype, "influence", {
  89741. /**
  89742. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89743. */
  89744. get: function () {
  89745. return this._influence;
  89746. },
  89747. set: function (influence) {
  89748. if (this._influence === influence) {
  89749. return;
  89750. }
  89751. var previous = this._influence;
  89752. this._influence = influence;
  89753. if (this.onInfluenceChanged.hasObservers) {
  89754. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89755. }
  89756. },
  89757. enumerable: true,
  89758. configurable: true
  89759. });
  89760. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89761. /**
  89762. * Gets or sets the animation properties override
  89763. */
  89764. get: function () {
  89765. if (!this._animationPropertiesOverride && this._scene) {
  89766. return this._scene.animationPropertiesOverride;
  89767. }
  89768. return this._animationPropertiesOverride;
  89769. },
  89770. set: function (value) {
  89771. this._animationPropertiesOverride = value;
  89772. },
  89773. enumerable: true,
  89774. configurable: true
  89775. });
  89776. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89777. /**
  89778. * Gets a boolean defining if the target contains position data
  89779. */
  89780. get: function () {
  89781. return !!this._positions;
  89782. },
  89783. enumerable: true,
  89784. configurable: true
  89785. });
  89786. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89787. /**
  89788. * Gets a boolean defining if the target contains normal data
  89789. */
  89790. get: function () {
  89791. return !!this._normals;
  89792. },
  89793. enumerable: true,
  89794. configurable: true
  89795. });
  89796. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89797. /**
  89798. * Gets a boolean defining if the target contains tangent data
  89799. */
  89800. get: function () {
  89801. return !!this._tangents;
  89802. },
  89803. enumerable: true,
  89804. configurable: true
  89805. });
  89806. /**
  89807. * Affects position data to this target
  89808. * @param data defines the position data to use
  89809. */
  89810. MorphTarget.prototype.setPositions = function (data) {
  89811. this._positions = data;
  89812. };
  89813. /**
  89814. * Gets the position data stored in this target
  89815. * @returns a FloatArray containing the position data (or null if not present)
  89816. */
  89817. MorphTarget.prototype.getPositions = function () {
  89818. return this._positions;
  89819. };
  89820. /**
  89821. * Affects normal data to this target
  89822. * @param data defines the normal data to use
  89823. */
  89824. MorphTarget.prototype.setNormals = function (data) {
  89825. this._normals = data;
  89826. };
  89827. /**
  89828. * Gets the normal data stored in this target
  89829. * @returns a FloatArray containing the normal data (or null if not present)
  89830. */
  89831. MorphTarget.prototype.getNormals = function () {
  89832. return this._normals;
  89833. };
  89834. /**
  89835. * Affects tangent data to this target
  89836. * @param data defines the tangent data to use
  89837. */
  89838. MorphTarget.prototype.setTangents = function (data) {
  89839. this._tangents = data;
  89840. };
  89841. /**
  89842. * Gets the tangent data stored in this target
  89843. * @returns a FloatArray containing the tangent data (or null if not present)
  89844. */
  89845. MorphTarget.prototype.getTangents = function () {
  89846. return this._tangents;
  89847. };
  89848. /**
  89849. * Serializes the current target into a Serialization object
  89850. * @returns the serialized object
  89851. */
  89852. MorphTarget.prototype.serialize = function () {
  89853. var serializationObject = {};
  89854. serializationObject.name = this.name;
  89855. serializationObject.influence = this.influence;
  89856. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89857. if (this.hasNormals) {
  89858. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89859. }
  89860. if (this.hasTangents) {
  89861. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89862. }
  89863. // Animations
  89864. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89865. return serializationObject;
  89866. };
  89867. // Statics
  89868. /**
  89869. * Creates a new target from serialized data
  89870. * @param serializationObject defines the serialized data to use
  89871. * @returns a new MorphTarget
  89872. */
  89873. MorphTarget.Parse = function (serializationObject) {
  89874. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89875. result.setPositions(serializationObject.positions);
  89876. if (serializationObject.normals) {
  89877. result.setNormals(serializationObject.normals);
  89878. }
  89879. if (serializationObject.tangents) {
  89880. result.setTangents(serializationObject.tangents);
  89881. }
  89882. // Animations
  89883. if (serializationObject.animations) {
  89884. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89885. var parsedAnimation = serializationObject.animations[animationIndex];
  89886. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89887. }
  89888. }
  89889. return result;
  89890. };
  89891. /**
  89892. * Creates a MorphTarget from mesh data
  89893. * @param mesh defines the source mesh
  89894. * @param name defines the name to use for the new target
  89895. * @param influence defines the influence to attach to the target
  89896. * @returns a new MorphTarget
  89897. */
  89898. MorphTarget.FromMesh = function (mesh, name, influence) {
  89899. if (!name) {
  89900. name = mesh.name;
  89901. }
  89902. var result = new MorphTarget(name, influence, mesh.getScene());
  89903. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89905. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89906. }
  89907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89908. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89909. }
  89910. return result;
  89911. };
  89912. return MorphTarget;
  89913. }());
  89914. BABYLON.MorphTarget = MorphTarget;
  89915. })(BABYLON || (BABYLON = {}));
  89916. //# sourceMappingURL=babylon.morphTarget.js.map
  89917. var BABYLON;
  89918. (function (BABYLON) {
  89919. /**
  89920. * This class is used to deform meshes using morphing between different targets
  89921. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89922. */
  89923. var MorphTargetManager = /** @class */ (function () {
  89924. /**
  89925. * Creates a new MorphTargetManager
  89926. * @param scene defines the current scene
  89927. */
  89928. function MorphTargetManager(scene) {
  89929. if (scene === void 0) { scene = null; }
  89930. this._targets = new Array();
  89931. this._targetObservable = new Array();
  89932. this._activeTargets = new BABYLON.SmartArray(16);
  89933. this._supportsNormals = false;
  89934. this._supportsTangents = false;
  89935. this._vertexCount = 0;
  89936. this._uniqueId = 0;
  89937. this._tempInfluences = new Array();
  89938. if (!scene) {
  89939. scene = BABYLON.Engine.LastCreatedScene;
  89940. }
  89941. this._scene = scene;
  89942. if (this._scene) {
  89943. this._scene.morphTargetManagers.push(this);
  89944. this._uniqueId = this._scene.getUniqueId();
  89945. }
  89946. }
  89947. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89948. /**
  89949. * Gets the unique ID of this manager
  89950. */
  89951. get: function () {
  89952. return this._uniqueId;
  89953. },
  89954. enumerable: true,
  89955. configurable: true
  89956. });
  89957. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89958. /**
  89959. * Gets the number of vertices handled by this manager
  89960. */
  89961. get: function () {
  89962. return this._vertexCount;
  89963. },
  89964. enumerable: true,
  89965. configurable: true
  89966. });
  89967. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89968. /**
  89969. * Gets a boolean indicating if this manager supports morphing of normals
  89970. */
  89971. get: function () {
  89972. return this._supportsNormals;
  89973. },
  89974. enumerable: true,
  89975. configurable: true
  89976. });
  89977. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89978. /**
  89979. * Gets a boolean indicating if this manager supports morphing of tangents
  89980. */
  89981. get: function () {
  89982. return this._supportsTangents;
  89983. },
  89984. enumerable: true,
  89985. configurable: true
  89986. });
  89987. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89988. /**
  89989. * Gets the number of targets stored in this manager
  89990. */
  89991. get: function () {
  89992. return this._targets.length;
  89993. },
  89994. enumerable: true,
  89995. configurable: true
  89996. });
  89997. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89998. /**
  89999. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90000. */
  90001. get: function () {
  90002. return this._activeTargets.length;
  90003. },
  90004. enumerable: true,
  90005. configurable: true
  90006. });
  90007. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90008. /**
  90009. * Gets the list of influences (one per target)
  90010. */
  90011. get: function () {
  90012. return this._influences;
  90013. },
  90014. enumerable: true,
  90015. configurable: true
  90016. });
  90017. /**
  90018. * Gets the active target at specified index. An active target is a target with an influence > 0
  90019. * @param index defines the index to check
  90020. * @returns the requested target
  90021. */
  90022. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90023. return this._activeTargets.data[index];
  90024. };
  90025. /**
  90026. * Gets the target at specified index
  90027. * @param index defines the index to check
  90028. * @returns the requested target
  90029. */
  90030. MorphTargetManager.prototype.getTarget = function (index) {
  90031. return this._targets[index];
  90032. };
  90033. /**
  90034. * Add a new target to this manager
  90035. * @param target defines the target to add
  90036. */
  90037. MorphTargetManager.prototype.addTarget = function (target) {
  90038. var _this = this;
  90039. this._targets.push(target);
  90040. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90041. _this._syncActiveTargets(needUpdate);
  90042. }));
  90043. this._syncActiveTargets(true);
  90044. };
  90045. /**
  90046. * Removes a target from the manager
  90047. * @param target defines the target to remove
  90048. */
  90049. MorphTargetManager.prototype.removeTarget = function (target) {
  90050. var index = this._targets.indexOf(target);
  90051. if (index >= 0) {
  90052. this._targets.splice(index, 1);
  90053. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90054. this._syncActiveTargets(true);
  90055. }
  90056. };
  90057. /**
  90058. * Serializes the current manager into a Serialization object
  90059. * @returns the serialized object
  90060. */
  90061. MorphTargetManager.prototype.serialize = function () {
  90062. var serializationObject = {};
  90063. serializationObject.id = this.uniqueId;
  90064. serializationObject.targets = [];
  90065. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90066. var target = _a[_i];
  90067. serializationObject.targets.push(target.serialize());
  90068. }
  90069. return serializationObject;
  90070. };
  90071. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90072. var influenceCount = 0;
  90073. this._activeTargets.reset();
  90074. this._supportsNormals = true;
  90075. this._supportsTangents = true;
  90076. this._vertexCount = 0;
  90077. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90078. var target = _a[_i];
  90079. this._activeTargets.push(target);
  90080. this._tempInfluences[influenceCount++] = target.influence;
  90081. var positions = target.getPositions();
  90082. if (positions) {
  90083. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90084. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90085. var vertexCount = positions.length / 3;
  90086. if (this._vertexCount === 0) {
  90087. this._vertexCount = vertexCount;
  90088. }
  90089. else if (this._vertexCount !== vertexCount) {
  90090. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90091. return;
  90092. }
  90093. }
  90094. }
  90095. if (!this._influences || this._influences.length !== influenceCount) {
  90096. this._influences = new Float32Array(influenceCount);
  90097. }
  90098. for (var index = 0; index < influenceCount; index++) {
  90099. this._influences[index] = this._tempInfluences[index];
  90100. }
  90101. if (needUpdate) {
  90102. this.synchronize();
  90103. }
  90104. };
  90105. /**
  90106. * Syncrhonize the targets with all the meshes using this morph target manager
  90107. */
  90108. MorphTargetManager.prototype.synchronize = function () {
  90109. if (!this._scene) {
  90110. return;
  90111. }
  90112. // Flag meshes as dirty to resync with the active targets
  90113. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90114. var mesh = _a[_i];
  90115. if (mesh.morphTargetManager === this) {
  90116. mesh._syncGeometryWithMorphTargetManager();
  90117. }
  90118. }
  90119. };
  90120. // Statics
  90121. /**
  90122. * Creates a new MorphTargetManager from serialized data
  90123. * @param serializationObject defines the serialized data
  90124. * @param scene defines the hosting scene
  90125. * @returns the new MorphTargetManager
  90126. */
  90127. MorphTargetManager.Parse = function (serializationObject, scene) {
  90128. var result = new MorphTargetManager(scene);
  90129. result._uniqueId = serializationObject.id;
  90130. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90131. var targetData = _a[_i];
  90132. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90133. }
  90134. return result;
  90135. };
  90136. return MorphTargetManager;
  90137. }());
  90138. BABYLON.MorphTargetManager = MorphTargetManager;
  90139. })(BABYLON || (BABYLON = {}));
  90140. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90141. var BABYLON;
  90142. (function (BABYLON) {
  90143. var Octree = /** @class */ (function () {
  90144. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90145. if (maxDepth === void 0) { maxDepth = 2; }
  90146. this.maxDepth = maxDepth;
  90147. this.dynamicContent = new Array();
  90148. this._maxBlockCapacity = maxBlockCapacity || 64;
  90149. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90150. this._creationFunc = creationFunc;
  90151. }
  90152. // Methods
  90153. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90154. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90155. };
  90156. Octree.prototype.addMesh = function (entry) {
  90157. for (var index = 0; index < this.blocks.length; index++) {
  90158. var block = this.blocks[index];
  90159. block.addEntry(entry);
  90160. }
  90161. };
  90162. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90163. this._selectionContent.reset();
  90164. for (var index = 0; index < this.blocks.length; index++) {
  90165. var block = this.blocks[index];
  90166. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90167. }
  90168. if (allowDuplicate) {
  90169. this._selectionContent.concat(this.dynamicContent);
  90170. }
  90171. else {
  90172. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90173. }
  90174. return this._selectionContent;
  90175. };
  90176. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90177. this._selectionContent.reset();
  90178. for (var index = 0; index < this.blocks.length; index++) {
  90179. var block = this.blocks[index];
  90180. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90181. }
  90182. if (allowDuplicate) {
  90183. this._selectionContent.concat(this.dynamicContent);
  90184. }
  90185. else {
  90186. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90187. }
  90188. return this._selectionContent;
  90189. };
  90190. Octree.prototype.intersectsRay = function (ray) {
  90191. this._selectionContent.reset();
  90192. for (var index = 0; index < this.blocks.length; index++) {
  90193. var block = this.blocks[index];
  90194. block.intersectsRay(ray, this._selectionContent);
  90195. }
  90196. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90197. return this._selectionContent;
  90198. };
  90199. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90200. target.blocks = new Array();
  90201. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90202. // Segmenting space
  90203. for (var x = 0; x < 2; x++) {
  90204. for (var y = 0; y < 2; y++) {
  90205. for (var z = 0; z < 2; z++) {
  90206. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90207. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90208. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90209. block.addEntries(entries);
  90210. target.blocks.push(block);
  90211. }
  90212. }
  90213. }
  90214. };
  90215. Octree.CreationFuncForMeshes = function (entry, block) {
  90216. var boundingInfo = entry.getBoundingInfo();
  90217. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90218. block.entries.push(entry);
  90219. }
  90220. };
  90221. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90222. var boundingInfo = entry.getBoundingInfo();
  90223. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90224. block.entries.push(entry);
  90225. }
  90226. };
  90227. return Octree;
  90228. }());
  90229. BABYLON.Octree = Octree;
  90230. })(BABYLON || (BABYLON = {}));
  90231. //# sourceMappingURL=babylon.octree.js.map
  90232. var BABYLON;
  90233. (function (BABYLON) {
  90234. var OctreeBlock = /** @class */ (function () {
  90235. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90236. this.entries = new Array();
  90237. this._boundingVectors = new Array();
  90238. this._capacity = capacity;
  90239. this._depth = depth;
  90240. this._maxDepth = maxDepth;
  90241. this._creationFunc = creationFunc;
  90242. this._minPoint = minPoint;
  90243. this._maxPoint = maxPoint;
  90244. this._boundingVectors.push(minPoint.clone());
  90245. this._boundingVectors.push(maxPoint.clone());
  90246. this._boundingVectors.push(minPoint.clone());
  90247. this._boundingVectors[2].x = maxPoint.x;
  90248. this._boundingVectors.push(minPoint.clone());
  90249. this._boundingVectors[3].y = maxPoint.y;
  90250. this._boundingVectors.push(minPoint.clone());
  90251. this._boundingVectors[4].z = maxPoint.z;
  90252. this._boundingVectors.push(maxPoint.clone());
  90253. this._boundingVectors[5].z = minPoint.z;
  90254. this._boundingVectors.push(maxPoint.clone());
  90255. this._boundingVectors[6].x = minPoint.x;
  90256. this._boundingVectors.push(maxPoint.clone());
  90257. this._boundingVectors[7].y = minPoint.y;
  90258. }
  90259. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90260. // Property
  90261. get: function () {
  90262. return this._capacity;
  90263. },
  90264. enumerable: true,
  90265. configurable: true
  90266. });
  90267. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90268. get: function () {
  90269. return this._minPoint;
  90270. },
  90271. enumerable: true,
  90272. configurable: true
  90273. });
  90274. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90275. get: function () {
  90276. return this._maxPoint;
  90277. },
  90278. enumerable: true,
  90279. configurable: true
  90280. });
  90281. // Methods
  90282. OctreeBlock.prototype.addEntry = function (entry) {
  90283. if (this.blocks) {
  90284. for (var index = 0; index < this.blocks.length; index++) {
  90285. var block = this.blocks[index];
  90286. block.addEntry(entry);
  90287. }
  90288. return;
  90289. }
  90290. this._creationFunc(entry, this);
  90291. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90292. this.createInnerBlocks();
  90293. }
  90294. };
  90295. OctreeBlock.prototype.addEntries = function (entries) {
  90296. for (var index = 0; index < entries.length; index++) {
  90297. var mesh = entries[index];
  90298. this.addEntry(mesh);
  90299. }
  90300. };
  90301. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90302. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90303. if (this.blocks) {
  90304. for (var index = 0; index < this.blocks.length; index++) {
  90305. var block = this.blocks[index];
  90306. block.select(frustumPlanes, selection, allowDuplicate);
  90307. }
  90308. return;
  90309. }
  90310. if (allowDuplicate) {
  90311. selection.concat(this.entries);
  90312. }
  90313. else {
  90314. selection.concatWithNoDuplicate(this.entries);
  90315. }
  90316. }
  90317. };
  90318. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90319. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90320. if (this.blocks) {
  90321. for (var index = 0; index < this.blocks.length; index++) {
  90322. var block = this.blocks[index];
  90323. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90324. }
  90325. return;
  90326. }
  90327. if (allowDuplicate) {
  90328. selection.concat(this.entries);
  90329. }
  90330. else {
  90331. selection.concatWithNoDuplicate(this.entries);
  90332. }
  90333. }
  90334. };
  90335. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90336. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90337. if (this.blocks) {
  90338. for (var index = 0; index < this.blocks.length; index++) {
  90339. var block = this.blocks[index];
  90340. block.intersectsRay(ray, selection);
  90341. }
  90342. return;
  90343. }
  90344. selection.concatWithNoDuplicate(this.entries);
  90345. }
  90346. };
  90347. OctreeBlock.prototype.createInnerBlocks = function () {
  90348. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90349. };
  90350. return OctreeBlock;
  90351. }());
  90352. BABYLON.OctreeBlock = OctreeBlock;
  90353. })(BABYLON || (BABYLON = {}));
  90354. //# sourceMappingURL=babylon.octreeBlock.js.map
  90355. var BABYLON;
  90356. (function (BABYLON) {
  90357. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90358. __extends(VRDistortionCorrectionPostProcess, _super);
  90359. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90360. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90361. 'LensCenter',
  90362. 'Scale',
  90363. 'ScaleIn',
  90364. 'HmdWarpParam'
  90365. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90366. _this._isRightEye = isRightEye;
  90367. _this._distortionFactors = vrMetrics.distortionK;
  90368. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90369. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90370. _this.adaptScaleToCurrentViewport = true;
  90371. _this.onSizeChangedObservable.add(function () {
  90372. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90373. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90374. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90375. });
  90376. _this.onApplyObservable.add(function (effect) {
  90377. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90378. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90379. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90380. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90381. });
  90382. return _this;
  90383. }
  90384. return VRDistortionCorrectionPostProcess;
  90385. }(BABYLON.PostProcess));
  90386. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90387. })(BABYLON || (BABYLON = {}));
  90388. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90389. var BABYLON;
  90390. (function (BABYLON) {
  90391. /**
  90392. * Postprocess used to generate anaglyphic rendering
  90393. */
  90394. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90395. __extends(AnaglyphPostProcess, _super);
  90396. /**
  90397. * Creates a new AnaglyphPostProcess
  90398. * @param name defines postprocess name
  90399. * @param options defines creation options or target ratio scale
  90400. * @param rigCameras defines cameras using this postprocess
  90401. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90402. * @param engine defines hosting engine
  90403. * @param reusable defines if the postprocess will be reused multiple times per frame
  90404. */
  90405. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90406. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90407. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90408. _this.onApplyObservable.add(function (effect) {
  90409. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90410. });
  90411. return _this;
  90412. }
  90413. return AnaglyphPostProcess;
  90414. }(BABYLON.PostProcess));
  90415. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90416. })(BABYLON || (BABYLON = {}));
  90417. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90418. var BABYLON;
  90419. (function (BABYLON) {
  90420. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90421. __extends(StereoscopicInterlacePostProcess, _super);
  90422. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90423. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90424. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90425. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90426. _this.onSizeChangedObservable.add(function () {
  90427. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90428. });
  90429. _this.onApplyObservable.add(function (effect) {
  90430. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90431. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90432. });
  90433. return _this;
  90434. }
  90435. return StereoscopicInterlacePostProcess;
  90436. }(BABYLON.PostProcess));
  90437. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90438. })(BABYLON || (BABYLON = {}));
  90439. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90440. var BABYLON;
  90441. (function (BABYLON) {
  90442. /**
  90443. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90444. * Screen rotation is taken into account.
  90445. */
  90446. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90447. function FreeCameraDeviceOrientationInput() {
  90448. var _this = this;
  90449. this._screenOrientationAngle = 0;
  90450. this._screenQuaternion = new BABYLON.Quaternion();
  90451. this._alpha = 0;
  90452. this._beta = 0;
  90453. this._gamma = 0;
  90454. this._orientationChanged = function () {
  90455. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90456. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90457. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90458. };
  90459. this._deviceOrientation = function (evt) {
  90460. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90461. _this._beta = evt.beta !== null ? evt.beta : 0;
  90462. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90463. };
  90464. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90465. this._orientationChanged();
  90466. }
  90467. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90468. get: function () {
  90469. return this._camera;
  90470. },
  90471. set: function (camera) {
  90472. this._camera = camera;
  90473. if (this._camera != null && !this._camera.rotationQuaternion) {
  90474. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90475. }
  90476. },
  90477. enumerable: true,
  90478. configurable: true
  90479. });
  90480. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90481. window.addEventListener("orientationchange", this._orientationChanged);
  90482. window.addEventListener("deviceorientation", this._deviceOrientation);
  90483. //In certain cases, the attach control is called AFTER orientation was changed,
  90484. //So this is needed.
  90485. this._orientationChanged();
  90486. };
  90487. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90488. window.removeEventListener("orientationchange", this._orientationChanged);
  90489. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90490. };
  90491. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90492. //if no device orientation provided, don't update the rotation.
  90493. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90494. if (!this._alpha)
  90495. return;
  90496. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90497. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90498. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90499. //Mirror on XY Plane
  90500. this._camera.rotationQuaternion.z *= -1;
  90501. this._camera.rotationQuaternion.w *= -1;
  90502. };
  90503. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90504. return "FreeCameraDeviceOrientationInput";
  90505. };
  90506. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90507. return "deviceOrientation";
  90508. };
  90509. return FreeCameraDeviceOrientationInput;
  90510. }());
  90511. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90512. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90513. })(BABYLON || (BABYLON = {}));
  90514. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90515. var BABYLON;
  90516. (function (BABYLON) {
  90517. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90518. function ArcRotateCameraVRDeviceOrientationInput() {
  90519. this.alphaCorrection = 1;
  90520. this.betaCorrection = 1;
  90521. this.gammaCorrection = 1;
  90522. this._alpha = 0;
  90523. this._gamma = 0;
  90524. this._dirty = false;
  90525. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90526. }
  90527. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90528. this.camera.attachControl(element, noPreventDefault);
  90529. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90530. };
  90531. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90532. if (evt.alpha !== null) {
  90533. this._alpha = +evt.alpha | 0;
  90534. }
  90535. if (evt.gamma !== null) {
  90536. this._gamma = +evt.gamma | 0;
  90537. }
  90538. this._dirty = true;
  90539. };
  90540. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90541. if (this._dirty) {
  90542. this._dirty = false;
  90543. if (this._gamma < 0) {
  90544. this._gamma = 180 + this._gamma;
  90545. }
  90546. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90547. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90548. }
  90549. };
  90550. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90551. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90552. };
  90553. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90554. return "ArcRotateCameraVRDeviceOrientationInput";
  90555. };
  90556. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90557. return "VRDeviceOrientation";
  90558. };
  90559. return ArcRotateCameraVRDeviceOrientationInput;
  90560. }());
  90561. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90562. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90563. })(BABYLON || (BABYLON = {}));
  90564. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90565. var BABYLON;
  90566. (function (BABYLON) {
  90567. var VRCameraMetrics = /** @class */ (function () {
  90568. function VRCameraMetrics() {
  90569. this.compensateDistortion = true;
  90570. }
  90571. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90572. get: function () {
  90573. return this.hResolution / (2 * this.vResolution);
  90574. },
  90575. enumerable: true,
  90576. configurable: true
  90577. });
  90578. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90579. get: function () {
  90580. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90581. },
  90582. enumerable: true,
  90583. configurable: true
  90584. });
  90585. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90586. get: function () {
  90587. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90588. var h = (4 * meters) / this.hScreenSize;
  90589. return BABYLON.Matrix.Translation(h, 0, 0);
  90590. },
  90591. enumerable: true,
  90592. configurable: true
  90593. });
  90594. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90595. get: function () {
  90596. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90597. var h = (4 * meters) / this.hScreenSize;
  90598. return BABYLON.Matrix.Translation(-h, 0, 0);
  90599. },
  90600. enumerable: true,
  90601. configurable: true
  90602. });
  90603. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90604. get: function () {
  90605. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90606. },
  90607. enumerable: true,
  90608. configurable: true
  90609. });
  90610. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90611. get: function () {
  90612. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90613. },
  90614. enumerable: true,
  90615. configurable: true
  90616. });
  90617. VRCameraMetrics.GetDefault = function () {
  90618. var result = new VRCameraMetrics();
  90619. result.hResolution = 1280;
  90620. result.vResolution = 800;
  90621. result.hScreenSize = 0.149759993;
  90622. result.vScreenSize = 0.0935999975;
  90623. result.vScreenCenter = 0.0467999987;
  90624. result.eyeToScreenDistance = 0.0410000011;
  90625. result.lensSeparationDistance = 0.0635000020;
  90626. result.interpupillaryDistance = 0.0640000030;
  90627. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90628. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90629. result.postProcessScaleFactor = 1.714605507808412;
  90630. result.lensCenterOffset = 0.151976421;
  90631. return result;
  90632. };
  90633. return VRCameraMetrics;
  90634. }());
  90635. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90636. })(BABYLON || (BABYLON = {}));
  90637. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90638. var BABYLON;
  90639. (function (BABYLON) {
  90640. /**
  90641. * This represents a WebVR camera.
  90642. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90643. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90644. */
  90645. var WebVRFreeCamera = /** @class */ (function (_super) {
  90646. __extends(WebVRFreeCamera, _super);
  90647. /**
  90648. * Instantiates a WebVRFreeCamera.
  90649. * @param name The name of the WebVRFreeCamera
  90650. * @param position The starting anchor position for the camera
  90651. * @param scene The scene the camera belongs to
  90652. * @param webVROptions a set of customizable options for the webVRCamera
  90653. */
  90654. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90655. if (webVROptions === void 0) { webVROptions = {}; }
  90656. var _this = _super.call(this, name, position, scene) || this;
  90657. _this.webVROptions = webVROptions;
  90658. /**
  90659. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90660. */
  90661. _this._vrDevice = null;
  90662. /**
  90663. * The rawPose of the vrDevice.
  90664. */
  90665. _this.rawPose = null;
  90666. _this._specsVersion = "1.1";
  90667. _this._attached = false;
  90668. _this._descendants = [];
  90669. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90670. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90671. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90672. _this._standingMatrix = null;
  90673. /**
  90674. * Represents device position in babylon space.
  90675. */
  90676. _this.devicePosition = BABYLON.Vector3.Zero();
  90677. /**
  90678. * Represents device rotation in babylon space.
  90679. */
  90680. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90681. /**
  90682. * The scale of the device to be used when translating from device space to babylon space.
  90683. */
  90684. _this.deviceScaleFactor = 1;
  90685. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90686. _this._worldToDevice = BABYLON.Matrix.Identity();
  90687. /**
  90688. * References to the webVR controllers for the vrDevice.
  90689. */
  90690. _this.controllers = [];
  90691. /**
  90692. * Emits an event when a controller is attached.
  90693. */
  90694. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90695. /**
  90696. * Emits an event when a controller's mesh has been loaded;
  90697. */
  90698. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90699. /**
  90700. * If the rig cameras be used as parent instead of this camera.
  90701. */
  90702. _this.rigParenting = true;
  90703. _this._defaultHeight = undefined;
  90704. _this._workingVector = BABYLON.Vector3.Zero();
  90705. _this._oneVector = BABYLON.Vector3.One();
  90706. _this._workingMatrix = BABYLON.Matrix.Identity();
  90707. _this._cache.position = BABYLON.Vector3.Zero();
  90708. if (webVROptions.defaultHeight) {
  90709. _this._defaultHeight = webVROptions.defaultHeight;
  90710. _this.position.y = _this._defaultHeight;
  90711. }
  90712. _this.minZ = 0.1;
  90713. //legacy support - the compensation boolean was removed.
  90714. if (arguments.length === 5) {
  90715. _this.webVROptions = arguments[4];
  90716. }
  90717. // default webVR options
  90718. if (_this.webVROptions.trackPosition == undefined) {
  90719. _this.webVROptions.trackPosition = true;
  90720. }
  90721. if (_this.webVROptions.controllerMeshes == undefined) {
  90722. _this.webVROptions.controllerMeshes = true;
  90723. }
  90724. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90725. _this.webVROptions.defaultLightingOnControllers = true;
  90726. }
  90727. _this.rotationQuaternion = new BABYLON.Quaternion();
  90728. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90729. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90730. }
  90731. //enable VR
  90732. var engine = _this.getEngine();
  90733. _this._onVREnabled = function (success) { if (success) {
  90734. _this.initControllers();
  90735. } };
  90736. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90737. engine.initWebVR().add(function (event) {
  90738. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90739. return;
  90740. }
  90741. _this._vrDevice = event.vrDisplay;
  90742. //reset the rig parameters.
  90743. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90744. if (_this._attached) {
  90745. _this.getEngine().enableVR();
  90746. }
  90747. });
  90748. if (typeof (VRFrameData) !== "undefined")
  90749. _this._frameData = new VRFrameData();
  90750. /**
  90751. * The idea behind the following lines:
  90752. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90753. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90754. * the second will not show it correctly.
  90755. *
  90756. * To solve this - each object that has the camera as parent will be added to a protected array.
  90757. * When the rig camera renders, it will take this array and set all of those to be its children.
  90758. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90759. * Amazing!
  90760. */
  90761. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90762. if (camera.parent === _this && _this.rigParenting) {
  90763. _this._descendants = _this.getDescendants(true, function (n) {
  90764. // don't take the cameras or the controllers!
  90765. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90766. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90767. return !isController && !isRigCamera;
  90768. });
  90769. _this._descendants.forEach(function (node) {
  90770. node.parent = camera;
  90771. });
  90772. }
  90773. });
  90774. scene.onAfterCameraRenderObservable.add(function (camera) {
  90775. if (camera.parent === _this && _this.rigParenting) {
  90776. _this._descendants.forEach(function (node) {
  90777. node.parent = _this;
  90778. });
  90779. }
  90780. });
  90781. return _this;
  90782. }
  90783. /**
  90784. * Gets the device distance from the ground in meters.
  90785. * @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.
  90786. */
  90787. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90788. if (this._standingMatrix) {
  90789. // Add standing matrix offset to get real offset from ground in room
  90790. this._standingMatrix.getTranslationToRef(this._workingVector);
  90791. return this._deviceRoomPosition.y + this._workingVector.y;
  90792. }
  90793. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90794. return this._defaultHeight || 0;
  90795. };
  90796. /**
  90797. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90798. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90799. */
  90800. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90801. var _this = this;
  90802. if (callback === void 0) { callback = function (bool) { }; }
  90803. // Use standing matrix if available
  90804. this.getEngine().initWebVRAsync().then(function (result) {
  90805. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90806. callback(false);
  90807. }
  90808. else {
  90809. _this._standingMatrix = new BABYLON.Matrix();
  90810. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90811. if (!_this.getScene().useRightHandedSystem) {
  90812. [2, 6, 8, 9, 14].forEach(function (num) {
  90813. if (_this._standingMatrix) {
  90814. _this._standingMatrix.m[num] *= -1;
  90815. }
  90816. });
  90817. }
  90818. callback(true);
  90819. }
  90820. });
  90821. };
  90822. /**
  90823. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90824. * @returns A promise with a boolean set to if the standing matrix is supported.
  90825. */
  90826. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90827. var _this = this;
  90828. return new Promise(function (res, rej) {
  90829. _this.useStandingMatrix(function (supported) {
  90830. res(supported);
  90831. });
  90832. });
  90833. };
  90834. /**
  90835. * Disposes the camera
  90836. */
  90837. WebVRFreeCamera.prototype.dispose = function () {
  90838. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90839. _super.prototype.dispose.call(this);
  90840. };
  90841. /**
  90842. * Gets a vrController by name.
  90843. * @param name The name of the controller to retreive
  90844. * @returns the controller matching the name specified or null if not found
  90845. */
  90846. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90847. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90848. var gp = _a[_i];
  90849. if (gp.hand === name) {
  90850. return gp;
  90851. }
  90852. }
  90853. return null;
  90854. };
  90855. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90856. /**
  90857. * The controller corrisponding to the users left hand.
  90858. */
  90859. get: function () {
  90860. if (!this._leftController) {
  90861. this._leftController = this.getControllerByName("left");
  90862. }
  90863. return this._leftController;
  90864. },
  90865. enumerable: true,
  90866. configurable: true
  90867. });
  90868. ;
  90869. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90870. /**
  90871. * The controller corrisponding to the users right hand.
  90872. */
  90873. get: function () {
  90874. if (!this._rightController) {
  90875. this._rightController = this.getControllerByName("right");
  90876. }
  90877. return this._rightController;
  90878. },
  90879. enumerable: true,
  90880. configurable: true
  90881. });
  90882. ;
  90883. /**
  90884. * Casts a ray forward from the vrCamera's gaze.
  90885. * @param length Length of the ray (default: 100)
  90886. * @returns the ray corrisponding to the gaze
  90887. */
  90888. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90889. if (length === void 0) { length = 100; }
  90890. if (this.leftCamera) {
  90891. // Use left eye to avoid computation to compute center on every call
  90892. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90893. }
  90894. else {
  90895. return _super.prototype.getForwardRay.call(this, length);
  90896. }
  90897. };
  90898. /**
  90899. * Updates the camera based on device's frame data
  90900. */
  90901. WebVRFreeCamera.prototype._checkInputs = function () {
  90902. if (this._vrDevice && this._vrDevice.isPresenting) {
  90903. this._vrDevice.getFrameData(this._frameData);
  90904. this.updateFromDevice(this._frameData.pose);
  90905. }
  90906. _super.prototype._checkInputs.call(this);
  90907. };
  90908. /**
  90909. * Updates the poseControlled values based on the input device pose.
  90910. * @param poseData Pose coming from the device
  90911. */
  90912. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90913. if (poseData && poseData.orientation) {
  90914. this.rawPose = poseData;
  90915. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90916. if (this.getScene().useRightHandedSystem) {
  90917. this._deviceRoomRotationQuaternion.z *= -1;
  90918. this._deviceRoomRotationQuaternion.w *= -1;
  90919. }
  90920. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90921. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90922. if (this.getScene().useRightHandedSystem) {
  90923. this._deviceRoomPosition.z *= -1;
  90924. }
  90925. }
  90926. }
  90927. };
  90928. /**
  90929. * WebVR's attach control will start broadcasting frames to the device.
  90930. * Note that in certain browsers (chrome for example) this function must be called
  90931. * within a user-interaction callback. Example:
  90932. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90933. *
  90934. * @param element html element to attach the vrDevice to
  90935. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90936. */
  90937. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90938. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90939. this._attached = true;
  90940. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90941. if (this._vrDevice) {
  90942. this.getEngine().enableVR();
  90943. }
  90944. };
  90945. /**
  90946. * Detaches the camera from the html element and disables VR
  90947. *
  90948. * @param element html element to detach from
  90949. */
  90950. WebVRFreeCamera.prototype.detachControl = function (element) {
  90951. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90952. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90953. _super.prototype.detachControl.call(this, element);
  90954. this._attached = false;
  90955. this.getEngine().disableVR();
  90956. };
  90957. /**
  90958. * @returns the name of this class
  90959. */
  90960. WebVRFreeCamera.prototype.getClassName = function () {
  90961. return "WebVRFreeCamera";
  90962. };
  90963. /**
  90964. * Calls resetPose on the vrDisplay
  90965. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90966. */
  90967. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90968. //uses the vrDisplay's "resetPose()".
  90969. //pitch and roll won't be affected.
  90970. this._vrDevice.resetPose();
  90971. };
  90972. /**
  90973. * Updates the rig cameras (left and right eye)
  90974. */
  90975. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90976. var camLeft = this._rigCameras[0];
  90977. var camRight = this._rigCameras[1];
  90978. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90979. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90980. camLeft.position.copyFrom(this._deviceRoomPosition);
  90981. camRight.position.copyFrom(this._deviceRoomPosition);
  90982. };
  90983. /**
  90984. * Updates the cached values of the camera
  90985. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90986. */
  90987. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90988. var _this = this;
  90989. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90990. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90991. if (!this.updateCacheCalled) {
  90992. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90993. this.updateCacheCalled = true;
  90994. this.update();
  90995. }
  90996. // Set working vector to the device position in room space rotated by the new rotation
  90997. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90998. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90999. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91000. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91001. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91002. // Add translation from anchor position
  91003. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91004. this._workingVector.addInPlace(this.position);
  91005. this._workingVector.subtractInPlace(this._cache.position);
  91006. this._deviceToWorld.setTranslation(this._workingVector);
  91007. // Set an inverted matrix to be used when updating the camera
  91008. this._deviceToWorld.invertToRef(this._worldToDevice);
  91009. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91010. this.controllers.forEach(function (controller) {
  91011. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91012. controller.update();
  91013. });
  91014. }
  91015. if (!ignoreParentClass) {
  91016. _super.prototype._updateCache.call(this);
  91017. }
  91018. this.updateCacheCalled = false;
  91019. };
  91020. /**
  91021. * Updates the current device position and rotation in the babylon world
  91022. */
  91023. WebVRFreeCamera.prototype.update = function () {
  91024. // Get current device position in babylon world
  91025. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91026. // Get current device rotation in babylon world
  91027. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91028. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91029. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91030. _super.prototype.update.call(this);
  91031. };
  91032. /**
  91033. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91034. * @returns an identity matrix
  91035. */
  91036. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91037. return BABYLON.Matrix.Identity();
  91038. };
  91039. /**
  91040. * This function is called by the two RIG cameras.
  91041. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91042. */
  91043. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91044. var _this = this;
  91045. // Update the parent camera prior to using a child camera to avoid desynchronization
  91046. var parentCamera = this._cameraRigParams["parentCamera"];
  91047. parentCamera._updateCache();
  91048. //WebVR 1.1
  91049. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91050. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91051. if (!this.getScene().useRightHandedSystem) {
  91052. [2, 6, 8, 9, 14].forEach(function (num) {
  91053. _this._webvrViewMatrix.m[num] *= -1;
  91054. });
  91055. }
  91056. // update the camera rotation matrix
  91057. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91058. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91059. // Computing target and final matrix
  91060. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91061. // should the view matrix be updated with scale and position offset?
  91062. if (parentCamera.deviceScaleFactor !== 1) {
  91063. this._webvrViewMatrix.invert();
  91064. // scale the position, if set
  91065. if (parentCamera.deviceScaleFactor) {
  91066. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91067. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91068. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91069. }
  91070. this._webvrViewMatrix.invert();
  91071. }
  91072. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91073. // Compute global position
  91074. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91075. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91076. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91077. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91078. this._markSyncedWithParent();
  91079. return this._webvrViewMatrix;
  91080. };
  91081. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91082. var _this = this;
  91083. var parentCamera = this.parent;
  91084. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91085. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91086. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91087. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91088. //babylon compatible matrix
  91089. if (!this.getScene().useRightHandedSystem) {
  91090. [8, 9, 10, 11].forEach(function (num) {
  91091. _this._projectionMatrix.m[num] *= -1;
  91092. });
  91093. }
  91094. return this._projectionMatrix;
  91095. };
  91096. /**
  91097. * Initializes the controllers and their meshes
  91098. */
  91099. WebVRFreeCamera.prototype.initControllers = function () {
  91100. var _this = this;
  91101. this.controllers = [];
  91102. var manager = this.getScene().gamepadManager;
  91103. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91104. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91105. var webVrController = gamepad;
  91106. if (webVrController.defaultModel) {
  91107. webVrController.defaultModel.setEnabled(false);
  91108. }
  91109. if (webVrController.hand === "right") {
  91110. _this._rightController = null;
  91111. }
  91112. if (webVrController.hand === "left") {
  91113. _this._leftController = null;
  91114. }
  91115. var controllerIndex = _this.controllers.indexOf(webVrController);
  91116. if (controllerIndex !== -1) {
  91117. _this.controllers.splice(controllerIndex, 1);
  91118. }
  91119. }
  91120. });
  91121. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91122. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91123. var webVrController_1 = gamepad;
  91124. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91125. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91126. if (_this.webVROptions.controllerMeshes) {
  91127. if (webVrController_1.defaultModel) {
  91128. webVrController_1.defaultModel.setEnabled(true);
  91129. }
  91130. else {
  91131. // Load the meshes
  91132. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91133. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91134. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91135. if (_this.webVROptions.defaultLightingOnControllers) {
  91136. if (!_this._lightOnControllers) {
  91137. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91138. }
  91139. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91140. var children = mesh.getChildren();
  91141. if (children.length !== 0) {
  91142. children.forEach(function (mesh) {
  91143. light.includedOnlyMeshes.push(mesh);
  91144. activateLightOnSubMeshes_1(mesh, light);
  91145. });
  91146. }
  91147. };
  91148. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91149. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91150. }
  91151. });
  91152. }
  91153. }
  91154. webVrController_1.attachToPoseControlledCamera(_this);
  91155. // since this is async - sanity check. Is the controller already stored?
  91156. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91157. //add to the controllers array
  91158. _this.controllers.push(webVrController_1);
  91159. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91160. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91161. // So we're overriding setting left & right manually to be sure
  91162. var firstViveWandDetected = false;
  91163. for (var i = 0; i < _this.controllers.length; i++) {
  91164. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91165. if (!firstViveWandDetected) {
  91166. firstViveWandDetected = true;
  91167. _this.controllers[i].hand = "left";
  91168. }
  91169. else {
  91170. _this.controllers[i].hand = "right";
  91171. }
  91172. }
  91173. }
  91174. //did we find enough controllers? Great! let the developer know.
  91175. if (_this.controllers.length >= 2) {
  91176. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91177. }
  91178. }
  91179. }
  91180. });
  91181. };
  91182. return WebVRFreeCamera;
  91183. }(BABYLON.FreeCamera));
  91184. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91185. })(BABYLON || (BABYLON = {}));
  91186. //# sourceMappingURL=babylon.webVRCamera.js.map
  91187. var BABYLON;
  91188. (function (BABYLON) {
  91189. // We're mainly based on the logic defined into the FreeCamera code
  91190. /**
  91191. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91192. * being tilted forward or back and left or right.
  91193. */
  91194. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91195. __extends(DeviceOrientationCamera, _super);
  91196. /**
  91197. * Creates a new device orientation camera
  91198. * @param name The name of the camera
  91199. * @param position The start position camera
  91200. * @param scene The scene the camera belongs to
  91201. */
  91202. function DeviceOrientationCamera(name, position, scene) {
  91203. var _this = _super.call(this, name, position, scene) || this;
  91204. _this._quaternionCache = new BABYLON.Quaternion();
  91205. _this.inputs.addDeviceOrientation();
  91206. return _this;
  91207. }
  91208. /**
  91209. * Gets the current instance class name ("DeviceOrientationCamera").
  91210. * This helps avoiding instanceof at run time.
  91211. * @returns the class name
  91212. */
  91213. DeviceOrientationCamera.prototype.getClassName = function () {
  91214. return "DeviceOrientationCamera";
  91215. };
  91216. /**
  91217. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91218. */
  91219. DeviceOrientationCamera.prototype._checkInputs = function () {
  91220. _super.prototype._checkInputs.call(this);
  91221. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91222. if (this._initialQuaternion) {
  91223. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91224. }
  91225. };
  91226. /**
  91227. * Reset the camera to its default orientation on the specified axis only.
  91228. * @param axis The axis to reset
  91229. */
  91230. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91231. var _this = this;
  91232. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91233. //can only work if this camera has a rotation quaternion already.
  91234. if (!this.rotationQuaternion)
  91235. return;
  91236. if (!this._initialQuaternion) {
  91237. this._initialQuaternion = new BABYLON.Quaternion();
  91238. }
  91239. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91240. ['x', 'y', 'z'].forEach(function (axisName) {
  91241. if (!axis[axisName]) {
  91242. _this._initialQuaternion[axisName] = 0;
  91243. }
  91244. else {
  91245. _this._initialQuaternion[axisName] *= -1;
  91246. }
  91247. });
  91248. this._initialQuaternion.normalize();
  91249. //force rotation update
  91250. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91251. };
  91252. return DeviceOrientationCamera;
  91253. }(BABYLON.FreeCamera));
  91254. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91255. })(BABYLON || (BABYLON = {}));
  91256. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91257. var BABYLON;
  91258. (function (BABYLON) {
  91259. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91260. __extends(VRDeviceOrientationFreeCamera, _super);
  91261. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91262. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91263. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91264. var _this = _super.call(this, name, position, scene) || this;
  91265. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91266. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91267. return _this;
  91268. }
  91269. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91270. return "VRDeviceOrientationFreeCamera";
  91271. };
  91272. return VRDeviceOrientationFreeCamera;
  91273. }(BABYLON.DeviceOrientationCamera));
  91274. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91275. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91276. __extends(VRDeviceOrientationGamepadCamera, _super);
  91277. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91278. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91279. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91280. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91281. _this.inputs.addGamepad();
  91282. return _this;
  91283. }
  91284. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91285. return "VRDeviceOrientationGamepadCamera";
  91286. };
  91287. return VRDeviceOrientationGamepadCamera;
  91288. }(VRDeviceOrientationFreeCamera));
  91289. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91290. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91291. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91292. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91293. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91294. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91295. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91296. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91297. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91298. _this.inputs.addVRDeviceOrientation();
  91299. return _this;
  91300. }
  91301. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91302. return "VRDeviceOrientationArcRotateCamera";
  91303. };
  91304. return VRDeviceOrientationArcRotateCamera;
  91305. }(BABYLON.ArcRotateCamera));
  91306. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91307. })(BABYLON || (BABYLON = {}));
  91308. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91309. var BABYLON;
  91310. (function (BABYLON) {
  91311. /**
  91312. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91313. */
  91314. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91315. __extends(AnaglyphFreeCamera, _super);
  91316. /**
  91317. * Creates a new AnaglyphFreeCamera
  91318. * @param name defines camera name
  91319. * @param position defines initial position
  91320. * @param interaxialDistance defines distance between each color axis
  91321. * @param scene defines the hosting scene
  91322. */
  91323. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91324. var _this = _super.call(this, name, position, scene) || this;
  91325. _this.interaxialDistance = interaxialDistance;
  91326. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91327. return _this;
  91328. }
  91329. /**
  91330. * Gets camera class name
  91331. * @returns AnaglyphFreeCamera
  91332. */
  91333. AnaglyphFreeCamera.prototype.getClassName = function () {
  91334. return "AnaglyphFreeCamera";
  91335. };
  91336. return AnaglyphFreeCamera;
  91337. }(BABYLON.FreeCamera));
  91338. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91339. /**
  91340. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91341. */
  91342. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91343. __extends(AnaglyphArcRotateCamera, _super);
  91344. /**
  91345. * Creates a new AnaglyphArcRotateCamera
  91346. * @param name defines camera name
  91347. * @param alpha defines alpha angle (in radians)
  91348. * @param beta defines beta angle (in radians)
  91349. * @param radius defines radius
  91350. * @param target defines camera target
  91351. * @param interaxialDistance defines distance between each color axis
  91352. * @param scene defines the hosting scene
  91353. */
  91354. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91355. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91356. _this.interaxialDistance = interaxialDistance;
  91357. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91358. return _this;
  91359. }
  91360. /**
  91361. * Gets camera class name
  91362. * @returns AnaglyphArcRotateCamera
  91363. */
  91364. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91365. return "AnaglyphArcRotateCamera";
  91366. };
  91367. return AnaglyphArcRotateCamera;
  91368. }(BABYLON.ArcRotateCamera));
  91369. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91370. /**
  91371. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91372. */
  91373. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91374. __extends(AnaglyphGamepadCamera, _super);
  91375. /**
  91376. * Creates a new AnaglyphGamepadCamera
  91377. * @param name defines camera name
  91378. * @param position defines initial position
  91379. * @param interaxialDistance defines distance between each color axis
  91380. * @param scene defines the hosting scene
  91381. */
  91382. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91383. var _this = _super.call(this, name, position, scene) || this;
  91384. _this.interaxialDistance = interaxialDistance;
  91385. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91386. return _this;
  91387. }
  91388. /**
  91389. * Gets camera class name
  91390. * @returns AnaglyphGamepadCamera
  91391. */
  91392. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91393. return "AnaglyphGamepadCamera";
  91394. };
  91395. return AnaglyphGamepadCamera;
  91396. }(BABYLON.GamepadCamera));
  91397. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91398. /**
  91399. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91400. */
  91401. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91402. __extends(AnaglyphUniversalCamera, _super);
  91403. /**
  91404. * Creates a new AnaglyphUniversalCamera
  91405. * @param name defines camera name
  91406. * @param position defines initial position
  91407. * @param interaxialDistance defines distance between each color axis
  91408. * @param scene defines the hosting scene
  91409. */
  91410. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91411. var _this = _super.call(this, name, position, scene) || this;
  91412. _this.interaxialDistance = interaxialDistance;
  91413. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91414. return _this;
  91415. }
  91416. /**
  91417. * Gets camera class name
  91418. * @returns AnaglyphUniversalCamera
  91419. */
  91420. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91421. return "AnaglyphUniversalCamera";
  91422. };
  91423. return AnaglyphUniversalCamera;
  91424. }(BABYLON.UniversalCamera));
  91425. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91426. /**
  91427. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91428. */
  91429. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91430. __extends(StereoscopicFreeCamera, _super);
  91431. /**
  91432. * Creates a new StereoscopicFreeCamera
  91433. * @param name defines camera name
  91434. * @param position defines initial position
  91435. * @param interaxialDistance defines distance between each color axis
  91436. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91437. * @param scene defines the hosting scene
  91438. */
  91439. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91440. var _this = _super.call(this, name, position, scene) || this;
  91441. _this.interaxialDistance = interaxialDistance;
  91442. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91443. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91444. return _this;
  91445. }
  91446. /**
  91447. * Gets camera class name
  91448. * @returns StereoscopicFreeCamera
  91449. */
  91450. StereoscopicFreeCamera.prototype.getClassName = function () {
  91451. return "StereoscopicFreeCamera";
  91452. };
  91453. return StereoscopicFreeCamera;
  91454. }(BABYLON.FreeCamera));
  91455. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91456. /**
  91457. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91458. */
  91459. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91460. __extends(StereoscopicArcRotateCamera, _super);
  91461. /**
  91462. * Creates a new StereoscopicArcRotateCamera
  91463. * @param name defines camera name
  91464. * @param alpha defines alpha angle (in radians)
  91465. * @param beta defines beta angle (in radians)
  91466. * @param radius defines radius
  91467. * @param target defines camera target
  91468. * @param interaxialDistance defines distance between each color axis
  91469. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91470. * @param scene defines the hosting scene
  91471. */
  91472. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91473. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91474. _this.interaxialDistance = interaxialDistance;
  91475. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91476. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91477. return _this;
  91478. }
  91479. /**
  91480. * Gets camera class name
  91481. * @returns StereoscopicArcRotateCamera
  91482. */
  91483. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91484. return "StereoscopicArcRotateCamera";
  91485. };
  91486. return StereoscopicArcRotateCamera;
  91487. }(BABYLON.ArcRotateCamera));
  91488. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91489. /**
  91490. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91491. */
  91492. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91493. __extends(StereoscopicGamepadCamera, _super);
  91494. /**
  91495. * Creates a new StereoscopicGamepadCamera
  91496. * @param name defines camera name
  91497. * @param position defines initial position
  91498. * @param interaxialDistance defines distance between each color axis
  91499. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91500. * @param scene defines the hosting scene
  91501. */
  91502. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91503. var _this = _super.call(this, name, position, scene) || this;
  91504. _this.interaxialDistance = interaxialDistance;
  91505. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91506. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91507. return _this;
  91508. }
  91509. /**
  91510. * Gets camera class name
  91511. * @returns StereoscopicGamepadCamera
  91512. */
  91513. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91514. return "StereoscopicGamepadCamera";
  91515. };
  91516. return StereoscopicGamepadCamera;
  91517. }(BABYLON.GamepadCamera));
  91518. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91519. /**
  91520. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91521. */
  91522. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91523. __extends(StereoscopicUniversalCamera, _super);
  91524. /**
  91525. * Creates a new StereoscopicUniversalCamera
  91526. * @param name defines camera name
  91527. * @param position defines initial position
  91528. * @param interaxialDistance defines distance between each color axis
  91529. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91530. * @param scene defines the hosting scene
  91531. */
  91532. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91533. var _this = _super.call(this, name, position, scene) || this;
  91534. _this.interaxialDistance = interaxialDistance;
  91535. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91536. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91537. return _this;
  91538. }
  91539. /**
  91540. * Gets camera class name
  91541. * @returns StereoscopicUniversalCamera
  91542. */
  91543. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91544. return "StereoscopicUniversalCamera";
  91545. };
  91546. return StereoscopicUniversalCamera;
  91547. }(BABYLON.UniversalCamera));
  91548. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91549. })(BABYLON || (BABYLON = {}));
  91550. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91551. var BABYLON;
  91552. (function (BABYLON) {
  91553. var VRExperienceHelperGazer = /** @class */ (function () {
  91554. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91555. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91556. this.scene = scene;
  91557. this._pointerDownOnMeshAsked = false;
  91558. this._isActionableMesh = false;
  91559. this._teleportationRequestInitiated = false;
  91560. this._teleportationBackRequestInitiated = false;
  91561. this._rotationRightAsked = false;
  91562. this._rotationLeftAsked = false;
  91563. this._dpadPressed = true;
  91564. this._activePointer = false;
  91565. this._id = VRExperienceHelperGazer._idCounter++;
  91566. // Gaze tracker
  91567. if (!gazeTrackerToClone) {
  91568. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91569. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91570. this._gazeTracker.isPickable = false;
  91571. this._gazeTracker.isVisible = false;
  91572. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91573. targetMat.specularColor = BABYLON.Color3.Black();
  91574. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91575. targetMat.backFaceCulling = false;
  91576. this._gazeTracker.material = targetMat;
  91577. }
  91578. else {
  91579. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91580. }
  91581. }
  91582. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91583. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91584. };
  91585. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91586. this._pointerDownOnMeshAsked = true;
  91587. if (this._currentHit) {
  91588. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91589. }
  91590. };
  91591. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91592. if (this._currentHit) {
  91593. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91594. }
  91595. this._pointerDownOnMeshAsked = false;
  91596. };
  91597. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91598. this._activePointer = true;
  91599. };
  91600. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91601. this._activePointer = false;
  91602. };
  91603. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91604. if (distance === void 0) { distance = 100; }
  91605. };
  91606. VRExperienceHelperGazer.prototype.dispose = function () {
  91607. this._interactionsEnabled = false;
  91608. this._teleportationEnabled = false;
  91609. if (this._gazeTracker) {
  91610. this._gazeTracker.dispose();
  91611. }
  91612. };
  91613. VRExperienceHelperGazer._idCounter = 0;
  91614. return VRExperienceHelperGazer;
  91615. }());
  91616. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91617. __extends(VRExperienceHelperControllerGazer, _super);
  91618. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91619. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91620. _this.webVRController = webVRController;
  91621. // Laser pointer
  91622. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91623. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91624. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91625. laserPointerMaterial.alpha = 0.6;
  91626. _this._laserPointer.material = laserPointerMaterial;
  91627. _this._laserPointer.rotation.x = Math.PI / 2;
  91628. _this._laserPointer.position.z = -0.5;
  91629. _this._laserPointer.isVisible = false;
  91630. _this._laserPointer.isPickable = false;
  91631. if (!webVRController.mesh) {
  91632. // Create an empty mesh that is used prior to loading the high quality model
  91633. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91634. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91635. preloadPointerPose.rotation.x = -0.7;
  91636. preloadMesh.addChild(preloadPointerPose);
  91637. webVRController.attachToMesh(preloadMesh);
  91638. }
  91639. _this._setLaserPointerParent(webVRController.mesh);
  91640. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91641. _this._setLaserPointerParent(mesh);
  91642. });
  91643. return _this;
  91644. }
  91645. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91646. return this.webVRController.getForwardRay(length);
  91647. };
  91648. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91649. _super.prototype._activatePointer.call(this);
  91650. this._laserPointer.isVisible = true;
  91651. };
  91652. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91653. _super.prototype._deactivatePointer.call(this);
  91654. this._laserPointer.isVisible = false;
  91655. };
  91656. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91657. this._laserPointer.material.emissiveColor = color;
  91658. };
  91659. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91660. var makeNotPick = function (root) {
  91661. root.name += " laserPointer";
  91662. root.isPickable = false;
  91663. root.getChildMeshes().forEach(function (c) {
  91664. makeNotPick(c);
  91665. });
  91666. };
  91667. makeNotPick(mesh);
  91668. var childMeshes = mesh.getChildMeshes();
  91669. this.webVRController._pointingPoseNode = null;
  91670. for (var i = 0; i < childMeshes.length; i++) {
  91671. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91672. mesh = childMeshes[i];
  91673. this.webVRController._pointingPoseNode = mesh;
  91674. break;
  91675. }
  91676. }
  91677. this._laserPointer.parent = mesh;
  91678. };
  91679. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91680. if (distance === void 0) { distance = 100; }
  91681. this._laserPointer.scaling.y = distance;
  91682. this._laserPointer.position.z = -distance / 2;
  91683. };
  91684. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91685. _super.prototype.dispose.call(this);
  91686. this._laserPointer.dispose();
  91687. if (this._meshAttachedObserver) {
  91688. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91689. }
  91690. };
  91691. return VRExperienceHelperControllerGazer;
  91692. }(VRExperienceHelperGazer));
  91693. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91694. __extends(VRExperienceHelperCameraGazer, _super);
  91695. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91696. var _this = _super.call(this, scene) || this;
  91697. _this.getCamera = getCamera;
  91698. return _this;
  91699. }
  91700. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91701. var camera = this.getCamera();
  91702. if (camera) {
  91703. return camera.getForwardRay(length);
  91704. }
  91705. else {
  91706. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91707. }
  91708. };
  91709. return VRExperienceHelperCameraGazer;
  91710. }(VRExperienceHelperGazer));
  91711. /**
  91712. * Helps to quickly add VR support to an existing scene.
  91713. * See http://doc.babylonjs.com/how_to/webvr_helper
  91714. */
  91715. var VRExperienceHelper = /** @class */ (function () {
  91716. /**
  91717. * Instantiates a VRExperienceHelper.
  91718. * Helps to quickly add VR support to an existing scene.
  91719. * @param scene The scene the VRExperienceHelper belongs to.
  91720. * @param webVROptions Options to modify the vr experience helper's behavior.
  91721. */
  91722. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91723. if (webVROptions === void 0) { webVROptions = {}; }
  91724. var _this = this;
  91725. this.webVROptions = webVROptions;
  91726. // Can the system support WebVR, even if a headset isn't plugged in?
  91727. this._webVRsupported = false;
  91728. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91729. this._webVRready = false;
  91730. // Are we waiting for the requestPresent callback to complete?
  91731. this._webVRrequesting = false;
  91732. // Are we presenting to the headset right now?
  91733. this._webVRpresenting = false;
  91734. // Are we presenting in the fullscreen fallback?
  91735. this._fullscreenVRpresenting = false;
  91736. /**
  91737. * Observable raised when entering VR.
  91738. */
  91739. this.onEnteringVRObservable = new BABYLON.Observable();
  91740. /**
  91741. * Observable raised when exiting VR.
  91742. */
  91743. this.onExitingVRObservable = new BABYLON.Observable();
  91744. /**
  91745. * Observable raised when controller mesh is loaded.
  91746. */
  91747. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91748. this._useCustomVRButton = false;
  91749. this._teleportationRequested = false;
  91750. this._teleportActive = false;
  91751. this._floorMeshesCollection = [];
  91752. this._rotationAllowed = true;
  91753. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91754. this._isDefaultTeleportationTarget = true;
  91755. this._teleportationFillColor = "#444444";
  91756. this._teleportationBorderColor = "#FFFFFF";
  91757. this._rotationAngle = 0;
  91758. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91759. this._padSensibilityUp = 0.65;
  91760. this._padSensibilityDown = 0.35;
  91761. this.leftController = null;
  91762. this.rightController = null;
  91763. /**
  91764. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91765. */
  91766. this.onNewMeshSelected = new BABYLON.Observable();
  91767. /**
  91768. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91769. */
  91770. this.onNewMeshPicked = new BABYLON.Observable();
  91771. /**
  91772. * Observable raised before camera teleportation
  91773. */
  91774. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91775. /**
  91776. * Observable raised after camera teleportation
  91777. */
  91778. this.onAfterCameraTeleport = new BABYLON.Observable();
  91779. /**
  91780. * Observable raised when current selected mesh gets unselected
  91781. */
  91782. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91783. /**
  91784. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91785. */
  91786. this.teleportationEnabled = true;
  91787. this._teleportationInitialized = false;
  91788. this._interactionsEnabled = false;
  91789. this._interactionsRequested = false;
  91790. this._displayGaze = true;
  91791. this._displayLaserPointer = true;
  91792. this._onResize = function () {
  91793. _this.moveButtonToBottomRight();
  91794. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91795. _this.exitVR();
  91796. }
  91797. };
  91798. this._onFullscreenChange = function () {
  91799. if (document.fullscreen !== undefined) {
  91800. _this._fullscreenVRpresenting = document.fullscreen;
  91801. }
  91802. else if (document.mozFullScreen !== undefined) {
  91803. _this._fullscreenVRpresenting = document.mozFullScreen;
  91804. }
  91805. else if (document.webkitIsFullScreen !== undefined) {
  91806. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91807. }
  91808. else if (document.msIsFullScreen !== undefined) {
  91809. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91810. }
  91811. else if (document.msFullscreenElement !== undefined) {
  91812. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91813. }
  91814. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91815. _this.exitVR();
  91816. if (!_this._useCustomVRButton) {
  91817. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91818. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91819. }
  91820. }
  91821. };
  91822. this.beforeRender = function () {
  91823. if (_this.leftController && _this.leftController._activePointer) {
  91824. _this._castRayAndSelectObject(_this.leftController);
  91825. }
  91826. if (_this.rightController && _this.rightController._activePointer) {
  91827. _this._castRayAndSelectObject(_this.rightController);
  91828. }
  91829. if (_this._noControllerIsActive) {
  91830. _this._castRayAndSelectObject(_this._cameraGazer);
  91831. }
  91832. else {
  91833. _this._cameraGazer._gazeTracker.isVisible = false;
  91834. }
  91835. };
  91836. this._onNewGamepadConnected = function (gamepad) {
  91837. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91838. if (gamepad.leftStick) {
  91839. gamepad.onleftstickchanged(function (stickValues) {
  91840. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91841. // Listening to classic/xbox gamepad only if no VR controller is active
  91842. if ((!_this.leftController && !_this.rightController) ||
  91843. ((_this.leftController && !_this.leftController._activePointer) &&
  91844. (_this.rightController && !_this.rightController._activePointer))) {
  91845. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91846. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91847. }
  91848. }
  91849. });
  91850. }
  91851. if (gamepad.rightStick) {
  91852. gamepad.onrightstickchanged(function (stickValues) {
  91853. if (_this._teleportationInitialized) {
  91854. _this._checkRotate(stickValues, _this._cameraGazer);
  91855. }
  91856. });
  91857. }
  91858. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91859. gamepad.onbuttondown(function (buttonPressed) {
  91860. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91861. _this._cameraGazer._selectionPointerDown();
  91862. }
  91863. });
  91864. gamepad.onbuttonup(function (buttonPressed) {
  91865. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91866. _this._cameraGazer._selectionPointerUp();
  91867. }
  91868. });
  91869. }
  91870. }
  91871. else {
  91872. var webVRController = gamepad;
  91873. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91874. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91875. _this.rightController = controller;
  91876. }
  91877. else {
  91878. _this.leftController = controller;
  91879. }
  91880. _this._tryEnableInteractionOnController(controller);
  91881. }
  91882. };
  91883. // 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
  91884. this._tryEnableInteractionOnController = function (controller) {
  91885. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91886. _this._enableInteractionOnController(controller);
  91887. }
  91888. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91889. _this._enableTeleportationOnController(controller);
  91890. }
  91891. };
  91892. this._onNewGamepadDisconnected = function (gamepad) {
  91893. if (gamepad instanceof BABYLON.WebVRController) {
  91894. if (gamepad.hand === "left" && _this.leftController != null) {
  91895. _this.leftController.dispose();
  91896. _this.leftController = null;
  91897. }
  91898. if (gamepad.hand === "right" && _this.rightController != null) {
  91899. _this.rightController.dispose();
  91900. _this.rightController = null;
  91901. }
  91902. }
  91903. };
  91904. this._workingVector = BABYLON.Vector3.Zero();
  91905. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91906. this._workingMatrix = BABYLON.Matrix.Identity();
  91907. this._scene = scene;
  91908. this._canvas = scene.getEngine().getRenderingCanvas();
  91909. // Parse options
  91910. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91911. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91912. }
  91913. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91914. webVROptions.createDeviceOrientationCamera = true;
  91915. }
  91916. if (webVROptions.laserToggle === undefined) {
  91917. webVROptions.laserToggle = true;
  91918. }
  91919. if (webVROptions.defaultHeight === undefined) {
  91920. webVROptions.defaultHeight = 1.7;
  91921. }
  91922. if (webVROptions.useCustomVRButton) {
  91923. this._useCustomVRButton = true;
  91924. if (webVROptions.customVRButton) {
  91925. this._btnVR = webVROptions.customVRButton;
  91926. }
  91927. }
  91928. if (webVROptions.rayLength) {
  91929. this._rayLength = webVROptions.rayLength;
  91930. }
  91931. this._defaultHeight = webVROptions.defaultHeight;
  91932. if (webVROptions.positionScale) {
  91933. this._rayLength *= webVROptions.positionScale;
  91934. this._defaultHeight *= webVROptions.positionScale;
  91935. }
  91936. // Set position
  91937. if (this._scene.activeCamera) {
  91938. this._position = this._scene.activeCamera.position.clone();
  91939. }
  91940. else {
  91941. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91942. }
  91943. // Set non-vr camera
  91944. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91945. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91946. // Copy data from existing camera
  91947. if (this._scene.activeCamera) {
  91948. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91949. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91950. // Set rotation from previous camera
  91951. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91952. var targetCamera = this._scene.activeCamera;
  91953. if (targetCamera.rotationQuaternion) {
  91954. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91955. }
  91956. else {
  91957. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91958. }
  91959. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91960. }
  91961. }
  91962. this._scene.activeCamera = this._deviceOrientationCamera;
  91963. if (this._canvas) {
  91964. this._scene.activeCamera.attachControl(this._canvas);
  91965. }
  91966. }
  91967. else {
  91968. this._existingCamera = this._scene.activeCamera;
  91969. }
  91970. // Create VR cameras
  91971. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91972. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91973. }
  91974. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91975. this._webVRCamera.useStandingMatrix();
  91976. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91977. // Create default button
  91978. if (!this._useCustomVRButton) {
  91979. this._btnVR = document.createElement("BUTTON");
  91980. this._btnVR.className = "babylonVRicon";
  91981. this._btnVR.id = "babylonVRiconbtn";
  91982. this._btnVR.title = "Click to switch to VR";
  91983. 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) }";
  91984. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91985. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91986. // css += ".babylonVRicon.vrdisplaysupported { }";
  91987. // css += ".babylonVRicon.vrdisplayready { }";
  91988. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91989. var style = document.createElement('style');
  91990. style.appendChild(document.createTextNode(css));
  91991. document.getElementsByTagName('head')[0].appendChild(style);
  91992. this.moveButtonToBottomRight();
  91993. }
  91994. // VR button click event
  91995. if (this._btnVR) {
  91996. this._btnVR.addEventListener("click", function () {
  91997. if (!_this.isInVRMode) {
  91998. _this.enterVR();
  91999. }
  92000. else {
  92001. _this.exitVR();
  92002. }
  92003. });
  92004. }
  92005. // Window events
  92006. window.addEventListener("resize", this._onResize);
  92007. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92008. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92009. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92010. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92011. document.onmsfullscreenchange = this._onFullscreenChange;
  92012. // Display vr button when headset is connected
  92013. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92014. this.displayVRButton();
  92015. }
  92016. else {
  92017. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92018. if (e.vrDisplay) {
  92019. _this.displayVRButton();
  92020. }
  92021. });
  92022. }
  92023. // Exiting VR mode using 'ESC' key on desktop
  92024. this._onKeyDown = function (event) {
  92025. if (event.keyCode === 27 && _this.isInVRMode) {
  92026. _this.exitVR();
  92027. }
  92028. };
  92029. document.addEventListener("keydown", this._onKeyDown);
  92030. // Exiting VR mode double tapping the touch screen
  92031. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92032. if (_this.isInVRMode) {
  92033. _this.exitVR();
  92034. if (_this._fullscreenVRpresenting) {
  92035. _this._scene.getEngine().switchFullscreen(true);
  92036. }
  92037. }
  92038. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92039. // Listen for WebVR display changes
  92040. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92041. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92042. this._onVRRequestPresentStart = function () {
  92043. _this._webVRrequesting = true;
  92044. _this.updateButtonVisibility();
  92045. };
  92046. this._onVRRequestPresentComplete = function (success) {
  92047. _this._webVRrequesting = false;
  92048. _this.updateButtonVisibility();
  92049. };
  92050. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92051. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92052. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92053. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92054. scene.onDisposeObservable.add(function () {
  92055. _this.dispose();
  92056. });
  92057. // Gamepad connection events
  92058. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92059. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92060. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92061. this.updateButtonVisibility();
  92062. //create easing functions
  92063. this._circleEase = new BABYLON.CircleEase();
  92064. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92065. if (this.webVROptions.floorMeshes) {
  92066. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92067. }
  92068. }
  92069. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92070. /** Return this.onEnteringVRObservable
  92071. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92072. */
  92073. get: function () {
  92074. return this.onEnteringVRObservable;
  92075. },
  92076. enumerable: true,
  92077. configurable: true
  92078. });
  92079. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92080. /** Return this.onExitingVRObservable
  92081. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92082. */
  92083. get: function () {
  92084. return this.onExitingVRObservable;
  92085. },
  92086. enumerable: true,
  92087. configurable: true
  92088. });
  92089. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92090. /** Return this.onControllerMeshLoadedObservable
  92091. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92092. */
  92093. get: function () {
  92094. return this.onControllerMeshLoadedObservable;
  92095. },
  92096. enumerable: true,
  92097. configurable: true
  92098. });
  92099. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92100. /**
  92101. * The mesh used to display where the user is going to teleport.
  92102. */
  92103. get: function () {
  92104. return this._teleportationTarget;
  92105. },
  92106. /**
  92107. * Sets the mesh to be used to display where the user is going to teleport.
  92108. */
  92109. set: function (value) {
  92110. if (value) {
  92111. value.name = "teleportationTarget";
  92112. this._isDefaultTeleportationTarget = false;
  92113. this._teleportationTarget = value;
  92114. }
  92115. },
  92116. enumerable: true,
  92117. configurable: true
  92118. });
  92119. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92120. /**
  92121. * The mesh used to display where the user is selecting,
  92122. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92123. * See http://doc.babylonjs.com/resources/baking_transformations
  92124. */
  92125. get: function () {
  92126. return this._cameraGazer._gazeTracker;
  92127. },
  92128. set: function (value) {
  92129. if (value) {
  92130. this._cameraGazer._gazeTracker = value;
  92131. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92132. this._cameraGazer._gazeTracker.isPickable = false;
  92133. this._cameraGazer._gazeTracker.isVisible = false;
  92134. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92135. if (this.leftController) {
  92136. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92137. }
  92138. if (this.rightController) {
  92139. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92140. }
  92141. }
  92142. },
  92143. enumerable: true,
  92144. configurable: true
  92145. });
  92146. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92147. /**
  92148. * If the ray of the gaze should be displayed.
  92149. */
  92150. get: function () {
  92151. return this._displayGaze;
  92152. },
  92153. /**
  92154. * Sets if the ray of the gaze should be displayed.
  92155. */
  92156. set: function (value) {
  92157. this._displayGaze = value;
  92158. if (!value) {
  92159. this._cameraGazer._gazeTracker.isVisible = false;
  92160. if (this.leftController) {
  92161. this.leftController._gazeTracker.isVisible = false;
  92162. }
  92163. if (this.rightController) {
  92164. this.rightController._gazeTracker.isVisible = false;
  92165. }
  92166. }
  92167. },
  92168. enumerable: true,
  92169. configurable: true
  92170. });
  92171. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92172. /**
  92173. * If the ray of the LaserPointer should be displayed.
  92174. */
  92175. get: function () {
  92176. return this._displayLaserPointer;
  92177. },
  92178. /**
  92179. * Sets if the ray of the LaserPointer should be displayed.
  92180. */
  92181. set: function (value) {
  92182. this._displayLaserPointer = value;
  92183. if (!value) {
  92184. if (this.rightController) {
  92185. this.rightController._deactivatePointer();
  92186. this.rightController._gazeTracker.isVisible = false;
  92187. }
  92188. if (this.leftController) {
  92189. this.leftController._deactivatePointer();
  92190. this.leftController._gazeTracker.isVisible = false;
  92191. }
  92192. }
  92193. else {
  92194. if (this.rightController) {
  92195. this.rightController._activatePointer();
  92196. }
  92197. if (this.leftController) {
  92198. this.leftController._activatePointer();
  92199. }
  92200. }
  92201. },
  92202. enumerable: true,
  92203. configurable: true
  92204. });
  92205. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92206. /**
  92207. * The deviceOrientationCamera used as the camera when not in VR.
  92208. */
  92209. get: function () {
  92210. return this._deviceOrientationCamera;
  92211. },
  92212. enumerable: true,
  92213. configurable: true
  92214. });
  92215. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92216. /**
  92217. * Based on the current WebVR support, returns the current VR camera used.
  92218. */
  92219. get: function () {
  92220. if (this._webVRready) {
  92221. return this._webVRCamera;
  92222. }
  92223. else {
  92224. return this._scene.activeCamera;
  92225. }
  92226. },
  92227. enumerable: true,
  92228. configurable: true
  92229. });
  92230. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92231. /**
  92232. * The webVRCamera which is used when in VR.
  92233. */
  92234. get: function () {
  92235. return this._webVRCamera;
  92236. },
  92237. enumerable: true,
  92238. configurable: true
  92239. });
  92240. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92241. /**
  92242. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92243. */
  92244. get: function () {
  92245. return this._vrDeviceOrientationCamera;
  92246. },
  92247. enumerable: true,
  92248. configurable: true
  92249. });
  92250. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92251. get: function () {
  92252. var result = this._cameraGazer._teleportationRequestInitiated
  92253. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92254. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92255. return result;
  92256. },
  92257. enumerable: true,
  92258. configurable: true
  92259. });
  92260. // Raised when one of the controller has loaded successfully its associated default mesh
  92261. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92262. if (this.leftController && this.leftController.webVRController == webVRController) {
  92263. if (webVRController.mesh) {
  92264. this.leftController._setLaserPointerParent(webVRController.mesh);
  92265. }
  92266. }
  92267. if (this.rightController && this.rightController.webVRController == webVRController) {
  92268. if (webVRController.mesh) {
  92269. this.rightController._setLaserPointerParent(webVRController.mesh);
  92270. }
  92271. }
  92272. try {
  92273. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92274. }
  92275. catch (err) {
  92276. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92277. }
  92278. };
  92279. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92280. /**
  92281. * Gets a value indicating if we are currently in VR mode.
  92282. */
  92283. get: function () {
  92284. return this._webVRpresenting || this._fullscreenVRpresenting;
  92285. },
  92286. enumerable: true,
  92287. configurable: true
  92288. });
  92289. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92290. var vrDisplay = this._scene.getEngine().getVRDevice();
  92291. if (vrDisplay) {
  92292. var wasPresenting = this._webVRpresenting;
  92293. // A VR display is connected
  92294. this._webVRpresenting = vrDisplay.isPresenting;
  92295. if (wasPresenting && !this._webVRpresenting)
  92296. this.exitVR();
  92297. }
  92298. else {
  92299. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92300. }
  92301. this.updateButtonVisibility();
  92302. };
  92303. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92304. this._webVRsupported = eventArgs.vrSupported;
  92305. this._webVRready = !!eventArgs.vrDisplay;
  92306. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92307. this.updateButtonVisibility();
  92308. };
  92309. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92310. if (this._canvas && !this._useCustomVRButton) {
  92311. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92312. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92313. }
  92314. };
  92315. VRExperienceHelper.prototype.displayVRButton = function () {
  92316. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92317. document.body.appendChild(this._btnVR);
  92318. this._btnVRDisplayed = true;
  92319. }
  92320. };
  92321. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92322. if (!this._btnVR || this._useCustomVRButton) {
  92323. return;
  92324. }
  92325. this._btnVR.className = "babylonVRicon";
  92326. if (this.isInVRMode) {
  92327. this._btnVR.className += " vrdisplaypresenting";
  92328. }
  92329. else {
  92330. if (this._webVRready)
  92331. this._btnVR.className += " vrdisplayready";
  92332. if (this._webVRsupported)
  92333. this._btnVR.className += " vrdisplaysupported";
  92334. if (this._webVRrequesting)
  92335. this._btnVR.className += " vrdisplayrequesting";
  92336. }
  92337. };
  92338. /**
  92339. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92340. * Otherwise, will use the fullscreen API.
  92341. */
  92342. VRExperienceHelper.prototype.enterVR = function () {
  92343. if (this.onEnteringVRObservable) {
  92344. try {
  92345. this.onEnteringVRObservable.notifyObservers(this);
  92346. }
  92347. catch (err) {
  92348. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92349. }
  92350. }
  92351. if (this._scene.activeCamera) {
  92352. this._position = this._scene.activeCamera.position.clone();
  92353. // make sure that we return to the last active camera
  92354. this._existingCamera = this._scene.activeCamera;
  92355. }
  92356. if (this._webVRrequesting)
  92357. return;
  92358. // If WebVR is supported and a headset is connected
  92359. if (this._webVRready) {
  92360. if (!this._webVRpresenting) {
  92361. this._webVRCamera.position = this._position;
  92362. this._scene.activeCamera = this._webVRCamera;
  92363. }
  92364. }
  92365. else if (this._vrDeviceOrientationCamera) {
  92366. this._vrDeviceOrientationCamera.position = this._position;
  92367. if (this._scene.activeCamera) {
  92368. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92369. }
  92370. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92371. this._scene.getEngine().switchFullscreen(true);
  92372. this.updateButtonVisibility();
  92373. }
  92374. if (this._scene.activeCamera && this._canvas) {
  92375. this._scene.activeCamera.attachControl(this._canvas);
  92376. }
  92377. if (this._interactionsEnabled) {
  92378. this._scene.registerBeforeRender(this.beforeRender);
  92379. }
  92380. };
  92381. /**
  92382. * Attempt to exit VR, or fullscreen.
  92383. */
  92384. VRExperienceHelper.prototype.exitVR = function () {
  92385. if (this.onExitingVRObservable) {
  92386. try {
  92387. this.onExitingVRObservable.notifyObservers(this);
  92388. }
  92389. catch (err) {
  92390. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92391. }
  92392. }
  92393. if (this._webVRpresenting) {
  92394. this._scene.getEngine().disableVR();
  92395. }
  92396. if (this._scene.activeCamera) {
  92397. this._position = this._scene.activeCamera.position.clone();
  92398. }
  92399. if (this._deviceOrientationCamera) {
  92400. this._deviceOrientationCamera.position = this._position;
  92401. this._scene.activeCamera = this._deviceOrientationCamera;
  92402. if (this._canvas) {
  92403. this._scene.activeCamera.attachControl(this._canvas);
  92404. }
  92405. }
  92406. else if (this._existingCamera) {
  92407. this._existingCamera.position = this._position;
  92408. this._scene.activeCamera = this._existingCamera;
  92409. }
  92410. this.updateButtonVisibility();
  92411. if (this._interactionsEnabled) {
  92412. this._scene.unregisterBeforeRender(this.beforeRender);
  92413. }
  92414. // resize to update width and height when exiting vr exits fullscreen
  92415. this._scene.getEngine().resize();
  92416. };
  92417. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92418. /**
  92419. * The position of the vr experience helper.
  92420. */
  92421. get: function () {
  92422. return this._position;
  92423. },
  92424. /**
  92425. * Sets the position of the vr experience helper.
  92426. */
  92427. set: function (value) {
  92428. this._position = value;
  92429. if (this._scene.activeCamera) {
  92430. this._scene.activeCamera.position = value;
  92431. }
  92432. },
  92433. enumerable: true,
  92434. configurable: true
  92435. });
  92436. /**
  92437. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92438. */
  92439. VRExperienceHelper.prototype.enableInteractions = function () {
  92440. var _this = this;
  92441. if (!this._interactionsEnabled) {
  92442. this._interactionsRequested = true;
  92443. if (this.leftController) {
  92444. this._enableInteractionOnController(this.leftController);
  92445. }
  92446. if (this.rightController) {
  92447. this._enableInteractionOnController(this.rightController);
  92448. }
  92449. this.raySelectionPredicate = function (mesh) {
  92450. return mesh.isVisible;
  92451. };
  92452. this.meshSelectionPredicate = function (mesh) {
  92453. return true;
  92454. };
  92455. this._raySelectionPredicate = function (mesh) {
  92456. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92457. && mesh.name.indexOf("teleportationTarget") === -1
  92458. && mesh.name.indexOf("torusTeleportation") === -1
  92459. && mesh.name.indexOf("laserPointer") === -1)) {
  92460. return _this.raySelectionPredicate(mesh);
  92461. }
  92462. return false;
  92463. };
  92464. this._interactionsEnabled = true;
  92465. }
  92466. };
  92467. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92468. get: function () {
  92469. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92470. },
  92471. enumerable: true,
  92472. configurable: true
  92473. });
  92474. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92475. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92476. if (this._floorMeshesCollection[i].id === mesh.id) {
  92477. return true;
  92478. }
  92479. }
  92480. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92481. return true;
  92482. }
  92483. return false;
  92484. };
  92485. /**
  92486. * Adds a floor mesh to be used for teleportation.
  92487. * @param floorMesh the mesh to be used for teleportation.
  92488. */
  92489. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92490. if (!this._floorMeshesCollection) {
  92491. return;
  92492. }
  92493. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92494. return;
  92495. }
  92496. this._floorMeshesCollection.push(floorMesh);
  92497. };
  92498. /**
  92499. * Removes a floor mesh from being used for teleportation.
  92500. * @param floorMesh the mesh to be removed.
  92501. */
  92502. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92503. if (!this._floorMeshesCollection) {
  92504. return;
  92505. }
  92506. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92507. if (meshIndex !== -1) {
  92508. this._floorMeshesCollection.splice(meshIndex, 1);
  92509. }
  92510. };
  92511. /**
  92512. * Enables interactions and teleportation using the VR controllers and gaze.
  92513. * @param vrTeleportationOptions options to modify teleportation behavior.
  92514. */
  92515. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92516. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92517. if (!this._teleportationInitialized) {
  92518. this._teleportationRequested = true;
  92519. this.enableInteractions();
  92520. if (vrTeleportationOptions.floorMeshName) {
  92521. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92522. }
  92523. if (vrTeleportationOptions.floorMeshes) {
  92524. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92525. }
  92526. if (this.leftController != null) {
  92527. this._enableTeleportationOnController(this.leftController);
  92528. }
  92529. if (this.rightController != null) {
  92530. this._enableTeleportationOnController(this.rightController);
  92531. }
  92532. // Creates an image processing post process for the vignette not relying
  92533. // on the main scene configuration for image processing to reduce setup and spaces
  92534. // (gamma/linear) conflicts.
  92535. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92536. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92537. imageProcessingConfiguration.vignetteEnabled = true;
  92538. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92539. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92540. this._teleportationInitialized = true;
  92541. if (this._isDefaultTeleportationTarget) {
  92542. this._createTeleportationCircles();
  92543. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92544. }
  92545. }
  92546. };
  92547. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92548. var _this = this;
  92549. var controllerMesh = controller.webVRController.mesh;
  92550. if (controllerMesh) {
  92551. controller._interactionsEnabled = true;
  92552. controller._activatePointer();
  92553. if (this.webVROptions.laserToggle) {
  92554. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92555. // Enabling / disabling laserPointer
  92556. if (_this._displayLaserPointer && stateObject.value === 1) {
  92557. if (controller._activePointer) {
  92558. controller._deactivatePointer();
  92559. }
  92560. else {
  92561. controller._activatePointer();
  92562. }
  92563. if (_this.displayGaze) {
  92564. controller._gazeTracker.isVisible = controller._activePointer;
  92565. }
  92566. }
  92567. });
  92568. }
  92569. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92570. var gazer = controller;
  92571. if (_this._noControllerIsActive) {
  92572. gazer = _this._cameraGazer;
  92573. }
  92574. if (!gazer._pointerDownOnMeshAsked) {
  92575. if (stateObject.value > _this._padSensibilityUp) {
  92576. gazer._selectionPointerDown();
  92577. }
  92578. }
  92579. else if (stateObject.value < _this._padSensibilityDown) {
  92580. gazer._selectionPointerUp();
  92581. }
  92582. });
  92583. }
  92584. };
  92585. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92586. // Dont teleport if another gaze already requested teleportation
  92587. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92588. return;
  92589. }
  92590. if (!gazer._teleportationRequestInitiated) {
  92591. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92592. gazer._activatePointer();
  92593. gazer._teleportationRequestInitiated = true;
  92594. }
  92595. }
  92596. else {
  92597. // Listening to the proper controller values changes to confirm teleportation
  92598. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92599. if (this._teleportActive) {
  92600. this._teleportCamera(this._haloCenter);
  92601. }
  92602. gazer._teleportationRequestInitiated = false;
  92603. }
  92604. }
  92605. };
  92606. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92607. // Only rotate when user is not currently selecting a teleportation location
  92608. if (gazer._teleportationRequestInitiated) {
  92609. return;
  92610. }
  92611. if (!gazer._rotationLeftAsked) {
  92612. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92613. gazer._rotationLeftAsked = true;
  92614. if (this._rotationAllowed) {
  92615. this._rotateCamera(false);
  92616. }
  92617. }
  92618. }
  92619. else {
  92620. if (stateObject.x > -this._padSensibilityDown) {
  92621. gazer._rotationLeftAsked = false;
  92622. }
  92623. }
  92624. if (!gazer._rotationRightAsked) {
  92625. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92626. gazer._rotationRightAsked = true;
  92627. if (this._rotationAllowed) {
  92628. this._rotateCamera(true);
  92629. }
  92630. }
  92631. }
  92632. else {
  92633. if (stateObject.x < this._padSensibilityDown) {
  92634. gazer._rotationRightAsked = false;
  92635. }
  92636. }
  92637. };
  92638. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92639. // Only teleport backwards when user is not currently selecting a teleportation location
  92640. if (gazer._teleportationRequestInitiated) {
  92641. return;
  92642. }
  92643. // Teleport backwards
  92644. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92645. if (!gazer._teleportationBackRequestInitiated) {
  92646. if (!this.currentVRCamera) {
  92647. return;
  92648. }
  92649. // Get rotation and position of the current camera
  92650. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92651. var position = this.currentVRCamera.position;
  92652. // If the camera has device position, use that instead
  92653. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92654. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92655. position = this.currentVRCamera.devicePosition;
  92656. }
  92657. // Get matrix with only the y rotation of the device rotation
  92658. rotation.toEulerAnglesToRef(this._workingVector);
  92659. this._workingVector.z = 0;
  92660. this._workingVector.x = 0;
  92661. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92662. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92663. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92664. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92665. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92666. var ray = new BABYLON.Ray(position, this._workingVector);
  92667. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92668. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92669. this._teleportCamera(hit.pickedPoint);
  92670. }
  92671. gazer._teleportationBackRequestInitiated = true;
  92672. }
  92673. }
  92674. else {
  92675. gazer._teleportationBackRequestInitiated = false;
  92676. }
  92677. };
  92678. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92679. var _this = this;
  92680. var controllerMesh = controller.webVRController.mesh;
  92681. if (controllerMesh) {
  92682. if (!controller._interactionsEnabled) {
  92683. this._enableInteractionOnController(controller);
  92684. }
  92685. controller._interactionsEnabled = true;
  92686. controller._teleportationEnabled = true;
  92687. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92688. controller._dpadPressed = false;
  92689. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92690. controller._dpadPressed = stateObject.pressed;
  92691. if (!controller._dpadPressed) {
  92692. controller._rotationLeftAsked = false;
  92693. controller._rotationRightAsked = false;
  92694. controller._teleportationBackRequestInitiated = false;
  92695. }
  92696. });
  92697. }
  92698. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92699. if (_this.teleportationEnabled) {
  92700. _this._checkTeleportBackwards(stateObject, controller);
  92701. _this._checkTeleportWithRay(stateObject, controller);
  92702. }
  92703. _this._checkRotate(stateObject, controller);
  92704. });
  92705. }
  92706. };
  92707. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92708. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92709. this._teleportationTarget.isPickable = false;
  92710. var length = 512;
  92711. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92712. dynamicTexture.hasAlpha = true;
  92713. var context = dynamicTexture.getContext();
  92714. var centerX = length / 2;
  92715. var centerY = length / 2;
  92716. var radius = 200;
  92717. context.beginPath();
  92718. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92719. context.fillStyle = this._teleportationFillColor;
  92720. context.fill();
  92721. context.lineWidth = 10;
  92722. context.strokeStyle = this._teleportationBorderColor;
  92723. context.stroke();
  92724. context.closePath();
  92725. dynamicTexture.update();
  92726. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92727. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92728. this._teleportationTarget.material = teleportationCircleMaterial;
  92729. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92730. torus.isPickable = false;
  92731. torus.parent = this._teleportationTarget;
  92732. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92733. var keys = [];
  92734. keys.push({
  92735. frame: 0,
  92736. value: 0
  92737. });
  92738. keys.push({
  92739. frame: 30,
  92740. value: 0.4
  92741. });
  92742. keys.push({
  92743. frame: 60,
  92744. value: 0
  92745. });
  92746. animationInnerCircle.setKeys(keys);
  92747. var easingFunction = new BABYLON.SineEase();
  92748. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92749. animationInnerCircle.setEasingFunction(easingFunction);
  92750. torus.animations = [];
  92751. torus.animations.push(animationInnerCircle);
  92752. this._scene.beginAnimation(torus, 0, 60, true);
  92753. this._hideTeleportationTarget();
  92754. };
  92755. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92756. this._teleportActive = true;
  92757. if (this._teleportationInitialized) {
  92758. this._teleportationTarget.isVisible = true;
  92759. if (this._isDefaultTeleportationTarget) {
  92760. this._teleportationTarget.getChildren()[0].isVisible = true;
  92761. }
  92762. }
  92763. };
  92764. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92765. this._teleportActive = false;
  92766. if (this._teleportationInitialized) {
  92767. this._teleportationTarget.isVisible = false;
  92768. if (this._isDefaultTeleportationTarget) {
  92769. this._teleportationTarget.getChildren()[0].isVisible = false;
  92770. }
  92771. }
  92772. };
  92773. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92774. var _this = this;
  92775. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92776. return;
  92777. }
  92778. if (right) {
  92779. this._rotationAngle++;
  92780. }
  92781. else {
  92782. this._rotationAngle--;
  92783. }
  92784. this.currentVRCamera.animations = [];
  92785. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92786. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92787. var animationRotationKeys = [];
  92788. animationRotationKeys.push({
  92789. frame: 0,
  92790. value: this.currentVRCamera.rotationQuaternion
  92791. });
  92792. animationRotationKeys.push({
  92793. frame: 6,
  92794. value: target
  92795. });
  92796. animationRotation.setKeys(animationRotationKeys);
  92797. animationRotation.setEasingFunction(this._circleEase);
  92798. this.currentVRCamera.animations.push(animationRotation);
  92799. this._postProcessMove.animations = [];
  92800. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92801. var vignetteWeightKeys = [];
  92802. vignetteWeightKeys.push({
  92803. frame: 0,
  92804. value: 0
  92805. });
  92806. vignetteWeightKeys.push({
  92807. frame: 3,
  92808. value: 4
  92809. });
  92810. vignetteWeightKeys.push({
  92811. frame: 6,
  92812. value: 0
  92813. });
  92814. animationPP.setKeys(vignetteWeightKeys);
  92815. animationPP.setEasingFunction(this._circleEase);
  92816. this._postProcessMove.animations.push(animationPP);
  92817. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92818. var vignetteStretchKeys = [];
  92819. vignetteStretchKeys.push({
  92820. frame: 0,
  92821. value: 0
  92822. });
  92823. vignetteStretchKeys.push({
  92824. frame: 3,
  92825. value: 10
  92826. });
  92827. vignetteStretchKeys.push({
  92828. frame: 6,
  92829. value: 0
  92830. });
  92831. animationPP2.setKeys(vignetteStretchKeys);
  92832. animationPP2.setEasingFunction(this._circleEase);
  92833. this._postProcessMove.animations.push(animationPP2);
  92834. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92835. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92836. this._postProcessMove.samples = 4;
  92837. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92838. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92839. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92840. });
  92841. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92842. };
  92843. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92844. if (hit.pickedPoint) {
  92845. if (gazer._teleportationRequestInitiated) {
  92846. this._displayTeleportationTarget();
  92847. this._haloCenter.copyFrom(hit.pickedPoint);
  92848. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92849. }
  92850. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92851. if (pickNormal) {
  92852. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92853. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92854. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92855. }
  92856. this._teleportationTarget.position.y += 0.1;
  92857. }
  92858. };
  92859. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92860. var _this = this;
  92861. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92862. return;
  92863. }
  92864. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92865. // offset of the headset from the anchor.
  92866. if (this.webVRCamera.leftCamera) {
  92867. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92868. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92869. location.subtractToRef(this._workingVector, this._workingVector);
  92870. }
  92871. else {
  92872. this._workingVector.copyFrom(location);
  92873. }
  92874. // Add height to account for user's height offset
  92875. if (this.isInVRMode) {
  92876. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92877. }
  92878. else {
  92879. this._workingVector.y += this._defaultHeight;
  92880. }
  92881. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92882. // Create animation from the camera's position to the new location
  92883. this.currentVRCamera.animations = [];
  92884. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92885. var animationCameraTeleportationKeys = [{
  92886. frame: 0,
  92887. value: this.currentVRCamera.position
  92888. },
  92889. {
  92890. frame: 11,
  92891. value: this._workingVector
  92892. }
  92893. ];
  92894. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92895. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92896. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92897. this._postProcessMove.animations = [];
  92898. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92899. var vignetteWeightKeys = [];
  92900. vignetteWeightKeys.push({
  92901. frame: 0,
  92902. value: 0
  92903. });
  92904. vignetteWeightKeys.push({
  92905. frame: 5,
  92906. value: 8
  92907. });
  92908. vignetteWeightKeys.push({
  92909. frame: 11,
  92910. value: 0
  92911. });
  92912. animationPP.setKeys(vignetteWeightKeys);
  92913. this._postProcessMove.animations.push(animationPP);
  92914. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92915. var vignetteStretchKeys = [];
  92916. vignetteStretchKeys.push({
  92917. frame: 0,
  92918. value: 0
  92919. });
  92920. vignetteStretchKeys.push({
  92921. frame: 5,
  92922. value: 10
  92923. });
  92924. vignetteStretchKeys.push({
  92925. frame: 11,
  92926. value: 0
  92927. });
  92928. animationPP2.setKeys(vignetteStretchKeys);
  92929. this._postProcessMove.animations.push(animationPP2);
  92930. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92931. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92932. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92933. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92934. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92935. });
  92936. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92937. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92938. });
  92939. this._hideTeleportationTarget();
  92940. };
  92941. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92942. if (normal) {
  92943. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92944. if (angle < Math.PI / 2) {
  92945. normal.scaleInPlace(-1);
  92946. }
  92947. }
  92948. return normal;
  92949. };
  92950. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92951. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92952. return;
  92953. }
  92954. var ray = gazer._getForwardRay(this._rayLength);
  92955. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92956. if (hit) {
  92957. // Populate the contrllers mesh that can be used for drag/drop
  92958. if (gazer._laserPointer) {
  92959. hit.originMesh = gazer._laserPointer.parent;
  92960. }
  92961. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92962. }
  92963. gazer._currentHit = hit;
  92964. // Moving the gazeTracker on the mesh face targetted
  92965. if (hit && hit.pickedPoint) {
  92966. if (this._displayGaze) {
  92967. var multiplier = 1;
  92968. gazer._gazeTracker.isVisible = true;
  92969. if (gazer._isActionableMesh) {
  92970. multiplier = 3;
  92971. }
  92972. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92973. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92974. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92975. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92976. // To avoid z-fighting
  92977. var deltaFighting = 0.002;
  92978. if (pickNormal) {
  92979. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92980. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92981. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92982. }
  92983. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92984. if (gazer._gazeTracker.position.x < 0) {
  92985. gazer._gazeTracker.position.x += deltaFighting;
  92986. }
  92987. else {
  92988. gazer._gazeTracker.position.x -= deltaFighting;
  92989. }
  92990. if (gazer._gazeTracker.position.y < 0) {
  92991. gazer._gazeTracker.position.y += deltaFighting;
  92992. }
  92993. else {
  92994. gazer._gazeTracker.position.y -= deltaFighting;
  92995. }
  92996. if (gazer._gazeTracker.position.z < 0) {
  92997. gazer._gazeTracker.position.z += deltaFighting;
  92998. }
  92999. else {
  93000. gazer._gazeTracker.position.z -= deltaFighting;
  93001. }
  93002. }
  93003. // Changing the size of the laser pointer based on the distance from the targetted point
  93004. gazer._updatePointerDistance(hit.distance);
  93005. }
  93006. else {
  93007. gazer._updatePointerDistance();
  93008. gazer._gazeTracker.isVisible = false;
  93009. }
  93010. if (hit && hit.pickedMesh) {
  93011. // The object selected is the floor, we're in a teleportation scenario
  93012. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93013. // Moving the teleportation area to this targetted point
  93014. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93015. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93016. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93017. }
  93018. gazer._currentMeshSelected = null;
  93019. if (gazer._teleportationRequestInitiated) {
  93020. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93021. }
  93022. return;
  93023. }
  93024. // If not, we're in a selection scenario
  93025. //this._teleportationAllowed = false;
  93026. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93027. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93028. this.onNewMeshPicked.notifyObservers(hit);
  93029. gazer._currentMeshSelected = hit.pickedMesh;
  93030. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93031. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93032. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93033. gazer._isActionableMesh = true;
  93034. }
  93035. else {
  93036. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93037. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93038. gazer._isActionableMesh = false;
  93039. }
  93040. try {
  93041. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93042. }
  93043. catch (err) {
  93044. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93045. }
  93046. }
  93047. else {
  93048. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93049. gazer._currentMeshSelected = null;
  93050. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93051. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93052. }
  93053. }
  93054. }
  93055. else {
  93056. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93057. gazer._currentMeshSelected = null;
  93058. //this._teleportationAllowed = false;
  93059. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93060. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93061. }
  93062. };
  93063. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93064. if (mesh) {
  93065. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93066. }
  93067. };
  93068. /**
  93069. * Sets the color of the laser ray from the vr controllers.
  93070. * @param color new color for the ray.
  93071. */
  93072. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93073. if (this.leftController) {
  93074. this.leftController._setLaserPointerColor(color);
  93075. }
  93076. if (this.rightController) {
  93077. this.rightController._setLaserPointerColor(color);
  93078. }
  93079. };
  93080. /**
  93081. * Sets the color of the ray from the vr headsets gaze.
  93082. * @param color new color for the ray.
  93083. */
  93084. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93085. if (!this._cameraGazer._gazeTracker.material) {
  93086. return;
  93087. }
  93088. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93089. if (this.leftController) {
  93090. this.leftController._gazeTracker.material.emissiveColor = color;
  93091. }
  93092. if (this.rightController) {
  93093. this.rightController._gazeTracker.material.emissiveColor = color;
  93094. }
  93095. };
  93096. /**
  93097. * Exits VR and disposes of the vr experience helper
  93098. */
  93099. VRExperienceHelper.prototype.dispose = function () {
  93100. if (this.isInVRMode) {
  93101. this.exitVR();
  93102. }
  93103. if (this._postProcessMove) {
  93104. this._postProcessMove.dispose();
  93105. }
  93106. if (this._webVRCamera) {
  93107. this._webVRCamera.dispose();
  93108. }
  93109. if (this._vrDeviceOrientationCamera) {
  93110. this._vrDeviceOrientationCamera.dispose();
  93111. }
  93112. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93113. document.body.removeChild(this._btnVR);
  93114. }
  93115. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93116. this._deviceOrientationCamera.dispose();
  93117. }
  93118. if (this._cameraGazer) {
  93119. this._cameraGazer.dispose();
  93120. }
  93121. if (this.leftController) {
  93122. this.leftController.dispose();
  93123. }
  93124. if (this.rightController) {
  93125. this.rightController.dispose();
  93126. }
  93127. if (this._teleportationTarget) {
  93128. this._teleportationTarget.dispose();
  93129. }
  93130. this._floorMeshesCollection = [];
  93131. document.removeEventListener("keydown", this._onKeyDown);
  93132. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93133. window.removeEventListener("resize", this._onResize);
  93134. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93135. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93136. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93137. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93138. document.onmsfullscreenchange = null;
  93139. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93140. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93141. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93142. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93143. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93144. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93145. this._scene.unregisterBeforeRender(this.beforeRender);
  93146. };
  93147. /**
  93148. * Gets the name of the VRExperienceHelper class
  93149. * @returns "VRExperienceHelper"
  93150. */
  93151. VRExperienceHelper.prototype.getClassName = function () {
  93152. return "VRExperienceHelper";
  93153. };
  93154. return VRExperienceHelper;
  93155. }());
  93156. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93157. })(BABYLON || (BABYLON = {}));
  93158. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93159. // Mainly based on these 2 articles :
  93160. // 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
  93161. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93162. var BABYLON;
  93163. (function (BABYLON) {
  93164. /**
  93165. * Defines the potential axis of a Joystick
  93166. */
  93167. var JoystickAxis;
  93168. (function (JoystickAxis) {
  93169. /** X axis */
  93170. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93171. /** Y axis */
  93172. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93173. /** Z axis */
  93174. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93175. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93176. /**
  93177. * Class used to define virtual joystick (used in touch mode)
  93178. */
  93179. var VirtualJoystick = /** @class */ (function () {
  93180. /**
  93181. * Creates a new virtual joystick
  93182. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93183. */
  93184. function VirtualJoystick(leftJoystick) {
  93185. var _this = this;
  93186. if (leftJoystick) {
  93187. this._leftJoystick = true;
  93188. }
  93189. else {
  93190. this._leftJoystick = false;
  93191. }
  93192. VirtualJoystick._globalJoystickIndex++;
  93193. // By default left & right arrow keys are moving the X
  93194. // and up & down keys are moving the Y
  93195. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93196. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93197. this.reverseLeftRight = false;
  93198. this.reverseUpDown = false;
  93199. // collections of pointers
  93200. this._touches = new BABYLON.StringDictionary();
  93201. this.deltaPosition = BABYLON.Vector3.Zero();
  93202. this._joystickSensibility = 25;
  93203. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93204. this._onResize = function (evt) {
  93205. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93206. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93207. if (VirtualJoystick.vjCanvas) {
  93208. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93209. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93210. }
  93211. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93212. };
  93213. // injecting a canvas element on top of the canvas 3D game
  93214. if (!VirtualJoystick.vjCanvas) {
  93215. window.addEventListener("resize", this._onResize, false);
  93216. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93217. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93218. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93219. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93220. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93221. VirtualJoystick.vjCanvas.style.width = "100%";
  93222. VirtualJoystick.vjCanvas.style.height = "100%";
  93223. VirtualJoystick.vjCanvas.style.position = "absolute";
  93224. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93225. VirtualJoystick.vjCanvas.style.top = "0px";
  93226. VirtualJoystick.vjCanvas.style.left = "0px";
  93227. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93228. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93229. // Support for jQuery PEP polyfill
  93230. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93231. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93232. if (!context) {
  93233. throw new Error("Unable to create canvas for virtual joystick");
  93234. }
  93235. VirtualJoystick.vjCanvasContext = context;
  93236. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93237. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93238. document.body.appendChild(VirtualJoystick.vjCanvas);
  93239. }
  93240. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93241. this.pressed = false;
  93242. // default joystick color
  93243. this._joystickColor = "cyan";
  93244. this._joystickPointerID = -1;
  93245. // current joystick position
  93246. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93247. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93248. // origin joystick position
  93249. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93250. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93251. this._onPointerDownHandlerRef = function (evt) {
  93252. _this._onPointerDown(evt);
  93253. };
  93254. this._onPointerMoveHandlerRef = function (evt) {
  93255. _this._onPointerMove(evt);
  93256. };
  93257. this._onPointerUpHandlerRef = function (evt) {
  93258. _this._onPointerUp(evt);
  93259. };
  93260. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93261. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93262. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93263. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93264. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93265. evt.preventDefault(); // Disables system menu
  93266. }, false);
  93267. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93268. }
  93269. /**
  93270. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93271. * @param newJoystickSensibility defines the new sensibility
  93272. */
  93273. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93274. this._joystickSensibility = newJoystickSensibility;
  93275. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93276. };
  93277. VirtualJoystick.prototype._onPointerDown = function (e) {
  93278. var positionOnScreenCondition;
  93279. e.preventDefault();
  93280. if (this._leftJoystick === true) {
  93281. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93282. }
  93283. else {
  93284. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93285. }
  93286. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93287. // First contact will be dedicated to the virtual joystick
  93288. this._joystickPointerID = e.pointerId;
  93289. this._joystickPointerStartPos.x = e.clientX;
  93290. this._joystickPointerStartPos.y = e.clientY;
  93291. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93292. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93293. this._deltaJoystickVector.x = 0;
  93294. this._deltaJoystickVector.y = 0;
  93295. this.pressed = true;
  93296. this._touches.add(e.pointerId.toString(), e);
  93297. }
  93298. else {
  93299. // You can only trigger the action buttons with a joystick declared
  93300. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93301. this._action();
  93302. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93303. }
  93304. }
  93305. };
  93306. VirtualJoystick.prototype._onPointerMove = function (e) {
  93307. // If the current pointer is the one associated to the joystick (first touch contact)
  93308. if (this._joystickPointerID == e.pointerId) {
  93309. this._joystickPointerPos.x = e.clientX;
  93310. this._joystickPointerPos.y = e.clientY;
  93311. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93312. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93313. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93314. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93315. switch (this._axisTargetedByLeftAndRight) {
  93316. case JoystickAxis.X:
  93317. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93318. break;
  93319. case JoystickAxis.Y:
  93320. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93321. break;
  93322. case JoystickAxis.Z:
  93323. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93324. break;
  93325. }
  93326. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93327. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93328. switch (this._axisTargetedByUpAndDown) {
  93329. case JoystickAxis.X:
  93330. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93331. break;
  93332. case JoystickAxis.Y:
  93333. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93334. break;
  93335. case JoystickAxis.Z:
  93336. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93337. break;
  93338. }
  93339. }
  93340. else {
  93341. var data = this._touches.get(e.pointerId.toString());
  93342. if (data) {
  93343. data.x = e.clientX;
  93344. data.y = e.clientY;
  93345. }
  93346. }
  93347. };
  93348. VirtualJoystick.prototype._onPointerUp = function (e) {
  93349. if (this._joystickPointerID == e.pointerId) {
  93350. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93351. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93352. this._joystickPointerID = -1;
  93353. this.pressed = false;
  93354. }
  93355. else {
  93356. var touch = this._touches.get(e.pointerId.toString());
  93357. if (touch) {
  93358. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93359. }
  93360. }
  93361. this._deltaJoystickVector.x = 0;
  93362. this._deltaJoystickVector.y = 0;
  93363. this._touches.remove(e.pointerId.toString());
  93364. };
  93365. /**
  93366. * Change the color of the virtual joystick
  93367. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93368. */
  93369. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93370. this._joystickColor = newColor;
  93371. };
  93372. /**
  93373. * Defines a callback to call when the joystick is touched
  93374. * @param action defines the callback
  93375. */
  93376. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93377. this._action = action;
  93378. };
  93379. /**
  93380. * Defines which axis you'd like to control for left & right
  93381. * @param axis defines the axis to use
  93382. */
  93383. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93384. switch (axis) {
  93385. case JoystickAxis.X:
  93386. case JoystickAxis.Y:
  93387. case JoystickAxis.Z:
  93388. this._axisTargetedByLeftAndRight = axis;
  93389. break;
  93390. default:
  93391. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93392. break;
  93393. }
  93394. };
  93395. /**
  93396. * Defines which axis you'd like to control for up & down
  93397. * @param axis defines the axis to use
  93398. */
  93399. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93400. switch (axis) {
  93401. case JoystickAxis.X:
  93402. case JoystickAxis.Y:
  93403. case JoystickAxis.Z:
  93404. this._axisTargetedByUpAndDown = axis;
  93405. break;
  93406. default:
  93407. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93408. break;
  93409. }
  93410. };
  93411. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93412. var _this = this;
  93413. if (this.pressed) {
  93414. this._touches.forEach(function (key, touch) {
  93415. if (touch.pointerId === _this._joystickPointerID) {
  93416. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93417. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93418. VirtualJoystick.vjCanvasContext.beginPath();
  93419. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93420. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93421. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93422. VirtualJoystick.vjCanvasContext.stroke();
  93423. VirtualJoystick.vjCanvasContext.closePath();
  93424. VirtualJoystick.vjCanvasContext.beginPath();
  93425. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93426. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93427. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93428. VirtualJoystick.vjCanvasContext.stroke();
  93429. VirtualJoystick.vjCanvasContext.closePath();
  93430. VirtualJoystick.vjCanvasContext.beginPath();
  93431. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93432. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93433. VirtualJoystick.vjCanvasContext.stroke();
  93434. VirtualJoystick.vjCanvasContext.closePath();
  93435. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93436. }
  93437. else {
  93438. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93439. VirtualJoystick.vjCanvasContext.beginPath();
  93440. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93441. VirtualJoystick.vjCanvasContext.beginPath();
  93442. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93443. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93444. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93445. VirtualJoystick.vjCanvasContext.stroke();
  93446. VirtualJoystick.vjCanvasContext.closePath();
  93447. touch.prevX = touch.x;
  93448. touch.prevY = touch.y;
  93449. }
  93450. ;
  93451. });
  93452. }
  93453. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93454. };
  93455. /**
  93456. * Release internal HTML canvas
  93457. */
  93458. VirtualJoystick.prototype.releaseCanvas = function () {
  93459. if (VirtualJoystick.vjCanvas) {
  93460. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93461. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93462. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93463. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93464. window.removeEventListener("resize", this._onResize);
  93465. document.body.removeChild(VirtualJoystick.vjCanvas);
  93466. VirtualJoystick.vjCanvas = null;
  93467. }
  93468. };
  93469. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93470. VirtualJoystick._globalJoystickIndex = 0;
  93471. return VirtualJoystick;
  93472. }());
  93473. BABYLON.VirtualJoystick = VirtualJoystick;
  93474. })(BABYLON || (BABYLON = {}));
  93475. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93476. var BABYLON;
  93477. (function (BABYLON) {
  93478. // We're mainly based on the logic defined into the FreeCamera code
  93479. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93480. __extends(VirtualJoysticksCamera, _super);
  93481. function VirtualJoysticksCamera(name, position, scene) {
  93482. var _this = _super.call(this, name, position, scene) || this;
  93483. _this.inputs.addVirtualJoystick();
  93484. return _this;
  93485. }
  93486. VirtualJoysticksCamera.prototype.getClassName = function () {
  93487. return "VirtualJoysticksCamera";
  93488. };
  93489. return VirtualJoysticksCamera;
  93490. }(BABYLON.FreeCamera));
  93491. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93492. })(BABYLON || (BABYLON = {}));
  93493. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93494. var BABYLON;
  93495. (function (BABYLON) {
  93496. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93497. function FreeCameraVirtualJoystickInput() {
  93498. }
  93499. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93500. return this._leftjoystick;
  93501. };
  93502. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93503. return this._rightjoystick;
  93504. };
  93505. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93506. if (this._leftjoystick) {
  93507. var camera = this.camera;
  93508. var speed = camera._computeLocalCameraSpeed() * 50;
  93509. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93510. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93511. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93512. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93513. if (!this._leftjoystick.pressed) {
  93514. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93515. }
  93516. if (!this._rightjoystick.pressed) {
  93517. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93518. }
  93519. }
  93520. };
  93521. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93522. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93523. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93524. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93525. this._leftjoystick.setJoystickSensibility(0.15);
  93526. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93527. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93528. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93529. this._rightjoystick.reverseUpDown = true;
  93530. this._rightjoystick.setJoystickSensibility(0.05);
  93531. this._rightjoystick.setJoystickColor("yellow");
  93532. };
  93533. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93534. this._leftjoystick.releaseCanvas();
  93535. this._rightjoystick.releaseCanvas();
  93536. };
  93537. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93538. return "FreeCameraVirtualJoystickInput";
  93539. };
  93540. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93541. return "virtualJoystick";
  93542. };
  93543. return FreeCameraVirtualJoystickInput;
  93544. }());
  93545. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93546. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93547. })(BABYLON || (BABYLON = {}));
  93548. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93549. var BABYLON;
  93550. (function (BABYLON) {
  93551. var SimplificationSettings = /** @class */ (function () {
  93552. function SimplificationSettings(quality, distance, optimizeMesh) {
  93553. this.quality = quality;
  93554. this.distance = distance;
  93555. this.optimizeMesh = optimizeMesh;
  93556. }
  93557. return SimplificationSettings;
  93558. }());
  93559. BABYLON.SimplificationSettings = SimplificationSettings;
  93560. var SimplificationQueue = /** @class */ (function () {
  93561. function SimplificationQueue() {
  93562. this.running = false;
  93563. this._simplificationArray = [];
  93564. }
  93565. SimplificationQueue.prototype.addTask = function (task) {
  93566. this._simplificationArray.push(task);
  93567. };
  93568. SimplificationQueue.prototype.executeNext = function () {
  93569. var task = this._simplificationArray.pop();
  93570. if (task) {
  93571. this.running = true;
  93572. this.runSimplification(task);
  93573. }
  93574. else {
  93575. this.running = false;
  93576. }
  93577. };
  93578. SimplificationQueue.prototype.runSimplification = function (task) {
  93579. var _this = this;
  93580. if (task.parallelProcessing) {
  93581. //parallel simplifier
  93582. task.settings.forEach(function (setting) {
  93583. var simplifier = _this.getSimplifier(task);
  93584. simplifier.simplify(setting, function (newMesh) {
  93585. task.mesh.addLODLevel(setting.distance, newMesh);
  93586. newMesh.isVisible = true;
  93587. //check if it is the last
  93588. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93589. //all done, run the success callback.
  93590. task.successCallback();
  93591. }
  93592. _this.executeNext();
  93593. });
  93594. });
  93595. }
  93596. else {
  93597. //single simplifier.
  93598. var simplifier = this.getSimplifier(task);
  93599. var runDecimation = function (setting, callback) {
  93600. simplifier.simplify(setting, function (newMesh) {
  93601. task.mesh.addLODLevel(setting.distance, newMesh);
  93602. newMesh.isVisible = true;
  93603. //run the next quality level
  93604. callback();
  93605. });
  93606. };
  93607. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93608. runDecimation(task.settings[loop.index], function () {
  93609. loop.executeNext();
  93610. });
  93611. }, function () {
  93612. //execution ended, run the success callback.
  93613. if (task.successCallback) {
  93614. task.successCallback();
  93615. }
  93616. _this.executeNext();
  93617. });
  93618. }
  93619. };
  93620. SimplificationQueue.prototype.getSimplifier = function (task) {
  93621. switch (task.simplificationType) {
  93622. case SimplificationType.QUADRATIC:
  93623. default:
  93624. return new QuadraticErrorSimplification(task.mesh);
  93625. }
  93626. };
  93627. return SimplificationQueue;
  93628. }());
  93629. BABYLON.SimplificationQueue = SimplificationQueue;
  93630. /**
  93631. * The implemented types of simplification
  93632. * At the moment only Quadratic Error Decimation is implemented
  93633. */
  93634. var SimplificationType;
  93635. (function (SimplificationType) {
  93636. /** Quadratic error decimation */
  93637. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93638. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93639. var DecimationTriangle = /** @class */ (function () {
  93640. function DecimationTriangle(vertices) {
  93641. this.vertices = vertices;
  93642. this.error = new Array(4);
  93643. this.deleted = false;
  93644. this.isDirty = false;
  93645. this.deletePending = false;
  93646. this.borderFactor = 0;
  93647. }
  93648. return DecimationTriangle;
  93649. }());
  93650. BABYLON.DecimationTriangle = DecimationTriangle;
  93651. var DecimationVertex = /** @class */ (function () {
  93652. function DecimationVertex(position, id) {
  93653. this.position = position;
  93654. this.id = id;
  93655. this.isBorder = true;
  93656. this.q = new QuadraticMatrix();
  93657. this.triangleCount = 0;
  93658. this.triangleStart = 0;
  93659. this.originalOffsets = [];
  93660. }
  93661. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93662. this.position.copyFrom(newPosition);
  93663. };
  93664. return DecimationVertex;
  93665. }());
  93666. BABYLON.DecimationVertex = DecimationVertex;
  93667. var QuadraticMatrix = /** @class */ (function () {
  93668. function QuadraticMatrix(data) {
  93669. this.data = new Array(10);
  93670. for (var i = 0; i < 10; ++i) {
  93671. if (data && data[i]) {
  93672. this.data[i] = data[i];
  93673. }
  93674. else {
  93675. this.data[i] = 0;
  93676. }
  93677. }
  93678. }
  93679. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93680. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93681. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93682. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93683. return det;
  93684. };
  93685. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93686. for (var i = 0; i < 10; ++i) {
  93687. this.data[i] += matrix.data[i];
  93688. }
  93689. };
  93690. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93691. for (var i = 0; i < 10; ++i) {
  93692. this.data[i] += data[i];
  93693. }
  93694. };
  93695. QuadraticMatrix.prototype.add = function (matrix) {
  93696. var m = new QuadraticMatrix();
  93697. for (var i = 0; i < 10; ++i) {
  93698. m.data[i] = this.data[i] + matrix.data[i];
  93699. }
  93700. return m;
  93701. };
  93702. QuadraticMatrix.FromData = function (a, b, c, d) {
  93703. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93704. };
  93705. //returning an array to avoid garbage collection
  93706. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93707. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93708. };
  93709. return QuadraticMatrix;
  93710. }());
  93711. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93712. var Reference = /** @class */ (function () {
  93713. function Reference(vertexId, triangleId) {
  93714. this.vertexId = vertexId;
  93715. this.triangleId = triangleId;
  93716. }
  93717. return Reference;
  93718. }());
  93719. BABYLON.Reference = Reference;
  93720. /**
  93721. * An implementation of the Quadratic Error simplification algorithm.
  93722. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93723. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93724. * @author RaananW
  93725. */
  93726. var QuadraticErrorSimplification = /** @class */ (function () {
  93727. function QuadraticErrorSimplification(_mesh) {
  93728. this._mesh = _mesh;
  93729. this.syncIterations = 5000;
  93730. this.aggressiveness = 7;
  93731. this.decimationIterations = 100;
  93732. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93733. }
  93734. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93735. var _this = this;
  93736. this.initDecimatedMesh();
  93737. //iterating through the submeshes array, one after the other.
  93738. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93739. _this.initWithMesh(loop.index, function () {
  93740. _this.runDecimation(settings, loop.index, function () {
  93741. loop.executeNext();
  93742. });
  93743. }, settings.optimizeMesh);
  93744. }, function () {
  93745. setTimeout(function () {
  93746. successCallback(_this._reconstructedMesh);
  93747. }, 0);
  93748. });
  93749. };
  93750. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93751. var _this = this;
  93752. var targetCount = ~~(this.triangles.length * settings.quality);
  93753. var deletedTriangles = 0;
  93754. var triangleCount = this.triangles.length;
  93755. var iterationFunction = function (iteration, callback) {
  93756. setTimeout(function () {
  93757. if (iteration % 5 === 0) {
  93758. _this.updateMesh(iteration === 0);
  93759. }
  93760. for (var i = 0; i < _this.triangles.length; ++i) {
  93761. _this.triangles[i].isDirty = false;
  93762. }
  93763. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93764. var trianglesIterator = function (i) {
  93765. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93766. var t = _this.triangles[tIdx];
  93767. if (!t)
  93768. return;
  93769. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93770. return;
  93771. }
  93772. for (var j = 0; j < 3; ++j) {
  93773. if (t.error[j] < threshold) {
  93774. var deleted0 = [];
  93775. var deleted1 = [];
  93776. var v0 = t.vertices[j];
  93777. var v1 = t.vertices[(j + 1) % 3];
  93778. if (v0.isBorder || v1.isBorder)
  93779. continue;
  93780. var p = BABYLON.Vector3.Zero();
  93781. var n = BABYLON.Vector3.Zero();
  93782. var uv = BABYLON.Vector2.Zero();
  93783. var color = new BABYLON.Color4(0, 0, 0, 1);
  93784. _this.calculateError(v0, v1, p, n, uv, color);
  93785. var delTr = new Array();
  93786. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93787. continue;
  93788. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93789. continue;
  93790. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93791. continue;
  93792. var uniqueArray = new Array();
  93793. delTr.forEach(function (deletedT) {
  93794. if (uniqueArray.indexOf(deletedT) === -1) {
  93795. deletedT.deletePending = true;
  93796. uniqueArray.push(deletedT);
  93797. }
  93798. });
  93799. if (uniqueArray.length % 2 !== 0) {
  93800. continue;
  93801. }
  93802. v0.q = v1.q.add(v0.q);
  93803. v0.updatePosition(p);
  93804. var tStart = _this.references.length;
  93805. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93806. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93807. var tCount = _this.references.length - tStart;
  93808. if (tCount <= v0.triangleCount) {
  93809. if (tCount) {
  93810. for (var c = 0; c < tCount; c++) {
  93811. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93812. }
  93813. }
  93814. }
  93815. else {
  93816. v0.triangleStart = tStart;
  93817. }
  93818. v0.triangleCount = tCount;
  93819. break;
  93820. }
  93821. }
  93822. };
  93823. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93824. }, 0);
  93825. };
  93826. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93827. if (triangleCount - deletedTriangles <= targetCount)
  93828. loop.breakLoop();
  93829. else {
  93830. iterationFunction(loop.index, function () {
  93831. loop.executeNext();
  93832. });
  93833. }
  93834. }, function () {
  93835. setTimeout(function () {
  93836. //reconstruct this part of the mesh
  93837. _this.reconstructMesh(submeshIndex);
  93838. successCallback();
  93839. }, 0);
  93840. });
  93841. };
  93842. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93843. var _this = this;
  93844. this.vertices = [];
  93845. this.triangles = [];
  93846. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93847. var indices = this._mesh.getIndices();
  93848. var submesh = this._mesh.subMeshes[submeshIndex];
  93849. var findInVertices = function (positionToSearch) {
  93850. if (optimizeMesh) {
  93851. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93852. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93853. return _this.vertices[ii];
  93854. }
  93855. }
  93856. }
  93857. return null;
  93858. };
  93859. var vertexReferences = [];
  93860. var vertexInit = function (i) {
  93861. if (!positionData) {
  93862. return;
  93863. }
  93864. var offset = i + submesh.verticesStart;
  93865. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93866. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93867. vertex.originalOffsets.push(offset);
  93868. if (vertex.id === _this.vertices.length) {
  93869. _this.vertices.push(vertex);
  93870. }
  93871. vertexReferences.push(vertex.id);
  93872. };
  93873. //var totalVertices = mesh.getTotalVertices();
  93874. var totalVertices = submesh.verticesCount;
  93875. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93876. var indicesInit = function (i) {
  93877. if (!indices) {
  93878. return;
  93879. }
  93880. var offset = (submesh.indexStart / 3) + i;
  93881. var pos = (offset * 3);
  93882. var i0 = indices[pos + 0];
  93883. var i1 = indices[pos + 1];
  93884. var i2 = indices[pos + 2];
  93885. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93886. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93887. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93888. var triangle = new DecimationTriangle([v0, v1, v2]);
  93889. triangle.originalOffset = pos;
  93890. _this.triangles.push(triangle);
  93891. };
  93892. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93893. _this.init(callback);
  93894. });
  93895. });
  93896. };
  93897. QuadraticErrorSimplification.prototype.init = function (callback) {
  93898. var _this = this;
  93899. var triangleInit1 = function (i) {
  93900. var t = _this.triangles[i];
  93901. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93902. for (var j = 0; j < 3; j++) {
  93903. 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))));
  93904. }
  93905. };
  93906. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93907. var triangleInit2 = function (i) {
  93908. var t = _this.triangles[i];
  93909. for (var j = 0; j < 3; ++j) {
  93910. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93911. }
  93912. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93913. };
  93914. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93915. callback();
  93916. });
  93917. });
  93918. };
  93919. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93920. var newTriangles = [];
  93921. var i;
  93922. for (i = 0; i < this.vertices.length; ++i) {
  93923. this.vertices[i].triangleCount = 0;
  93924. }
  93925. var t;
  93926. var j;
  93927. for (i = 0; i < this.triangles.length; ++i) {
  93928. if (!this.triangles[i].deleted) {
  93929. t = this.triangles[i];
  93930. for (j = 0; j < 3; ++j) {
  93931. t.vertices[j].triangleCount = 1;
  93932. }
  93933. newTriangles.push(t);
  93934. }
  93935. }
  93936. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93937. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93938. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93939. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93940. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93941. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93942. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93943. var vertexCount = 0;
  93944. for (i = 0; i < this.vertices.length; ++i) {
  93945. var vertex = this.vertices[i];
  93946. vertex.id = vertexCount;
  93947. if (vertex.triangleCount) {
  93948. vertex.originalOffsets.forEach(function (originalOffset) {
  93949. if (!normalData) {
  93950. return;
  93951. }
  93952. newPositionData.push(vertex.position.x);
  93953. newPositionData.push(vertex.position.y);
  93954. newPositionData.push(vertex.position.z);
  93955. newNormalData.push(normalData[originalOffset * 3]);
  93956. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93957. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93958. if (uvs && uvs.length) {
  93959. newUVsData.push(uvs[(originalOffset * 2)]);
  93960. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93961. }
  93962. else if (colorsData && colorsData.length) {
  93963. newColorsData.push(colorsData[(originalOffset * 4)]);
  93964. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93965. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93966. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93967. }
  93968. ++vertexCount;
  93969. });
  93970. }
  93971. }
  93972. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93973. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93974. var submeshesArray = this._reconstructedMesh.subMeshes;
  93975. this._reconstructedMesh.subMeshes = [];
  93976. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93977. var originalIndices = this._mesh.getIndices();
  93978. for (i = 0; i < newTriangles.length; ++i) {
  93979. t = newTriangles[i]; //now get the new referencing point for each vertex
  93980. [0, 1, 2].forEach(function (idx) {
  93981. var id = originalIndices[t.originalOffset + idx];
  93982. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93983. if (offset < 0)
  93984. offset = 0;
  93985. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93986. });
  93987. }
  93988. //overwriting the old vertex buffers and indices.
  93989. this._reconstructedMesh.setIndices(newIndicesArray);
  93990. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93991. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93992. if (newUVsData.length > 0)
  93993. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93994. if (newColorsData.length > 0)
  93995. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93996. //create submesh
  93997. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93998. if (submeshIndex > 0) {
  93999. this._reconstructedMesh.subMeshes = [];
  94000. submeshesArray.forEach(function (submesh) {
  94001. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94002. });
  94003. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94004. }
  94005. };
  94006. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94007. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94008. this._reconstructedMesh.material = this._mesh.material;
  94009. this._reconstructedMesh.parent = this._mesh.parent;
  94010. this._reconstructedMesh.isVisible = false;
  94011. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94012. };
  94013. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94014. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94015. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94016. if (t.deleted)
  94017. continue;
  94018. var s = this.references[vertex1.triangleStart + i].vertexId;
  94019. var v1 = t.vertices[(s + 1) % 3];
  94020. var v2 = t.vertices[(s + 2) % 3];
  94021. if ((v1 === vertex2 || v2 === vertex2)) {
  94022. deletedArray[i] = true;
  94023. delTr.push(t);
  94024. continue;
  94025. }
  94026. var d1 = v1.position.subtract(point);
  94027. d1 = d1.normalize();
  94028. var d2 = v2.position.subtract(point);
  94029. d2 = d2.normalize();
  94030. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94031. return true;
  94032. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94033. deletedArray[i] = false;
  94034. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94035. return true;
  94036. }
  94037. return false;
  94038. };
  94039. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94040. var newDeleted = deletedTriangles;
  94041. for (var i = 0; i < vertex.triangleCount; ++i) {
  94042. var ref = this.references[vertex.triangleStart + i];
  94043. var t = this.triangles[ref.triangleId];
  94044. if (t.deleted)
  94045. continue;
  94046. if (deletedArray[i] && t.deletePending) {
  94047. t.deleted = true;
  94048. newDeleted++;
  94049. continue;
  94050. }
  94051. t.vertices[ref.vertexId] = origVertex;
  94052. t.isDirty = true;
  94053. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94054. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94055. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94056. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94057. this.references.push(ref);
  94058. }
  94059. return newDeleted;
  94060. };
  94061. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94062. for (var i = 0; i < this.vertices.length; ++i) {
  94063. var vCount = [];
  94064. var vId = [];
  94065. var v = this.vertices[i];
  94066. var j;
  94067. for (j = 0; j < v.triangleCount; ++j) {
  94068. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94069. for (var ii = 0; ii < 3; ii++) {
  94070. var ofs = 0;
  94071. var vv = triangle.vertices[ii];
  94072. while (ofs < vCount.length) {
  94073. if (vId[ofs] === vv.id)
  94074. break;
  94075. ++ofs;
  94076. }
  94077. if (ofs === vCount.length) {
  94078. vCount.push(1);
  94079. vId.push(vv.id);
  94080. }
  94081. else {
  94082. vCount[ofs]++;
  94083. }
  94084. }
  94085. }
  94086. for (j = 0; j < vCount.length; ++j) {
  94087. if (vCount[j] === 1) {
  94088. this.vertices[vId[j]].isBorder = true;
  94089. }
  94090. else {
  94091. this.vertices[vId[j]].isBorder = false;
  94092. }
  94093. }
  94094. }
  94095. };
  94096. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94097. if (identifyBorders === void 0) { identifyBorders = false; }
  94098. var i;
  94099. if (!identifyBorders) {
  94100. var newTrianglesVector = [];
  94101. for (i = 0; i < this.triangles.length; ++i) {
  94102. if (!this.triangles[i].deleted) {
  94103. newTrianglesVector.push(this.triangles[i]);
  94104. }
  94105. }
  94106. this.triangles = newTrianglesVector;
  94107. }
  94108. for (i = 0; i < this.vertices.length; ++i) {
  94109. this.vertices[i].triangleCount = 0;
  94110. this.vertices[i].triangleStart = 0;
  94111. }
  94112. var t;
  94113. var j;
  94114. var v;
  94115. for (i = 0; i < this.triangles.length; ++i) {
  94116. t = this.triangles[i];
  94117. for (j = 0; j < 3; ++j) {
  94118. v = t.vertices[j];
  94119. v.triangleCount++;
  94120. }
  94121. }
  94122. var tStart = 0;
  94123. for (i = 0; i < this.vertices.length; ++i) {
  94124. this.vertices[i].triangleStart = tStart;
  94125. tStart += this.vertices[i].triangleCount;
  94126. this.vertices[i].triangleCount = 0;
  94127. }
  94128. var newReferences = new Array(this.triangles.length * 3);
  94129. for (i = 0; i < this.triangles.length; ++i) {
  94130. t = this.triangles[i];
  94131. for (j = 0; j < 3; ++j) {
  94132. v = t.vertices[j];
  94133. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94134. v.triangleCount++;
  94135. }
  94136. }
  94137. this.references = newReferences;
  94138. if (identifyBorders) {
  94139. this.identifyBorder();
  94140. }
  94141. };
  94142. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94143. var x = point.x;
  94144. var y = point.y;
  94145. var z = point.z;
  94146. 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
  94147. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94148. };
  94149. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94150. var q = vertex1.q.add(vertex2.q);
  94151. var border = vertex1.isBorder && vertex2.isBorder;
  94152. var error = 0;
  94153. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94154. if (qDet !== 0 && !border) {
  94155. if (!pointResult) {
  94156. pointResult = BABYLON.Vector3.Zero();
  94157. }
  94158. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94159. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94160. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94161. error = this.vertexError(q, pointResult);
  94162. }
  94163. else {
  94164. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94165. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94166. var error1 = this.vertexError(q, vertex1.position);
  94167. var error2 = this.vertexError(q, vertex2.position);
  94168. var error3 = this.vertexError(q, p3);
  94169. error = Math.min(error1, error2, error3);
  94170. if (error === error1) {
  94171. if (pointResult) {
  94172. pointResult.copyFrom(vertex1.position);
  94173. }
  94174. }
  94175. else if (error === error2) {
  94176. if (pointResult) {
  94177. pointResult.copyFrom(vertex2.position);
  94178. }
  94179. }
  94180. else {
  94181. if (pointResult) {
  94182. pointResult.copyFrom(p3);
  94183. }
  94184. }
  94185. }
  94186. return error;
  94187. };
  94188. return QuadraticErrorSimplification;
  94189. }());
  94190. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94191. })(BABYLON || (BABYLON = {}));
  94192. //# sourceMappingURL=babylon.meshSimplification.js.map
  94193. var BABYLON;
  94194. (function (BABYLON) {
  94195. var MeshLODLevel = /** @class */ (function () {
  94196. function MeshLODLevel(distance, mesh) {
  94197. this.distance = distance;
  94198. this.mesh = mesh;
  94199. }
  94200. return MeshLODLevel;
  94201. }());
  94202. BABYLON.MeshLODLevel = MeshLODLevel;
  94203. })(BABYLON || (BABYLON = {}));
  94204. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94205. var BABYLON;
  94206. (function (BABYLON) {
  94207. /**
  94208. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94209. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94210. */
  94211. var SceneOptimization = /** @class */ (function () {
  94212. /**
  94213. * Creates the SceneOptimization object
  94214. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94215. * @param desc defines the description associated with the optimization
  94216. */
  94217. function SceneOptimization(
  94218. /**
  94219. * Defines the priority of this optimization (0 by default which means first in the list)
  94220. */
  94221. priority) {
  94222. if (priority === void 0) { priority = 0; }
  94223. this.priority = priority;
  94224. }
  94225. /**
  94226. * Gets a string describing the action executed by the current optimization
  94227. * @returns description string
  94228. */
  94229. SceneOptimization.prototype.getDescription = function () {
  94230. return "";
  94231. };
  94232. /**
  94233. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94234. * @param scene defines the current scene where to apply this optimization
  94235. * @param optimizer defines the current optimizer
  94236. * @returns true if everything that can be done was applied
  94237. */
  94238. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94239. return true;
  94240. };
  94241. ;
  94242. return SceneOptimization;
  94243. }());
  94244. BABYLON.SceneOptimization = SceneOptimization;
  94245. /**
  94246. * Defines an optimization used to reduce the size of render target textures
  94247. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94248. */
  94249. var TextureOptimization = /** @class */ (function (_super) {
  94250. __extends(TextureOptimization, _super);
  94251. /**
  94252. * Creates the TextureOptimization object
  94253. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94254. * @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
  94255. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94256. */
  94257. function TextureOptimization(
  94258. /**
  94259. * Defines the priority of this optimization (0 by default which means first in the list)
  94260. */
  94261. priority,
  94262. /**
  94263. * 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
  94264. */
  94265. maximumSize,
  94266. /**
  94267. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94268. */
  94269. step) {
  94270. if (priority === void 0) { priority = 0; }
  94271. if (maximumSize === void 0) { maximumSize = 1024; }
  94272. if (step === void 0) { step = 0.5; }
  94273. var _this = _super.call(this, priority) || this;
  94274. _this.priority = priority;
  94275. _this.maximumSize = maximumSize;
  94276. _this.step = step;
  94277. return _this;
  94278. }
  94279. /**
  94280. * Gets a string describing the action executed by the current optimization
  94281. * @returns description string
  94282. */
  94283. TextureOptimization.prototype.getDescription = function () {
  94284. return "Reducing render target texture size to " + this.maximumSize;
  94285. };
  94286. /**
  94287. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94288. * @param scene defines the current scene where to apply this optimization
  94289. * @param optimizer defines the current optimizer
  94290. * @returns true if everything that can be done was applied
  94291. */
  94292. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94293. var allDone = true;
  94294. for (var index = 0; index < scene.textures.length; index++) {
  94295. var texture = scene.textures[index];
  94296. if (!texture.canRescale || texture.getContext) {
  94297. continue;
  94298. }
  94299. var currentSize = texture.getSize();
  94300. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94301. if (maxDimension > this.maximumSize) {
  94302. texture.scale(this.step);
  94303. allDone = false;
  94304. }
  94305. }
  94306. return allDone;
  94307. };
  94308. return TextureOptimization;
  94309. }(SceneOptimization));
  94310. BABYLON.TextureOptimization = TextureOptimization;
  94311. /**
  94312. * Defines an optimization used to increase or decrease the rendering resolution
  94313. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94314. */
  94315. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94316. __extends(HardwareScalingOptimization, _super);
  94317. /**
  94318. * Creates the HardwareScalingOptimization object
  94319. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94320. * @param maximumScale defines the maximum scale to use (2 by default)
  94321. * @param step defines the step to use between two passes (0.5 by default)
  94322. */
  94323. function HardwareScalingOptimization(
  94324. /**
  94325. * Defines the priority of this optimization (0 by default which means first in the list)
  94326. */
  94327. priority,
  94328. /**
  94329. * Defines the maximum scale to use (2 by default)
  94330. */
  94331. maximumScale,
  94332. /**
  94333. * Defines the step to use between two passes (0.5 by default)
  94334. */
  94335. step) {
  94336. if (priority === void 0) { priority = 0; }
  94337. if (maximumScale === void 0) { maximumScale = 2; }
  94338. if (step === void 0) { step = 0.25; }
  94339. var _this = _super.call(this, priority) || this;
  94340. _this.priority = priority;
  94341. _this.maximumScale = maximumScale;
  94342. _this.step = step;
  94343. _this._currentScale = -1;
  94344. _this._directionOffset = 1;
  94345. return _this;
  94346. }
  94347. /**
  94348. * Gets a string describing the action executed by the current optimization
  94349. * @return description string
  94350. */
  94351. HardwareScalingOptimization.prototype.getDescription = function () {
  94352. return "Setting hardware scaling level to " + this._currentScale;
  94353. };
  94354. /**
  94355. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94356. * @param scene defines the current scene where to apply this optimization
  94357. * @param optimizer defines the current optimizer
  94358. * @returns true if everything that can be done was applied
  94359. */
  94360. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94361. if (this._currentScale === -1) {
  94362. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94363. if (this._currentScale > this.maximumScale) {
  94364. this._directionOffset = -1;
  94365. }
  94366. }
  94367. this._currentScale += this._directionOffset * this.step;
  94368. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94369. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94370. };
  94371. ;
  94372. return HardwareScalingOptimization;
  94373. }(SceneOptimization));
  94374. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94375. /**
  94376. * Defines an optimization used to remove shadows
  94377. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94378. */
  94379. var ShadowsOptimization = /** @class */ (function (_super) {
  94380. __extends(ShadowsOptimization, _super);
  94381. function ShadowsOptimization() {
  94382. return _super !== null && _super.apply(this, arguments) || this;
  94383. }
  94384. /**
  94385. * Gets a string describing the action executed by the current optimization
  94386. * @return description string
  94387. */
  94388. ShadowsOptimization.prototype.getDescription = function () {
  94389. return "Turning shadows on/off";
  94390. };
  94391. /**
  94392. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94393. * @param scene defines the current scene where to apply this optimization
  94394. * @param optimizer defines the current optimizer
  94395. * @returns true if everything that can be done was applied
  94396. */
  94397. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94398. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94399. return true;
  94400. };
  94401. ;
  94402. return ShadowsOptimization;
  94403. }(SceneOptimization));
  94404. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94405. /**
  94406. * Defines an optimization used to turn post-processes off
  94407. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94408. */
  94409. var PostProcessesOptimization = /** @class */ (function (_super) {
  94410. __extends(PostProcessesOptimization, _super);
  94411. function PostProcessesOptimization() {
  94412. return _super !== null && _super.apply(this, arguments) || this;
  94413. }
  94414. /**
  94415. * Gets a string describing the action executed by the current optimization
  94416. * @return description string
  94417. */
  94418. PostProcessesOptimization.prototype.getDescription = function () {
  94419. return "Turning post-processes on/off";
  94420. };
  94421. /**
  94422. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94423. * @param scene defines the current scene where to apply this optimization
  94424. * @param optimizer defines the current optimizer
  94425. * @returns true if everything that can be done was applied
  94426. */
  94427. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94428. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94429. return true;
  94430. };
  94431. ;
  94432. return PostProcessesOptimization;
  94433. }(SceneOptimization));
  94434. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94435. /**
  94436. * Defines an optimization used to turn lens flares off
  94437. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94438. */
  94439. var LensFlaresOptimization = /** @class */ (function (_super) {
  94440. __extends(LensFlaresOptimization, _super);
  94441. function LensFlaresOptimization() {
  94442. return _super !== null && _super.apply(this, arguments) || this;
  94443. }
  94444. /**
  94445. * Gets a string describing the action executed by the current optimization
  94446. * @return description string
  94447. */
  94448. LensFlaresOptimization.prototype.getDescription = function () {
  94449. return "Turning lens flares on/off";
  94450. };
  94451. /**
  94452. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94453. * @param scene defines the current scene where to apply this optimization
  94454. * @param optimizer defines the current optimizer
  94455. * @returns true if everything that can be done was applied
  94456. */
  94457. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94458. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94459. return true;
  94460. };
  94461. ;
  94462. return LensFlaresOptimization;
  94463. }(SceneOptimization));
  94464. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94465. /**
  94466. * Defines an optimization based on user defined callback.
  94467. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94468. */
  94469. var CustomOptimization = /** @class */ (function (_super) {
  94470. __extends(CustomOptimization, _super);
  94471. function CustomOptimization() {
  94472. return _super !== null && _super.apply(this, arguments) || this;
  94473. }
  94474. /**
  94475. * Gets a string describing the action executed by the current optimization
  94476. * @returns description string
  94477. */
  94478. CustomOptimization.prototype.getDescription = function () {
  94479. if (this.onGetDescription) {
  94480. return this.onGetDescription();
  94481. }
  94482. return "Running user defined callback";
  94483. };
  94484. /**
  94485. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94486. * @param scene defines the current scene where to apply this optimization
  94487. * @param optimizer defines the current optimizer
  94488. * @returns true if everything that can be done was applied
  94489. */
  94490. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94491. if (this.onApply) {
  94492. return this.onApply(scene, optimizer);
  94493. }
  94494. return true;
  94495. };
  94496. ;
  94497. return CustomOptimization;
  94498. }(SceneOptimization));
  94499. BABYLON.CustomOptimization = CustomOptimization;
  94500. /**
  94501. * Defines an optimization used to turn particles off
  94502. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94503. */
  94504. var ParticlesOptimization = /** @class */ (function (_super) {
  94505. __extends(ParticlesOptimization, _super);
  94506. function ParticlesOptimization() {
  94507. return _super !== null && _super.apply(this, arguments) || this;
  94508. }
  94509. /**
  94510. * Gets a string describing the action executed by the current optimization
  94511. * @return description string
  94512. */
  94513. ParticlesOptimization.prototype.getDescription = function () {
  94514. return "Turning particles on/off";
  94515. };
  94516. /**
  94517. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94518. * @param scene defines the current scene where to apply this optimization
  94519. * @param optimizer defines the current optimizer
  94520. * @returns true if everything that can be done was applied
  94521. */
  94522. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94523. scene.particlesEnabled = optimizer.isInImprovementMode;
  94524. return true;
  94525. };
  94526. ;
  94527. return ParticlesOptimization;
  94528. }(SceneOptimization));
  94529. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94530. /**
  94531. * Defines an optimization used to turn render targets off
  94532. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94533. */
  94534. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94535. __extends(RenderTargetsOptimization, _super);
  94536. function RenderTargetsOptimization() {
  94537. return _super !== null && _super.apply(this, arguments) || this;
  94538. }
  94539. /**
  94540. * Gets a string describing the action executed by the current optimization
  94541. * @return description string
  94542. */
  94543. RenderTargetsOptimization.prototype.getDescription = function () {
  94544. return "Turning render targets off";
  94545. };
  94546. /**
  94547. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94548. * @param scene defines the current scene where to apply this optimization
  94549. * @param optimizer defines the current optimizer
  94550. * @returns true if everything that can be done was applied
  94551. */
  94552. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94553. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94554. return true;
  94555. };
  94556. ;
  94557. return RenderTargetsOptimization;
  94558. }(SceneOptimization));
  94559. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94560. /**
  94561. * Defines an optimization used to merge meshes with compatible materials
  94562. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94563. */
  94564. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94565. __extends(MergeMeshesOptimization, _super);
  94566. function MergeMeshesOptimization() {
  94567. var _this = _super !== null && _super.apply(this, arguments) || this;
  94568. _this._canBeMerged = function (abstractMesh) {
  94569. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94570. return false;
  94571. }
  94572. var mesh = abstractMesh;
  94573. if (!mesh.isVisible || !mesh.isEnabled()) {
  94574. return false;
  94575. }
  94576. if (mesh.instances.length > 0) {
  94577. return false;
  94578. }
  94579. if (mesh.skeleton || mesh.hasLODLevels) {
  94580. return false;
  94581. }
  94582. if (mesh.parent) {
  94583. return false;
  94584. }
  94585. return true;
  94586. };
  94587. return _this;
  94588. }
  94589. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94590. /**
  94591. * Gets or sets a boolean which defines if optimization octree has to be updated
  94592. */
  94593. get: function () {
  94594. return MergeMeshesOptimization._UpdateSelectionTree;
  94595. },
  94596. /**
  94597. * Gets or sets a boolean which defines if optimization octree has to be updated
  94598. */
  94599. set: function (value) {
  94600. MergeMeshesOptimization._UpdateSelectionTree = value;
  94601. },
  94602. enumerable: true,
  94603. configurable: true
  94604. });
  94605. /**
  94606. * Gets a string describing the action executed by the current optimization
  94607. * @return description string
  94608. */
  94609. MergeMeshesOptimization.prototype.getDescription = function () {
  94610. return "Merging similar meshes together";
  94611. };
  94612. /**
  94613. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94614. * @param scene defines the current scene where to apply this optimization
  94615. * @param optimizer defines the current optimizer
  94616. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94617. * @returns true if everything that can be done was applied
  94618. */
  94619. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94620. var globalPool = scene.meshes.slice(0);
  94621. var globalLength = globalPool.length;
  94622. for (var index = 0; index < globalLength; index++) {
  94623. var currentPool = new Array();
  94624. var current = globalPool[index];
  94625. // Checks
  94626. if (!this._canBeMerged(current)) {
  94627. continue;
  94628. }
  94629. currentPool.push(current);
  94630. // Find compatible meshes
  94631. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94632. var otherMesh = globalPool[subIndex];
  94633. if (!this._canBeMerged(otherMesh)) {
  94634. continue;
  94635. }
  94636. if (otherMesh.material !== current.material) {
  94637. continue;
  94638. }
  94639. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94640. continue;
  94641. }
  94642. currentPool.push(otherMesh);
  94643. globalLength--;
  94644. globalPool.splice(subIndex, 1);
  94645. subIndex--;
  94646. }
  94647. if (currentPool.length < 2) {
  94648. continue;
  94649. }
  94650. // Merge meshes
  94651. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94652. }
  94653. if (updateSelectionTree != undefined) {
  94654. if (updateSelectionTree) {
  94655. scene.createOrUpdateSelectionOctree();
  94656. }
  94657. }
  94658. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94659. scene.createOrUpdateSelectionOctree();
  94660. }
  94661. return true;
  94662. };
  94663. ;
  94664. MergeMeshesOptimization._UpdateSelectionTree = false;
  94665. return MergeMeshesOptimization;
  94666. }(SceneOptimization));
  94667. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94668. /**
  94669. * Defines a list of options used by SceneOptimizer
  94670. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94671. */
  94672. var SceneOptimizerOptions = /** @class */ (function () {
  94673. /**
  94674. * Creates a new list of options used by SceneOptimizer
  94675. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94676. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94677. */
  94678. function SceneOptimizerOptions(
  94679. /**
  94680. * Defines the target frame rate to reach (60 by default)
  94681. */
  94682. targetFrameRate,
  94683. /**
  94684. * Defines the interval between two checkes (2000ms by default)
  94685. */
  94686. trackerDuration) {
  94687. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94688. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94689. this.targetFrameRate = targetFrameRate;
  94690. this.trackerDuration = trackerDuration;
  94691. /**
  94692. * Gets the list of optimizations to apply
  94693. */
  94694. this.optimizations = new Array();
  94695. }
  94696. /**
  94697. * Add a new optimization
  94698. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94699. * @returns the current SceneOptimizerOptions
  94700. */
  94701. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94702. this.optimizations.push(optimization);
  94703. return this;
  94704. };
  94705. /**
  94706. * Add a new custom optimization
  94707. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94708. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94709. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94710. * @returns the current SceneOptimizerOptions
  94711. */
  94712. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94713. if (priority === void 0) { priority = 0; }
  94714. var optimization = new CustomOptimization(priority);
  94715. optimization.onApply = onApply;
  94716. optimization.onGetDescription = onGetDescription;
  94717. this.optimizations.push(optimization);
  94718. return this;
  94719. };
  94720. /**
  94721. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94722. * @param targetFrameRate defines the target frame rate (60 by default)
  94723. * @returns a SceneOptimizerOptions object
  94724. */
  94725. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94726. var result = new SceneOptimizerOptions(targetFrameRate);
  94727. var priority = 0;
  94728. result.addOptimization(new MergeMeshesOptimization(priority));
  94729. result.addOptimization(new ShadowsOptimization(priority));
  94730. result.addOptimization(new LensFlaresOptimization(priority));
  94731. // Next priority
  94732. priority++;
  94733. result.addOptimization(new PostProcessesOptimization(priority));
  94734. result.addOptimization(new ParticlesOptimization(priority));
  94735. // Next priority
  94736. priority++;
  94737. result.addOptimization(new TextureOptimization(priority, 1024));
  94738. return result;
  94739. };
  94740. /**
  94741. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94742. * @param targetFrameRate defines the target frame rate (60 by default)
  94743. * @returns a SceneOptimizerOptions object
  94744. */
  94745. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94746. var result = new SceneOptimizerOptions(targetFrameRate);
  94747. var priority = 0;
  94748. result.addOptimization(new MergeMeshesOptimization(priority));
  94749. result.addOptimization(new ShadowsOptimization(priority));
  94750. result.addOptimization(new LensFlaresOptimization(priority));
  94751. // Next priority
  94752. priority++;
  94753. result.addOptimization(new PostProcessesOptimization(priority));
  94754. result.addOptimization(new ParticlesOptimization(priority));
  94755. // Next priority
  94756. priority++;
  94757. result.addOptimization(new TextureOptimization(priority, 512));
  94758. // Next priority
  94759. priority++;
  94760. result.addOptimization(new RenderTargetsOptimization(priority));
  94761. // Next priority
  94762. priority++;
  94763. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94764. return result;
  94765. };
  94766. /**
  94767. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94768. * @param targetFrameRate defines the target frame rate (60 by default)
  94769. * @returns a SceneOptimizerOptions object
  94770. */
  94771. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94772. var result = new SceneOptimizerOptions(targetFrameRate);
  94773. var priority = 0;
  94774. result.addOptimization(new MergeMeshesOptimization(priority));
  94775. result.addOptimization(new ShadowsOptimization(priority));
  94776. result.addOptimization(new LensFlaresOptimization(priority));
  94777. // Next priority
  94778. priority++;
  94779. result.addOptimization(new PostProcessesOptimization(priority));
  94780. result.addOptimization(new ParticlesOptimization(priority));
  94781. // Next priority
  94782. priority++;
  94783. result.addOptimization(new TextureOptimization(priority, 256));
  94784. // Next priority
  94785. priority++;
  94786. result.addOptimization(new RenderTargetsOptimization(priority));
  94787. // Next priority
  94788. priority++;
  94789. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94790. return result;
  94791. };
  94792. return SceneOptimizerOptions;
  94793. }());
  94794. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94795. /**
  94796. * Class used to run optimizations in order to reach a target frame rate
  94797. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94798. */
  94799. var SceneOptimizer = /** @class */ (function () {
  94800. /**
  94801. * Creates a new SceneOptimizer
  94802. * @param scene defines the scene to work on
  94803. * @param options defines the options to use with the SceneOptimizer
  94804. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94805. * @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)
  94806. */
  94807. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94808. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94809. if (improvementMode === void 0) { improvementMode = false; }
  94810. var _this = this;
  94811. this._isRunning = false;
  94812. this._currentPriorityLevel = 0;
  94813. this._targetFrameRate = 60;
  94814. this._trackerDuration = 2000;
  94815. this._currentFrameRate = 0;
  94816. this._improvementMode = false;
  94817. /**
  94818. * Defines an observable called when the optimizer reaches the target frame rate
  94819. */
  94820. this.onSuccessObservable = new BABYLON.Observable();
  94821. /**
  94822. * Defines an observable called when the optimizer enables an optimization
  94823. */
  94824. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94825. /**
  94826. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94827. */
  94828. this.onFailureObservable = new BABYLON.Observable();
  94829. if (!options) {
  94830. this._options = new SceneOptimizerOptions();
  94831. }
  94832. else {
  94833. this._options = options;
  94834. }
  94835. if (this._options.targetFrameRate) {
  94836. this._targetFrameRate = this._options.targetFrameRate;
  94837. }
  94838. if (this._options.trackerDuration) {
  94839. this._trackerDuration = this._options.trackerDuration;
  94840. }
  94841. if (autoGeneratePriorities) {
  94842. var priority = 0;
  94843. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94844. var optim = _a[_i];
  94845. optim.priority = priority++;
  94846. }
  94847. }
  94848. this._improvementMode = improvementMode;
  94849. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94850. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94851. _this._sceneDisposeObserver = null;
  94852. _this.dispose();
  94853. });
  94854. }
  94855. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94856. /**
  94857. * Gets a boolean indicating if the optimizer is in improvement mode
  94858. */
  94859. get: function () {
  94860. return this._improvementMode;
  94861. },
  94862. enumerable: true,
  94863. configurable: true
  94864. });
  94865. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94866. /**
  94867. * Gets the current priority level (0 at start)
  94868. */
  94869. get: function () {
  94870. return this._currentPriorityLevel;
  94871. },
  94872. enumerable: true,
  94873. configurable: true
  94874. });
  94875. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94876. /**
  94877. * Gets the current frame rate checked by the SceneOptimizer
  94878. */
  94879. get: function () {
  94880. return this._currentFrameRate;
  94881. },
  94882. enumerable: true,
  94883. configurable: true
  94884. });
  94885. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94886. /**
  94887. * Gets or sets the current target frame rate (60 by default)
  94888. */
  94889. get: function () {
  94890. return this._targetFrameRate;
  94891. },
  94892. /**
  94893. * Gets or sets the current target frame rate (60 by default)
  94894. */
  94895. set: function (value) {
  94896. this._targetFrameRate = value;
  94897. },
  94898. enumerable: true,
  94899. configurable: true
  94900. });
  94901. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94902. /**
  94903. * Gets or sets the current interval between two checks (every 2000ms by default)
  94904. */
  94905. get: function () {
  94906. return this._trackerDuration;
  94907. },
  94908. /**
  94909. * Gets or sets the current interval between two checks (every 2000ms by default)
  94910. */
  94911. set: function (value) {
  94912. this._trackerDuration = value;
  94913. },
  94914. enumerable: true,
  94915. configurable: true
  94916. });
  94917. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94918. /**
  94919. * Gets the list of active optimizations
  94920. */
  94921. get: function () {
  94922. return this._options.optimizations;
  94923. },
  94924. enumerable: true,
  94925. configurable: true
  94926. });
  94927. /**
  94928. * Stops the current optimizer
  94929. */
  94930. SceneOptimizer.prototype.stop = function () {
  94931. this._isRunning = false;
  94932. };
  94933. /**
  94934. * Reset the optimizer to initial step (current priority level = 0)
  94935. */
  94936. SceneOptimizer.prototype.reset = function () {
  94937. this._currentPriorityLevel = 0;
  94938. };
  94939. /**
  94940. * Start the optimizer. By default it will try to reach a specific framerate
  94941. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94942. */
  94943. SceneOptimizer.prototype.start = function () {
  94944. var _this = this;
  94945. if (this._isRunning) {
  94946. return;
  94947. }
  94948. this._isRunning = true;
  94949. // Let's wait for the scene to be ready before running our check
  94950. this._scene.executeWhenReady(function () {
  94951. setTimeout(function () {
  94952. _this._checkCurrentState();
  94953. }, _this._trackerDuration);
  94954. });
  94955. };
  94956. SceneOptimizer.prototype._checkCurrentState = function () {
  94957. var _this = this;
  94958. if (!this._isRunning) {
  94959. return;
  94960. }
  94961. var scene = this._scene;
  94962. var options = this._options;
  94963. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94964. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94965. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94966. this._isRunning = false;
  94967. this.onSuccessObservable.notifyObservers(this);
  94968. return;
  94969. }
  94970. // Apply current level of optimizations
  94971. var allDone = true;
  94972. var noOptimizationApplied = true;
  94973. for (var index = 0; index < options.optimizations.length; index++) {
  94974. var optimization = options.optimizations[index];
  94975. if (optimization.priority === this._currentPriorityLevel) {
  94976. noOptimizationApplied = false;
  94977. allDone = allDone && optimization.apply(scene, this);
  94978. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94979. }
  94980. }
  94981. // If no optimization was applied, this is a failure :(
  94982. if (noOptimizationApplied) {
  94983. this._isRunning = false;
  94984. this.onFailureObservable.notifyObservers(this);
  94985. return;
  94986. }
  94987. // If all optimizations were done, move to next level
  94988. if (allDone) {
  94989. this._currentPriorityLevel++;
  94990. }
  94991. // Let's the system running for a specific amount of time before checking FPS
  94992. scene.executeWhenReady(function () {
  94993. setTimeout(function () {
  94994. _this._checkCurrentState();
  94995. }, _this._trackerDuration);
  94996. });
  94997. };
  94998. /**
  94999. * Release all resources
  95000. */
  95001. SceneOptimizer.prototype.dispose = function () {
  95002. this.stop();
  95003. this.onSuccessObservable.clear();
  95004. this.onFailureObservable.clear();
  95005. this.onNewOptimizationAppliedObservable.clear();
  95006. if (this._sceneDisposeObserver) {
  95007. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95008. }
  95009. };
  95010. /**
  95011. * Helper function to create a SceneOptimizer with one single line of code
  95012. * @param scene defines the scene to work on
  95013. * @param options defines the options to use with the SceneOptimizer
  95014. * @param onSuccess defines a callback to call on success
  95015. * @param onFailure defines a callback to call on failure
  95016. * @returns the new SceneOptimizer object
  95017. */
  95018. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95019. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95020. if (onSuccess) {
  95021. optimizer.onSuccessObservable.add(function () {
  95022. onSuccess();
  95023. });
  95024. }
  95025. if (onFailure) {
  95026. optimizer.onFailureObservable.add(function () {
  95027. onFailure();
  95028. });
  95029. }
  95030. optimizer.start();
  95031. return optimizer;
  95032. };
  95033. return SceneOptimizer;
  95034. }());
  95035. BABYLON.SceneOptimizer = SceneOptimizer;
  95036. })(BABYLON || (BABYLON = {}));
  95037. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95038. var BABYLON;
  95039. (function (BABYLON) {
  95040. var OutlineRenderer = /** @class */ (function () {
  95041. function OutlineRenderer(scene) {
  95042. this.zOffset = 1;
  95043. this._scene = scene;
  95044. }
  95045. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95046. var _this = this;
  95047. if (useOverlay === void 0) { useOverlay = false; }
  95048. var scene = this._scene;
  95049. var engine = this._scene.getEngine();
  95050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95051. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95052. return;
  95053. }
  95054. var mesh = subMesh.getRenderingMesh();
  95055. var material = subMesh.getMaterial();
  95056. if (!material || !scene.activeCamera) {
  95057. return;
  95058. }
  95059. engine.enableEffect(this._effect);
  95060. // Logarithmic depth
  95061. if (material.useLogarithmicDepth) {
  95062. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95063. }
  95064. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95065. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95066. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95067. // Bones
  95068. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95069. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95070. }
  95071. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95072. // Alpha test
  95073. if (material && material.needAlphaTesting()) {
  95074. var alphaTexture = material.getAlphaTestTexture();
  95075. if (alphaTexture) {
  95076. this._effect.setTexture("diffuseSampler", alphaTexture);
  95077. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95078. }
  95079. }
  95080. engine.setZOffset(-this.zOffset);
  95081. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95082. engine.setZOffset(0);
  95083. };
  95084. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95085. var defines = [];
  95086. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95087. var mesh = subMesh.getMesh();
  95088. var material = subMesh.getMaterial();
  95089. if (material) {
  95090. // Alpha test
  95091. if (material.needAlphaTesting()) {
  95092. defines.push("#define ALPHATEST");
  95093. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95094. attribs.push(BABYLON.VertexBuffer.UVKind);
  95095. defines.push("#define UV1");
  95096. }
  95097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95098. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95099. defines.push("#define UV2");
  95100. }
  95101. }
  95102. //Logarithmic depth
  95103. if (material.useLogarithmicDepth) {
  95104. defines.push("#define LOGARITHMICDEPTH");
  95105. }
  95106. }
  95107. // Bones
  95108. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95109. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95110. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95111. if (mesh.numBoneInfluencers > 4) {
  95112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95114. }
  95115. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95116. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95117. }
  95118. else {
  95119. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95120. }
  95121. // Instances
  95122. if (useInstances) {
  95123. defines.push("#define INSTANCES");
  95124. attribs.push("world0");
  95125. attribs.push("world1");
  95126. attribs.push("world2");
  95127. attribs.push("world3");
  95128. }
  95129. // Get correct effect
  95130. var join = defines.join("\n");
  95131. if (this._cachedDefines !== join) {
  95132. this._cachedDefines = join;
  95133. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95134. }
  95135. return this._effect.isReady();
  95136. };
  95137. return OutlineRenderer;
  95138. }());
  95139. BABYLON.OutlineRenderer = OutlineRenderer;
  95140. })(BABYLON || (BABYLON = {}));
  95141. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95142. var BABYLON;
  95143. (function (BABYLON) {
  95144. var FaceAdjacencies = /** @class */ (function () {
  95145. function FaceAdjacencies() {
  95146. this.edges = new Array();
  95147. this.edgesConnectedCount = 0;
  95148. }
  95149. return FaceAdjacencies;
  95150. }());
  95151. var EdgesRenderer = /** @class */ (function () {
  95152. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95153. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95154. if (epsilon === void 0) { epsilon = 0.95; }
  95155. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95156. this.edgesWidthScalerForOrthographic = 1000.0;
  95157. this.edgesWidthScalerForPerspective = 50.0;
  95158. this._linesPositions = new Array();
  95159. this._linesNormals = new Array();
  95160. this._linesIndices = new Array();
  95161. this._buffers = {};
  95162. this._checkVerticesInsteadOfIndices = false;
  95163. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95164. this.isEnabled = true;
  95165. this._source = source;
  95166. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95167. this._epsilon = epsilon;
  95168. this._prepareRessources();
  95169. this._generateEdgesLines();
  95170. }
  95171. EdgesRenderer.prototype._prepareRessources = function () {
  95172. if (this._lineShader) {
  95173. return;
  95174. }
  95175. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95176. attributes: ["position", "normal"],
  95177. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95178. });
  95179. this._lineShader.disableDepthWrite = true;
  95180. this._lineShader.backFaceCulling = false;
  95181. };
  95182. EdgesRenderer.prototype._rebuild = function () {
  95183. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95184. if (buffer) {
  95185. buffer._rebuild();
  95186. }
  95187. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95188. if (buffer) {
  95189. buffer._rebuild();
  95190. }
  95191. var scene = this._source.getScene();
  95192. var engine = scene.getEngine();
  95193. this._ib = engine.createIndexBuffer(this._linesIndices);
  95194. };
  95195. EdgesRenderer.prototype.dispose = function () {
  95196. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95197. if (buffer) {
  95198. buffer.dispose();
  95199. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95200. }
  95201. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95202. if (buffer) {
  95203. buffer.dispose();
  95204. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95205. }
  95206. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95207. this._lineShader.dispose();
  95208. };
  95209. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95210. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95211. return 0;
  95212. }
  95213. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95214. return 1;
  95215. }
  95216. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95217. return 2;
  95218. }
  95219. return -1;
  95220. };
  95221. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95222. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95223. return 0;
  95224. }
  95225. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95226. return 1;
  95227. }
  95228. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95229. return 2;
  95230. }
  95231. return -1;
  95232. };
  95233. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95234. var needToCreateLine;
  95235. if (edge === undefined) {
  95236. needToCreateLine = true;
  95237. }
  95238. else {
  95239. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95240. needToCreateLine = dotProduct < this._epsilon;
  95241. }
  95242. if (needToCreateLine) {
  95243. var offset = this._linesPositions.length / 3;
  95244. var normal = p0.subtract(p1);
  95245. normal.normalize();
  95246. // Positions
  95247. this._linesPositions.push(p0.x);
  95248. this._linesPositions.push(p0.y);
  95249. this._linesPositions.push(p0.z);
  95250. this._linesPositions.push(p0.x);
  95251. this._linesPositions.push(p0.y);
  95252. this._linesPositions.push(p0.z);
  95253. this._linesPositions.push(p1.x);
  95254. this._linesPositions.push(p1.y);
  95255. this._linesPositions.push(p1.z);
  95256. this._linesPositions.push(p1.x);
  95257. this._linesPositions.push(p1.y);
  95258. this._linesPositions.push(p1.z);
  95259. // Normals
  95260. this._linesNormals.push(p1.x);
  95261. this._linesNormals.push(p1.y);
  95262. this._linesNormals.push(p1.z);
  95263. this._linesNormals.push(-1);
  95264. this._linesNormals.push(p1.x);
  95265. this._linesNormals.push(p1.y);
  95266. this._linesNormals.push(p1.z);
  95267. this._linesNormals.push(1);
  95268. this._linesNormals.push(p0.x);
  95269. this._linesNormals.push(p0.y);
  95270. this._linesNormals.push(p0.z);
  95271. this._linesNormals.push(-1);
  95272. this._linesNormals.push(p0.x);
  95273. this._linesNormals.push(p0.y);
  95274. this._linesNormals.push(p0.z);
  95275. this._linesNormals.push(1);
  95276. // Indices
  95277. this._linesIndices.push(offset);
  95278. this._linesIndices.push(offset + 1);
  95279. this._linesIndices.push(offset + 2);
  95280. this._linesIndices.push(offset);
  95281. this._linesIndices.push(offset + 2);
  95282. this._linesIndices.push(offset + 3);
  95283. }
  95284. };
  95285. EdgesRenderer.prototype._generateEdgesLines = function () {
  95286. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95287. var indices = this._source.getIndices();
  95288. if (!indices || !positions) {
  95289. return;
  95290. }
  95291. // First let's find adjacencies
  95292. var adjacencies = new Array();
  95293. var faceNormals = new Array();
  95294. var index;
  95295. var faceAdjacencies;
  95296. // Prepare faces
  95297. for (index = 0; index < indices.length; index += 3) {
  95298. faceAdjacencies = new FaceAdjacencies();
  95299. var p0Index = indices[index];
  95300. var p1Index = indices[index + 1];
  95301. var p2Index = indices[index + 2];
  95302. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95303. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95304. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95305. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95306. faceNormal.normalize();
  95307. faceNormals.push(faceNormal);
  95308. adjacencies.push(faceAdjacencies);
  95309. }
  95310. // Scan
  95311. for (index = 0; index < adjacencies.length; index++) {
  95312. faceAdjacencies = adjacencies[index];
  95313. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95314. var otherFaceAdjacencies = adjacencies[otherIndex];
  95315. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95316. break;
  95317. }
  95318. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95319. continue;
  95320. }
  95321. var otherP0 = indices[otherIndex * 3];
  95322. var otherP1 = indices[otherIndex * 3 + 1];
  95323. var otherP2 = indices[otherIndex * 3 + 2];
  95324. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95325. var otherEdgeIndex = 0;
  95326. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95327. continue;
  95328. }
  95329. switch (edgeIndex) {
  95330. case 0:
  95331. if (this._checkVerticesInsteadOfIndices) {
  95332. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95333. }
  95334. else {
  95335. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95336. }
  95337. break;
  95338. case 1:
  95339. if (this._checkVerticesInsteadOfIndices) {
  95340. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95341. }
  95342. else {
  95343. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95344. }
  95345. break;
  95346. case 2:
  95347. if (this._checkVerticesInsteadOfIndices) {
  95348. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95349. }
  95350. else {
  95351. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95352. }
  95353. break;
  95354. }
  95355. if (otherEdgeIndex === -1) {
  95356. continue;
  95357. }
  95358. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95359. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95360. faceAdjacencies.edgesConnectedCount++;
  95361. otherFaceAdjacencies.edgesConnectedCount++;
  95362. if (faceAdjacencies.edgesConnectedCount === 3) {
  95363. break;
  95364. }
  95365. }
  95366. }
  95367. }
  95368. // Create lines
  95369. for (index = 0; index < adjacencies.length; index++) {
  95370. // 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
  95371. var current = adjacencies[index];
  95372. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95373. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95374. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95375. }
  95376. // Merge into a single mesh
  95377. var engine = this._source.getScene().getEngine();
  95378. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95379. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95380. this._ib = engine.createIndexBuffer(this._linesIndices);
  95381. this._indicesCount = this._linesIndices.length;
  95382. };
  95383. EdgesRenderer.prototype.render = function () {
  95384. var scene = this._source.getScene();
  95385. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95386. return;
  95387. }
  95388. var engine = scene.getEngine();
  95389. this._lineShader._preBind();
  95390. // VBOs
  95391. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95392. scene.resetCachedMaterial();
  95393. this._lineShader.setColor4("color", this._source.edgesColor);
  95394. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95395. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95396. }
  95397. else {
  95398. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95399. }
  95400. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95401. this._lineShader.bind(this._source.getWorldMatrix());
  95402. // Draw order
  95403. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95404. this._lineShader.unbind();
  95405. engine.setDepthWrite(true);
  95406. };
  95407. return EdgesRenderer;
  95408. }());
  95409. BABYLON.EdgesRenderer = EdgesRenderer;
  95410. })(BABYLON || (BABYLON = {}));
  95411. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95412. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95413. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95414. s = arguments[i];
  95415. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95416. t[p] = s[p];
  95417. }
  95418. return t;
  95419. };
  95420. var BABYLON;
  95421. (function (BABYLON) {
  95422. /**
  95423. * The effect layer Helps adding post process effect blended with the main pass.
  95424. *
  95425. * This can be for instance use to generate glow or higlight effects on the scene.
  95426. *
  95427. * The effect layer class can not be used directly and is intented to inherited from to be
  95428. * customized per effects.
  95429. */
  95430. var EffectLayer = /** @class */ (function () {
  95431. /**
  95432. * Instantiates a new effect Layer and references it in the scene.
  95433. * @param name The name of the layer
  95434. * @param scene The scene to use the layer in
  95435. */
  95436. function EffectLayer(
  95437. /** The Friendly of the effect in the scene */
  95438. name, scene) {
  95439. this._vertexBuffers = {};
  95440. this._maxSize = 0;
  95441. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95442. this._shouldRender = true;
  95443. this._postProcesses = [];
  95444. this._textures = [];
  95445. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95446. /**
  95447. * The clear color of the texture used to generate the glow map.
  95448. */
  95449. this.neutralColor = new BABYLON.Color4();
  95450. /**
  95451. * Specifies wether the highlight layer is enabled or not.
  95452. */
  95453. this.isEnabled = true;
  95454. /**
  95455. * An event triggered when the effect layer has been disposed.
  95456. */
  95457. this.onDisposeObservable = new BABYLON.Observable();
  95458. /**
  95459. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95460. */
  95461. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95462. /**
  95463. * An event triggered when the generated texture is being merged in the scene.
  95464. */
  95465. this.onBeforeComposeObservable = new BABYLON.Observable();
  95466. /**
  95467. * An event triggered when the generated texture has been merged in the scene.
  95468. */
  95469. this.onAfterComposeObservable = new BABYLON.Observable();
  95470. /**
  95471. * An event triggered when the efffect layer changes its size.
  95472. */
  95473. this.onSizeChangedObservable = new BABYLON.Observable();
  95474. this.name = name;
  95475. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95476. this._engine = scene.getEngine();
  95477. this._maxSize = this._engine.getCaps().maxTextureSize;
  95478. this._scene.effectLayers.push(this);
  95479. // Generate Buffers
  95480. this._generateIndexBuffer();
  95481. this._genrateVertexBuffer();
  95482. }
  95483. Object.defineProperty(EffectLayer.prototype, "camera", {
  95484. /**
  95485. * Gets the camera attached to the layer.
  95486. */
  95487. get: function () {
  95488. return this._effectLayerOptions.camera;
  95489. },
  95490. enumerable: true,
  95491. configurable: true
  95492. });
  95493. /**
  95494. * Initializes the effect layer with the required options.
  95495. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95496. */
  95497. EffectLayer.prototype._init = function (options) {
  95498. // Adapt options
  95499. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95500. this._setMainTextureSize();
  95501. this._createMainTexture();
  95502. this._createTextureAndPostProcesses();
  95503. this._mergeEffect = this._createMergeEffect();
  95504. };
  95505. /**
  95506. * Generates the index buffer of the full screen quad blending to the main canvas.
  95507. */
  95508. EffectLayer.prototype._generateIndexBuffer = function () {
  95509. // Indices
  95510. var indices = [];
  95511. indices.push(0);
  95512. indices.push(1);
  95513. indices.push(2);
  95514. indices.push(0);
  95515. indices.push(2);
  95516. indices.push(3);
  95517. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95518. };
  95519. /**
  95520. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95521. */
  95522. EffectLayer.prototype._genrateVertexBuffer = function () {
  95523. // VBO
  95524. var vertices = [];
  95525. vertices.push(1, 1);
  95526. vertices.push(-1, 1);
  95527. vertices.push(-1, -1);
  95528. vertices.push(1, -1);
  95529. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95530. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95531. };
  95532. /**
  95533. * Sets the main texture desired size which is the closest power of two
  95534. * of the engine canvas size.
  95535. */
  95536. EffectLayer.prototype._setMainTextureSize = function () {
  95537. if (this._effectLayerOptions.mainTextureFixedSize) {
  95538. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95539. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95540. }
  95541. else {
  95542. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95543. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95544. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95545. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95546. }
  95547. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95548. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95549. };
  95550. /**
  95551. * Creates the main texture for the effect layer.
  95552. */
  95553. EffectLayer.prototype._createMainTexture = function () {
  95554. var _this = this;
  95555. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95556. width: this._mainTextureDesiredSize.width,
  95557. height: this._mainTextureDesiredSize.height
  95558. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95559. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95560. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95561. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95562. this._mainTexture.anisotropicFilteringLevel = 1;
  95563. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95564. this._mainTexture.renderParticles = false;
  95565. this._mainTexture.renderList = null;
  95566. this._mainTexture.ignoreCameraViewport = true;
  95567. // Custom render function
  95568. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95569. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95570. var index;
  95571. var engine = _this._scene.getEngine();
  95572. if (depthOnlySubMeshes.length) {
  95573. engine.setColorWrite(false);
  95574. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95575. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95576. }
  95577. engine.setColorWrite(true);
  95578. }
  95579. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95580. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95581. }
  95582. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95583. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95584. }
  95585. for (index = 0; index < transparentSubMeshes.length; index++) {
  95586. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95587. }
  95588. };
  95589. this._mainTexture.onClearObservable.add(function (engine) {
  95590. engine.clear(_this.neutralColor, true, true, true);
  95591. });
  95592. };
  95593. /**
  95594. * Checks for the readiness of the element composing the layer.
  95595. * @param subMesh the mesh to check for
  95596. * @param useInstances specify wether or not to use instances to render the mesh
  95597. * @param emissiveTexture the associated emissive texture used to generate the glow
  95598. * @return true if ready otherwise, false
  95599. */
  95600. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95601. var material = subMesh.getMaterial();
  95602. if (!material) {
  95603. return false;
  95604. }
  95605. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95606. return false;
  95607. }
  95608. var defines = [];
  95609. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95610. var mesh = subMesh.getMesh();
  95611. var uv1 = false;
  95612. var uv2 = false;
  95613. // Alpha test
  95614. if (material && material.needAlphaTesting()) {
  95615. var alphaTexture = material.getAlphaTestTexture();
  95616. if (alphaTexture) {
  95617. defines.push("#define ALPHATEST");
  95618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95619. alphaTexture.coordinatesIndex === 1) {
  95620. defines.push("#define DIFFUSEUV2");
  95621. uv2 = true;
  95622. }
  95623. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95624. defines.push("#define DIFFUSEUV1");
  95625. uv1 = true;
  95626. }
  95627. }
  95628. }
  95629. // Emissive
  95630. if (emissiveTexture) {
  95631. defines.push("#define EMISSIVE");
  95632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95633. emissiveTexture.coordinatesIndex === 1) {
  95634. defines.push("#define EMISSIVEUV2");
  95635. uv2 = true;
  95636. }
  95637. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95638. defines.push("#define EMISSIVEUV1");
  95639. uv1 = true;
  95640. }
  95641. }
  95642. if (uv1) {
  95643. attribs.push(BABYLON.VertexBuffer.UVKind);
  95644. defines.push("#define UV1");
  95645. }
  95646. if (uv2) {
  95647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95648. defines.push("#define UV2");
  95649. }
  95650. // Bones
  95651. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95654. if (mesh.numBoneInfluencers > 4) {
  95655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95657. }
  95658. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95659. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95660. }
  95661. else {
  95662. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95663. }
  95664. // Morph targets
  95665. var manager = mesh.morphTargetManager;
  95666. var morphInfluencers = 0;
  95667. if (manager) {
  95668. if (manager.numInfluencers > 0) {
  95669. defines.push("#define MORPHTARGETS");
  95670. morphInfluencers = manager.numInfluencers;
  95671. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95672. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95673. }
  95674. }
  95675. // Instances
  95676. if (useInstances) {
  95677. defines.push("#define INSTANCES");
  95678. attribs.push("world0");
  95679. attribs.push("world1");
  95680. attribs.push("world2");
  95681. attribs.push("world3");
  95682. }
  95683. // Get correct effect
  95684. var join = defines.join("\n");
  95685. if (this._cachedDefines !== join) {
  95686. this._cachedDefines = join;
  95687. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95688. }
  95689. return this._effectLayerMapGenerationEffect.isReady();
  95690. };
  95691. /**
  95692. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95693. */
  95694. EffectLayer.prototype.render = function () {
  95695. var currentEffect = this._mergeEffect;
  95696. // Check
  95697. if (!currentEffect.isReady())
  95698. return;
  95699. for (var i = 0; i < this._postProcesses.length; i++) {
  95700. if (!this._postProcesses[i].isReady()) {
  95701. return;
  95702. }
  95703. }
  95704. var engine = this._scene.getEngine();
  95705. this.onBeforeComposeObservable.notifyObservers(this);
  95706. // Render
  95707. engine.enableEffect(currentEffect);
  95708. engine.setState(false);
  95709. // VBOs
  95710. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95711. // Cache
  95712. var previousAlphaMode = engine.getAlphaMode();
  95713. // Go Blend.
  95714. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95715. // Blends the map on the main canvas.
  95716. this._internalRender(currentEffect);
  95717. // Restore Alpha
  95718. engine.setAlphaMode(previousAlphaMode);
  95719. this.onAfterComposeObservable.notifyObservers(this);
  95720. // Handle size changes.
  95721. var size = this._mainTexture.getSize();
  95722. this._setMainTextureSize();
  95723. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95724. // Recreate RTT and post processes on size change.
  95725. this.onSizeChangedObservable.notifyObservers(this);
  95726. this._disposeTextureAndPostProcesses();
  95727. this._createMainTexture();
  95728. this._createTextureAndPostProcesses();
  95729. }
  95730. };
  95731. /**
  95732. * Determine if a given mesh will be used in the current effect.
  95733. * @param mesh mesh to test
  95734. * @returns true if the mesh will be used
  95735. */
  95736. EffectLayer.prototype.hasMesh = function (mesh) {
  95737. return true;
  95738. };
  95739. /**
  95740. * Returns true if the layer contains information to display, otherwise false.
  95741. * @returns true if the glow layer should be rendered
  95742. */
  95743. EffectLayer.prototype.shouldRender = function () {
  95744. return this.isEnabled && this._shouldRender;
  95745. };
  95746. /**
  95747. * Returns true if the mesh should render, otherwise false.
  95748. * @param mesh The mesh to render
  95749. * @returns true if it should render otherwise false
  95750. */
  95751. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95752. return true;
  95753. };
  95754. /**
  95755. * Returns true if the mesh should render, otherwise false.
  95756. * @param mesh The mesh to render
  95757. * @returns true if it should render otherwise false
  95758. */
  95759. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95760. return true;
  95761. };
  95762. /**
  95763. * Renders the submesh passed in parameter to the generation map.
  95764. */
  95765. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95766. var _this = this;
  95767. if (!this.shouldRender()) {
  95768. return;
  95769. }
  95770. var material = subMesh.getMaterial();
  95771. var mesh = subMesh.getRenderingMesh();
  95772. var scene = this._scene;
  95773. var engine = scene.getEngine();
  95774. if (!material) {
  95775. return;
  95776. }
  95777. // Do not block in blend mode.
  95778. if (material.needAlphaBlendingForMesh(mesh)) {
  95779. return;
  95780. }
  95781. // Culling
  95782. engine.setState(material.backFaceCulling);
  95783. // Managing instances
  95784. var batch = mesh._getInstancesRenderList(subMesh._id);
  95785. if (batch.mustReturn) {
  95786. return;
  95787. }
  95788. // Early Exit per mesh
  95789. if (!this._shouldRenderMesh(mesh)) {
  95790. return;
  95791. }
  95792. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95793. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95794. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95795. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95796. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95797. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95798. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95799. // Alpha test
  95800. if (material && material.needAlphaTesting()) {
  95801. var alphaTexture = material.getAlphaTestTexture();
  95802. if (alphaTexture) {
  95803. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95804. var textureMatrix = alphaTexture.getTextureMatrix();
  95805. if (textureMatrix) {
  95806. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95807. }
  95808. }
  95809. }
  95810. // Glow emissive only
  95811. if (this._emissiveTextureAndColor.texture) {
  95812. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95813. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95814. }
  95815. // Bones
  95816. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95817. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95818. }
  95819. // Morph targets
  95820. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95821. // Draw
  95822. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95823. }
  95824. else {
  95825. // Need to reset refresh rate of the shadowMap
  95826. this._mainTexture.resetRefreshCounter();
  95827. }
  95828. };
  95829. /**
  95830. * Rebuild the required buffers.
  95831. * @hidden Internal use only.
  95832. */
  95833. EffectLayer.prototype._rebuild = function () {
  95834. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95835. if (vb) {
  95836. vb._rebuild();
  95837. }
  95838. this._generateIndexBuffer();
  95839. };
  95840. /**
  95841. * Dispose only the render target textures and post process.
  95842. */
  95843. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95844. this._mainTexture.dispose();
  95845. for (var i = 0; i < this._postProcesses.length; i++) {
  95846. if (this._postProcesses[i]) {
  95847. this._postProcesses[i].dispose();
  95848. }
  95849. }
  95850. this._postProcesses = [];
  95851. for (var i = 0; i < this._textures.length; i++) {
  95852. if (this._textures[i]) {
  95853. this._textures[i].dispose();
  95854. }
  95855. }
  95856. this._textures = [];
  95857. };
  95858. /**
  95859. * Dispose the highlight layer and free resources.
  95860. */
  95861. EffectLayer.prototype.dispose = function () {
  95862. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95863. if (vertexBuffer) {
  95864. vertexBuffer.dispose();
  95865. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95866. }
  95867. if (this._indexBuffer) {
  95868. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95869. this._indexBuffer = null;
  95870. }
  95871. // Clean textures and post processes
  95872. this._disposeTextureAndPostProcesses();
  95873. // Remove from scene
  95874. var index = this._scene.effectLayers.indexOf(this, 0);
  95875. if (index > -1) {
  95876. this._scene.effectLayers.splice(index, 1);
  95877. }
  95878. // Callback
  95879. this.onDisposeObservable.notifyObservers(this);
  95880. this.onDisposeObservable.clear();
  95881. this.onBeforeRenderMainTextureObservable.clear();
  95882. this.onBeforeComposeObservable.clear();
  95883. this.onAfterComposeObservable.clear();
  95884. this.onSizeChangedObservable.clear();
  95885. };
  95886. /**
  95887. * Gets the class name of the effect layer
  95888. * @returns the string with the class name of the effect layer
  95889. */
  95890. EffectLayer.prototype.getClassName = function () {
  95891. return "EffectLayer";
  95892. };
  95893. /**
  95894. * Creates an effect layer from parsed effect layer data
  95895. * @param parsedEffectLayer defines effect layer data
  95896. * @param scene defines the current scene
  95897. * @param rootUrl defines the root URL containing the effect layer information
  95898. * @returns a parsed effect Layer
  95899. */
  95900. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95901. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95902. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95903. };
  95904. __decorate([
  95905. BABYLON.serialize()
  95906. ], EffectLayer.prototype, "name", void 0);
  95907. __decorate([
  95908. BABYLON.serializeAsColor4()
  95909. ], EffectLayer.prototype, "neutralColor", void 0);
  95910. __decorate([
  95911. BABYLON.serialize()
  95912. ], EffectLayer.prototype, "isEnabled", void 0);
  95913. __decorate([
  95914. BABYLON.serializeAsCameraReference()
  95915. ], EffectLayer.prototype, "camera", null);
  95916. return EffectLayer;
  95917. }());
  95918. BABYLON.EffectLayer = EffectLayer;
  95919. })(BABYLON || (BABYLON = {}));
  95920. //# sourceMappingURL=babylon.effectLayer.js.map
  95921. var BABYLON;
  95922. (function (BABYLON) {
  95923. /**
  95924. * Special Glow Blur post process only blurring the alpha channel
  95925. * It enforces keeping the most luminous color in the color channel.
  95926. */
  95927. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95928. __extends(GlowBlurPostProcess, _super);
  95929. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95931. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95932. _this.direction = direction;
  95933. _this.kernel = kernel;
  95934. _this.onApplyObservable.add(function (effect) {
  95935. effect.setFloat2("screenSize", _this.width, _this.height);
  95936. effect.setVector2("direction", _this.direction);
  95937. effect.setFloat("blurWidth", _this.kernel);
  95938. });
  95939. return _this;
  95940. }
  95941. return GlowBlurPostProcess;
  95942. }(BABYLON.PostProcess));
  95943. /**
  95944. * The highlight layer Helps adding a glow effect around a mesh.
  95945. *
  95946. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95947. * glowy meshes to your scene.
  95948. *
  95949. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95950. */
  95951. var HighlightLayer = /** @class */ (function (_super) {
  95952. __extends(HighlightLayer, _super);
  95953. /**
  95954. * Instantiates a new highlight Layer and references it to the scene..
  95955. * @param name The name of the layer
  95956. * @param scene The scene to use the layer in
  95957. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95958. */
  95959. function HighlightLayer(name, scene, options) {
  95960. var _this = _super.call(this, name, scene) || this;
  95961. _this.name = name;
  95962. /**
  95963. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95964. */
  95965. _this.innerGlow = true;
  95966. /**
  95967. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95968. */
  95969. _this.outerGlow = true;
  95970. /**
  95971. * An event triggered when the highlight layer is being blurred.
  95972. */
  95973. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95974. /**
  95975. * An event triggered when the highlight layer has been blurred.
  95976. */
  95977. _this.onAfterBlurObservable = new BABYLON.Observable();
  95978. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95979. _this._meshes = {};
  95980. _this._excludedMeshes = {};
  95981. _this.neutralColor = HighlightLayer.NeutralColor;
  95982. // Warn on stencil
  95983. if (!_this._engine.isStencilEnable) {
  95984. 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 }");
  95985. }
  95986. // Adapt options
  95987. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95988. // Initialize the layer
  95989. _this._init({
  95990. alphaBlendingMode: _this._options.alphaBlendingMode,
  95991. camera: _this._options.camera,
  95992. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95993. mainTextureRatio: _this._options.mainTextureRatio
  95994. });
  95995. // Do not render as long as no meshes have been added
  95996. _this._shouldRender = false;
  95997. return _this;
  95998. }
  95999. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96000. /**
  96001. * Gets the horizontal size of the blur.
  96002. */
  96003. get: function () {
  96004. return this._horizontalBlurPostprocess.kernel;
  96005. },
  96006. /**
  96007. * Specifies the horizontal size of the blur.
  96008. */
  96009. set: function (value) {
  96010. this._horizontalBlurPostprocess.kernel = value;
  96011. },
  96012. enumerable: true,
  96013. configurable: true
  96014. });
  96015. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96016. /**
  96017. * Gets the vertical size of the blur.
  96018. */
  96019. get: function () {
  96020. return this._verticalBlurPostprocess.kernel;
  96021. },
  96022. /**
  96023. * Specifies the vertical size of the blur.
  96024. */
  96025. set: function (value) {
  96026. this._verticalBlurPostprocess.kernel = value;
  96027. },
  96028. enumerable: true,
  96029. configurable: true
  96030. });
  96031. /**
  96032. * Get the effect name of the layer.
  96033. * @return The effect name
  96034. */
  96035. HighlightLayer.prototype.getEffectName = function () {
  96036. return HighlightLayer.EffectName;
  96037. };
  96038. /**
  96039. * Create the merge effect. This is the shader use to blit the information back
  96040. * to the main canvas at the end of the scene rendering.
  96041. */
  96042. HighlightLayer.prototype._createMergeEffect = function () {
  96043. // Effect
  96044. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96045. };
  96046. /**
  96047. * Creates the render target textures and post processes used in the highlight layer.
  96048. */
  96049. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96050. var _this = this;
  96051. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96052. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96053. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96054. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96055. var textureType = 0;
  96056. if (this._engine.getCaps().textureHalfFloatRender) {
  96057. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96058. }
  96059. else {
  96060. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96061. }
  96062. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96063. width: blurTextureWidth,
  96064. height: blurTextureHeight
  96065. }, this._scene, false, true, textureType);
  96066. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96067. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96068. this._blurTexture.anisotropicFilteringLevel = 16;
  96069. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96070. this._blurTexture.renderParticles = false;
  96071. this._blurTexture.ignoreCameraViewport = true;
  96072. this._textures = [this._blurTexture];
  96073. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96074. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96075. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96076. effect.setTexture("textureSampler", _this._mainTexture);
  96077. });
  96078. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96079. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96080. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96081. });
  96082. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96083. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96084. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96085. });
  96086. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96087. }
  96088. else {
  96089. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96090. width: blurTextureWidth,
  96091. height: blurTextureHeight
  96092. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96093. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96094. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96095. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96096. effect.setTexture("textureSampler", _this._mainTexture);
  96097. });
  96098. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96099. width: blurTextureWidth,
  96100. height: blurTextureHeight
  96101. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96102. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96103. }
  96104. this._mainTexture.onAfterUnbindObservable.add(function () {
  96105. _this.onBeforeBlurObservable.notifyObservers(_this);
  96106. var internalTexture = _this._blurTexture.getInternalTexture();
  96107. if (internalTexture) {
  96108. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96109. }
  96110. _this.onAfterBlurObservable.notifyObservers(_this);
  96111. });
  96112. // Prevent autoClear.
  96113. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96114. };
  96115. /**
  96116. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96117. */
  96118. HighlightLayer.prototype.needStencil = function () {
  96119. return true;
  96120. };
  96121. /**
  96122. * Checks for the readiness of the element composing the layer.
  96123. * @param subMesh the mesh to check for
  96124. * @param useInstances specify wether or not to use instances to render the mesh
  96125. * @param emissiveTexture the associated emissive texture used to generate the glow
  96126. * @return true if ready otherwise, false
  96127. */
  96128. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96129. var material = subMesh.getMaterial();
  96130. var mesh = subMesh.getRenderingMesh();
  96131. if (!material || !mesh || !this._meshes) {
  96132. return false;
  96133. }
  96134. var emissiveTexture = null;
  96135. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96136. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96137. emissiveTexture = material.emissiveTexture;
  96138. }
  96139. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96140. };
  96141. /**
  96142. * Implementation specific of rendering the generating effect on the main canvas.
  96143. * @param effect The effect used to render through
  96144. */
  96145. HighlightLayer.prototype._internalRender = function (effect) {
  96146. // Texture
  96147. effect.setTexture("textureSampler", this._blurTexture);
  96148. // Cache
  96149. var engine = this._engine;
  96150. var previousStencilBuffer = engine.getStencilBuffer();
  96151. var previousStencilFunction = engine.getStencilFunction();
  96152. var previousStencilMask = engine.getStencilMask();
  96153. var previousStencilOperationPass = engine.getStencilOperationPass();
  96154. var previousStencilOperationFail = engine.getStencilOperationFail();
  96155. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96156. var previousStencilReference = engine.getStencilFunctionReference();
  96157. // Stencil operations
  96158. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96159. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96160. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96161. // Draw order
  96162. engine.setStencilMask(0x00);
  96163. engine.setStencilBuffer(true);
  96164. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96165. // 2 passes inner outer
  96166. if (this.outerGlow) {
  96167. effect.setFloat("offset", 0);
  96168. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96170. }
  96171. if (this.innerGlow) {
  96172. effect.setFloat("offset", 1);
  96173. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96174. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96175. }
  96176. // Restore Cache
  96177. engine.setStencilFunction(previousStencilFunction);
  96178. engine.setStencilMask(previousStencilMask);
  96179. engine.setStencilBuffer(previousStencilBuffer);
  96180. engine.setStencilOperationPass(previousStencilOperationPass);
  96181. engine.setStencilOperationFail(previousStencilOperationFail);
  96182. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96183. engine.setStencilFunctionReference(previousStencilReference);
  96184. };
  96185. /**
  96186. * Returns true if the layer contains information to display, otherwise false.
  96187. */
  96188. HighlightLayer.prototype.shouldRender = function () {
  96189. if (_super.prototype.shouldRender.call(this)) {
  96190. return this._meshes ? true : false;
  96191. }
  96192. return false;
  96193. };
  96194. /**
  96195. * Returns true if the mesh should render, otherwise false.
  96196. * @param mesh The mesh to render
  96197. * @returns true if it should render otherwise false
  96198. */
  96199. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96200. // Excluded Mesh
  96201. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96202. return false;
  96203. }
  96204. ;
  96205. return true;
  96206. };
  96207. /**
  96208. * Sets the required values for both the emissive texture and and the main color.
  96209. */
  96210. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96211. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96212. if (highlightLayerMesh) {
  96213. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96214. }
  96215. else {
  96216. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96217. }
  96218. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96219. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96220. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96221. }
  96222. else {
  96223. this._emissiveTextureAndColor.texture = null;
  96224. }
  96225. };
  96226. /**
  96227. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96228. * @param mesh The mesh to exclude from the highlight layer
  96229. */
  96230. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96231. if (!this._excludedMeshes) {
  96232. return;
  96233. }
  96234. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96235. if (!meshExcluded) {
  96236. this._excludedMeshes[mesh.uniqueId] = {
  96237. mesh: mesh,
  96238. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96239. mesh.getEngine().setStencilBuffer(false);
  96240. }),
  96241. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96242. mesh.getEngine().setStencilBuffer(true);
  96243. }),
  96244. };
  96245. }
  96246. };
  96247. /**
  96248. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96249. * @param mesh The mesh to highlight
  96250. */
  96251. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96252. if (!this._excludedMeshes) {
  96253. return;
  96254. }
  96255. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96256. if (meshExcluded) {
  96257. if (meshExcluded.beforeRender) {
  96258. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96259. }
  96260. if (meshExcluded.afterRender) {
  96261. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96262. }
  96263. }
  96264. this._excludedMeshes[mesh.uniqueId] = null;
  96265. };
  96266. /**
  96267. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96268. * @param mesh mesh to test
  96269. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96270. */
  96271. HighlightLayer.prototype.hasMesh = function (mesh) {
  96272. if (!this._meshes) {
  96273. return false;
  96274. }
  96275. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96276. };
  96277. /**
  96278. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96279. * @param mesh The mesh to highlight
  96280. * @param color The color of the highlight
  96281. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96282. */
  96283. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96284. var _this = this;
  96285. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96286. if (!this._meshes) {
  96287. return;
  96288. }
  96289. var meshHighlight = this._meshes[mesh.uniqueId];
  96290. if (meshHighlight) {
  96291. meshHighlight.color = color;
  96292. }
  96293. else {
  96294. this._meshes[mesh.uniqueId] = {
  96295. mesh: mesh,
  96296. color: color,
  96297. // Lambda required for capture due to Observable this context
  96298. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96299. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96300. _this._defaultStencilReference(mesh);
  96301. }
  96302. else {
  96303. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96304. }
  96305. }),
  96306. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96307. glowEmissiveOnly: glowEmissiveOnly
  96308. };
  96309. }
  96310. this._shouldRender = true;
  96311. };
  96312. /**
  96313. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96314. * @param mesh The mesh to highlight
  96315. */
  96316. HighlightLayer.prototype.removeMesh = function (mesh) {
  96317. if (!this._meshes) {
  96318. return;
  96319. }
  96320. var meshHighlight = this._meshes[mesh.uniqueId];
  96321. if (meshHighlight) {
  96322. if (meshHighlight.observerHighlight) {
  96323. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96324. }
  96325. if (meshHighlight.observerDefault) {
  96326. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96327. }
  96328. delete this._meshes[mesh.uniqueId];
  96329. }
  96330. this._shouldRender = false;
  96331. for (var meshHighlightToCheck in this._meshes) {
  96332. if (this._meshes[meshHighlightToCheck]) {
  96333. this._shouldRender = true;
  96334. break;
  96335. }
  96336. }
  96337. };
  96338. /**
  96339. * Force the stencil to the normal expected value for none glowing parts
  96340. */
  96341. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96342. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96343. };
  96344. /**
  96345. * Free any resources and references associated to a mesh.
  96346. * Internal use
  96347. * @param mesh The mesh to free.
  96348. */
  96349. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96350. this.removeMesh(mesh);
  96351. this.removeExcludedMesh(mesh);
  96352. };
  96353. /**
  96354. * Dispose the highlight layer and free resources.
  96355. */
  96356. HighlightLayer.prototype.dispose = function () {
  96357. if (this._meshes) {
  96358. // Clean mesh references
  96359. for (var id in this._meshes) {
  96360. var meshHighlight = this._meshes[id];
  96361. if (meshHighlight && meshHighlight.mesh) {
  96362. if (meshHighlight.observerHighlight) {
  96363. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96364. }
  96365. if (meshHighlight.observerDefault) {
  96366. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96367. }
  96368. }
  96369. }
  96370. this._meshes = null;
  96371. }
  96372. if (this._excludedMeshes) {
  96373. for (var id in this._excludedMeshes) {
  96374. var meshHighlight = this._excludedMeshes[id];
  96375. if (meshHighlight) {
  96376. if (meshHighlight.beforeRender) {
  96377. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96378. }
  96379. if (meshHighlight.afterRender) {
  96380. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96381. }
  96382. }
  96383. }
  96384. this._excludedMeshes = null;
  96385. }
  96386. _super.prototype.dispose.call(this);
  96387. };
  96388. /**
  96389. * Gets the class name of the effect layer
  96390. * @returns the string with the class name of the effect layer
  96391. */
  96392. HighlightLayer.prototype.getClassName = function () {
  96393. return "HighlightLayer";
  96394. };
  96395. /**
  96396. * Serializes this Highlight layer
  96397. * @returns a serialized Highlight layer object
  96398. */
  96399. HighlightLayer.prototype.serialize = function () {
  96400. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96401. serializationObject.customType = "BABYLON.HighlightLayer";
  96402. // Highlighted meshes
  96403. serializationObject.meshes = [];
  96404. if (this._meshes) {
  96405. for (var m in this._meshes) {
  96406. var mesh = this._meshes[m];
  96407. if (mesh) {
  96408. serializationObject.meshes.push({
  96409. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96410. color: mesh.color.asArray(),
  96411. meshId: mesh.mesh.id
  96412. });
  96413. }
  96414. }
  96415. }
  96416. // Excluded meshes
  96417. serializationObject.excludedMeshes = [];
  96418. if (this._excludedMeshes) {
  96419. for (var e in this._excludedMeshes) {
  96420. var excludedMesh = this._excludedMeshes[e];
  96421. if (excludedMesh) {
  96422. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96423. }
  96424. }
  96425. }
  96426. return serializationObject;
  96427. };
  96428. /**
  96429. * Creates a Highlight layer from parsed Highlight layer data
  96430. * @param parsedHightlightLayer defines the Highlight layer data
  96431. * @param scene defines the current scene
  96432. * @param rootUrl defines the root URL containing the Highlight layer information
  96433. * @returns a parsed Highlight layer
  96434. */
  96435. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96436. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96437. var index;
  96438. // Excluded meshes
  96439. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96440. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96441. if (mesh) {
  96442. hl.addExcludedMesh(mesh);
  96443. }
  96444. }
  96445. // Included meshes
  96446. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96447. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96448. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96449. if (mesh) {
  96450. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96451. }
  96452. }
  96453. return hl;
  96454. };
  96455. /**
  96456. * Effect Name of the highlight layer.
  96457. */
  96458. HighlightLayer.EffectName = "HighlightLayer";
  96459. /**
  96460. * The neutral color used during the preparation of the glow effect.
  96461. * This is black by default as the blend operation is a blend operation.
  96462. */
  96463. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96464. /**
  96465. * Stencil value used for glowing meshes.
  96466. */
  96467. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96468. /**
  96469. * Stencil value used for the other meshes in the scene.
  96470. */
  96471. HighlightLayer.NormalMeshStencilReference = 0x01;
  96472. __decorate([
  96473. BABYLON.serialize()
  96474. ], HighlightLayer.prototype, "innerGlow", void 0);
  96475. __decorate([
  96476. BABYLON.serialize()
  96477. ], HighlightLayer.prototype, "outerGlow", void 0);
  96478. __decorate([
  96479. BABYLON.serialize()
  96480. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96481. __decorate([
  96482. BABYLON.serialize()
  96483. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96484. __decorate([
  96485. BABYLON.serialize("options")
  96486. ], HighlightLayer.prototype, "_options", void 0);
  96487. return HighlightLayer;
  96488. }(BABYLON.EffectLayer));
  96489. BABYLON.HighlightLayer = HighlightLayer;
  96490. })(BABYLON || (BABYLON = {}));
  96491. //# sourceMappingURL=babylon.highlightLayer.js.map
  96492. var BABYLON;
  96493. (function (BABYLON) {
  96494. /**
  96495. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96496. *
  96497. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96498. * glowy meshes to your scene.
  96499. *
  96500. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96501. */
  96502. var GlowLayer = /** @class */ (function (_super) {
  96503. __extends(GlowLayer, _super);
  96504. /**
  96505. * Instantiates a new glow Layer and references it to the scene.
  96506. * @param name The name of the layer
  96507. * @param scene The scene to use the layer in
  96508. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96509. */
  96510. function GlowLayer(name, scene, options) {
  96511. var _this = _super.call(this, name, scene) || this;
  96512. _this._intensity = 1.0;
  96513. _this._includedOnlyMeshes = [];
  96514. _this._excludedMeshes = [];
  96515. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96516. // Adapt options
  96517. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96518. // Initialize the layer
  96519. _this._init({
  96520. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96521. camera: _this._options.camera,
  96522. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96523. mainTextureRatio: _this._options.mainTextureRatio
  96524. });
  96525. return _this;
  96526. }
  96527. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96528. /**
  96529. * Gets the kernel size of the blur.
  96530. */
  96531. get: function () {
  96532. return this._horizontalBlurPostprocess1.kernel;
  96533. },
  96534. /**
  96535. * Sets the kernel size of the blur.
  96536. */
  96537. set: function (value) {
  96538. this._horizontalBlurPostprocess1.kernel = value;
  96539. this._verticalBlurPostprocess1.kernel = value;
  96540. this._horizontalBlurPostprocess2.kernel = value;
  96541. this._verticalBlurPostprocess2.kernel = value;
  96542. },
  96543. enumerable: true,
  96544. configurable: true
  96545. });
  96546. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96547. /**
  96548. * Gets the glow intensity.
  96549. */
  96550. get: function () {
  96551. return this._intensity;
  96552. },
  96553. /**
  96554. * Sets the glow intensity.
  96555. */
  96556. set: function (value) {
  96557. this._intensity = value;
  96558. },
  96559. enumerable: true,
  96560. configurable: true
  96561. });
  96562. /**
  96563. * Get the effect name of the layer.
  96564. * @return The effect name
  96565. */
  96566. GlowLayer.prototype.getEffectName = function () {
  96567. return GlowLayer.EffectName;
  96568. };
  96569. /**
  96570. * Create the merge effect. This is the shader use to blit the information back
  96571. * to the main canvas at the end of the scene rendering.
  96572. */
  96573. GlowLayer.prototype._createMergeEffect = function () {
  96574. // Effect
  96575. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96576. };
  96577. /**
  96578. * Creates the render target textures and post processes used in the glow layer.
  96579. */
  96580. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96581. var _this = this;
  96582. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96583. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96584. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96585. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96586. var textureType = 0;
  96587. if (this._engine.getCaps().textureHalfFloatRender) {
  96588. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96589. }
  96590. else {
  96591. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96592. }
  96593. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96594. width: blurTextureWidth,
  96595. height: blurTextureHeight
  96596. }, this._scene, false, true, textureType);
  96597. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96598. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96599. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96600. this._blurTexture1.renderParticles = false;
  96601. this._blurTexture1.ignoreCameraViewport = true;
  96602. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96603. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96604. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96605. width: blurTextureWidth2,
  96606. height: blurTextureHeight2
  96607. }, this._scene, false, true, textureType);
  96608. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96609. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96610. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96611. this._blurTexture2.renderParticles = false;
  96612. this._blurTexture2.ignoreCameraViewport = true;
  96613. this._textures = [this._blurTexture1, this._blurTexture2];
  96614. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96615. width: blurTextureWidth,
  96616. height: blurTextureHeight
  96617. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96618. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96619. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96620. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96621. effect.setTexture("textureSampler", _this._mainTexture);
  96622. });
  96623. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96624. width: blurTextureWidth,
  96625. height: blurTextureHeight
  96626. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96627. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96628. width: blurTextureWidth2,
  96629. height: blurTextureHeight2
  96630. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96631. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96632. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96633. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96634. effect.setTexture("textureSampler", _this._blurTexture1);
  96635. });
  96636. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96637. width: blurTextureWidth2,
  96638. height: blurTextureHeight2
  96639. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96640. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96641. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96642. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96643. this._mainTexture.samples = this._options.mainTextureSamples;
  96644. this._mainTexture.onAfterUnbindObservable.add(function () {
  96645. var internalTexture = _this._blurTexture1.getInternalTexture();
  96646. if (internalTexture) {
  96647. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96648. internalTexture = _this._blurTexture2.getInternalTexture();
  96649. if (internalTexture) {
  96650. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96651. }
  96652. }
  96653. });
  96654. // Prevent autoClear.
  96655. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96656. };
  96657. /**
  96658. * Checks for the readiness of the element composing the layer.
  96659. * @param subMesh the mesh to check for
  96660. * @param useInstances specify wether or not to use instances to render the mesh
  96661. * @param emissiveTexture the associated emissive texture used to generate the glow
  96662. * @return true if ready otherwise, false
  96663. */
  96664. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96665. var material = subMesh.getMaterial();
  96666. var mesh = subMesh.getRenderingMesh();
  96667. if (!material || !mesh) {
  96668. return false;
  96669. }
  96670. var emissiveTexture = material.emissiveTexture;
  96671. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96672. };
  96673. /**
  96674. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96675. */
  96676. GlowLayer.prototype.needStencil = function () {
  96677. return false;
  96678. };
  96679. /**
  96680. * Implementation specific of rendering the generating effect on the main canvas.
  96681. * @param effect The effect used to render through
  96682. */
  96683. GlowLayer.prototype._internalRender = function (effect) {
  96684. // Texture
  96685. effect.setTexture("textureSampler", this._blurTexture1);
  96686. effect.setTexture("textureSampler2", this._blurTexture2);
  96687. effect.setFloat("offset", this._intensity);
  96688. // Cache
  96689. var engine = this._engine;
  96690. var previousStencilBuffer = engine.getStencilBuffer();
  96691. // Draw order
  96692. engine.setStencilBuffer(false);
  96693. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96694. // Draw order
  96695. engine.setStencilBuffer(previousStencilBuffer);
  96696. };
  96697. /**
  96698. * Sets the required values for both the emissive texture and and the main color.
  96699. */
  96700. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96701. var textureLevel = 1.0;
  96702. if (this.customEmissiveTextureSelector) {
  96703. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96704. }
  96705. else {
  96706. if (material) {
  96707. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96708. if (this._emissiveTextureAndColor.texture) {
  96709. textureLevel = this._emissiveTextureAndColor.texture.level;
  96710. }
  96711. }
  96712. else {
  96713. this._emissiveTextureAndColor.texture = null;
  96714. }
  96715. }
  96716. if (this.customEmissiveColorSelector) {
  96717. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96718. }
  96719. else {
  96720. if (material.emissiveColor) {
  96721. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96722. }
  96723. else {
  96724. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96725. }
  96726. }
  96727. };
  96728. /**
  96729. * Returns true if the mesh should render, otherwise false.
  96730. * @param mesh The mesh to render
  96731. * @returns true if it should render otherwise false
  96732. */
  96733. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96734. return this.hasMesh(mesh);
  96735. };
  96736. /**
  96737. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96738. * @param mesh The mesh to exclude from the glow layer
  96739. */
  96740. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96741. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96742. this._excludedMeshes.push(mesh.uniqueId);
  96743. }
  96744. };
  96745. /**
  96746. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96747. * @param mesh The mesh to remove
  96748. */
  96749. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96750. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96751. if (index !== -1) {
  96752. this._excludedMeshes.splice(index, 1);
  96753. }
  96754. };
  96755. /**
  96756. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96757. * @param mesh The mesh to include in the glow layer
  96758. */
  96759. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96760. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96761. this._includedOnlyMeshes.push(mesh.uniqueId);
  96762. }
  96763. };
  96764. /**
  96765. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96766. * @param mesh The mesh to remove
  96767. */
  96768. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96769. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96770. if (index !== -1) {
  96771. this._includedOnlyMeshes.splice(index, 1);
  96772. }
  96773. };
  96774. /**
  96775. * Determine if a given mesh will be used in the glow layer
  96776. * @param mesh The mesh to test
  96777. * @returns true if the mesh will be highlighted by the current glow layer
  96778. */
  96779. GlowLayer.prototype.hasMesh = function (mesh) {
  96780. // Included Mesh
  96781. if (this._includedOnlyMeshes.length) {
  96782. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96783. }
  96784. ;
  96785. // Excluded Mesh
  96786. if (this._excludedMeshes.length) {
  96787. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96788. }
  96789. ;
  96790. return true;
  96791. };
  96792. /**
  96793. * Free any resources and references associated to a mesh.
  96794. * Internal use
  96795. * @param mesh The mesh to free.
  96796. */
  96797. GlowLayer.prototype._disposeMesh = function (mesh) {
  96798. this.removeIncludedOnlyMesh(mesh);
  96799. this.removeExcludedMesh(mesh);
  96800. };
  96801. /**
  96802. * Gets the class name of the effect layer
  96803. * @returns the string with the class name of the effect layer
  96804. */
  96805. GlowLayer.prototype.getClassName = function () {
  96806. return "GlowLayer";
  96807. };
  96808. /**
  96809. * Serializes this glow layer
  96810. * @returns a serialized glow layer object
  96811. */
  96812. GlowLayer.prototype.serialize = function () {
  96813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96814. serializationObject.customType = "BABYLON.GlowLayer";
  96815. var index;
  96816. // Included meshes
  96817. serializationObject.includedMeshes = [];
  96818. if (this._includedOnlyMeshes.length) {
  96819. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96820. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96821. if (mesh) {
  96822. serializationObject.includedMeshes.push(mesh.id);
  96823. }
  96824. }
  96825. }
  96826. // Excluded meshes
  96827. serializationObject.excludedMeshes = [];
  96828. if (this._excludedMeshes.length) {
  96829. for (index = 0; index < this._excludedMeshes.length; index++) {
  96830. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96831. if (mesh) {
  96832. serializationObject.excludedMeshes.push(mesh.id);
  96833. }
  96834. }
  96835. }
  96836. return serializationObject;
  96837. };
  96838. /**
  96839. * Creates a Glow Layer from parsed glow layer data
  96840. * @param parsedGlowLayer defines glow layer data
  96841. * @param scene defines the current scene
  96842. * @param rootUrl defines the root URL containing the glow layer information
  96843. * @returns a parsed Glow Layer
  96844. */
  96845. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96846. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96847. var index;
  96848. // Excluded meshes
  96849. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96850. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96851. if (mesh) {
  96852. gl.addExcludedMesh(mesh);
  96853. }
  96854. }
  96855. // Included meshes
  96856. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96857. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96858. if (mesh) {
  96859. gl.addIncludedOnlyMesh(mesh);
  96860. }
  96861. }
  96862. return gl;
  96863. };
  96864. /**
  96865. * Effect Name of the layer.
  96866. */
  96867. GlowLayer.EffectName = "GlowLayer";
  96868. /**
  96869. * The default blur kernel size used for the glow.
  96870. */
  96871. GlowLayer.DefaultBlurKernelSize = 32;
  96872. /**
  96873. * The default texture size ratio used for the glow.
  96874. */
  96875. GlowLayer.DefaultTextureRatio = 0.5;
  96876. __decorate([
  96877. BABYLON.serialize()
  96878. ], GlowLayer.prototype, "blurKernelSize", null);
  96879. __decorate([
  96880. BABYLON.serialize()
  96881. ], GlowLayer.prototype, "intensity", null);
  96882. __decorate([
  96883. BABYLON.serialize("options")
  96884. ], GlowLayer.prototype, "_options", void 0);
  96885. return GlowLayer;
  96886. }(BABYLON.EffectLayer));
  96887. BABYLON.GlowLayer = GlowLayer;
  96888. })(BABYLON || (BABYLON = {}));
  96889. //# sourceMappingURL=babylon.glowLayer.js.map
  96890. var BABYLON;
  96891. (function (BABYLON) {
  96892. /**
  96893. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96894. */
  96895. var AssetTaskState;
  96896. (function (AssetTaskState) {
  96897. /**
  96898. * Initialization
  96899. */
  96900. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96901. /**
  96902. * Running
  96903. */
  96904. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96905. /**
  96906. * Done
  96907. */
  96908. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96909. /**
  96910. * Error
  96911. */
  96912. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96913. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96914. /**
  96915. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96916. */
  96917. var AbstractAssetTask = /** @class */ (function () {
  96918. /**
  96919. * Creates a new {BABYLON.AssetsManager}
  96920. * @param name defines the name of the task
  96921. */
  96922. function AbstractAssetTask(
  96923. /**
  96924. * Task name
  96925. */ name) {
  96926. this.name = name;
  96927. this._isCompleted = false;
  96928. this._taskState = AssetTaskState.INIT;
  96929. }
  96930. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96931. /**
  96932. * Get if the task is completed
  96933. */
  96934. get: function () {
  96935. return this._isCompleted;
  96936. },
  96937. enumerable: true,
  96938. configurable: true
  96939. });
  96940. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96941. /**
  96942. * Gets the current state of the task
  96943. */
  96944. get: function () {
  96945. return this._taskState;
  96946. },
  96947. enumerable: true,
  96948. configurable: true
  96949. });
  96950. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96951. /**
  96952. * Gets the current error object (if task is in error)
  96953. */
  96954. get: function () {
  96955. return this._errorObject;
  96956. },
  96957. enumerable: true,
  96958. configurable: true
  96959. });
  96960. /**
  96961. * Internal only
  96962. * @hidden
  96963. */
  96964. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96965. if (this._errorObject) {
  96966. return;
  96967. }
  96968. this._errorObject = {
  96969. message: message,
  96970. exception: exception
  96971. };
  96972. };
  96973. /**
  96974. * Execute the current task
  96975. * @param scene defines the scene where you want your assets to be loaded
  96976. * @param onSuccess is a callback called when the task is successfully executed
  96977. * @param onError is a callback called if an error occurs
  96978. */
  96979. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96980. var _this = this;
  96981. this._taskState = AssetTaskState.RUNNING;
  96982. this.runTask(scene, function () {
  96983. _this.onDoneCallback(onSuccess, onError);
  96984. }, function (msg, exception) {
  96985. _this.onErrorCallback(onError, msg, exception);
  96986. });
  96987. };
  96988. /**
  96989. * Execute the current task
  96990. * @param scene defines the scene where you want your assets to be loaded
  96991. * @param onSuccess is a callback called when the task is successfully executed
  96992. * @param onError is a callback called if an error occurs
  96993. */
  96994. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96995. throw new Error("runTask is not implemented");
  96996. };
  96997. /**
  96998. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96999. * This can be used with failed tasks that have the reason for failure fixed.
  97000. */
  97001. AbstractAssetTask.prototype.reset = function () {
  97002. this._taskState = AssetTaskState.INIT;
  97003. };
  97004. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97005. this._taskState = AssetTaskState.ERROR;
  97006. this._errorObject = {
  97007. message: message,
  97008. exception: exception
  97009. };
  97010. if (this.onError) {
  97011. this.onError(this, message, exception);
  97012. }
  97013. onError();
  97014. };
  97015. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97016. try {
  97017. this._taskState = AssetTaskState.DONE;
  97018. this._isCompleted = true;
  97019. if (this.onSuccess) {
  97020. this.onSuccess(this);
  97021. }
  97022. onSuccess();
  97023. }
  97024. catch (e) {
  97025. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97026. }
  97027. };
  97028. return AbstractAssetTask;
  97029. }());
  97030. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97031. /**
  97032. * Class used to share progress information about assets loading
  97033. */
  97034. var AssetsProgressEvent = /** @class */ (function () {
  97035. /**
  97036. * Creates a {BABYLON.AssetsProgressEvent}
  97037. * @param remainingCount defines the number of remaining tasks to process
  97038. * @param totalCount defines the total number of tasks
  97039. * @param task defines the task that was just processed
  97040. */
  97041. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97042. this.remainingCount = remainingCount;
  97043. this.totalCount = totalCount;
  97044. this.task = task;
  97045. }
  97046. return AssetsProgressEvent;
  97047. }());
  97048. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97049. /**
  97050. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97051. */
  97052. var MeshAssetTask = /** @class */ (function (_super) {
  97053. __extends(MeshAssetTask, _super);
  97054. /**
  97055. * Creates a new {BABYLON.MeshAssetTask}
  97056. * @param name defines the name of the task
  97057. * @param meshesNames defines the list of mesh's names you want to load
  97058. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97059. * @param sceneFilename defines the filename of the scene to load from
  97060. */
  97061. function MeshAssetTask(
  97062. /**
  97063. * Defines the name of the task
  97064. */
  97065. name,
  97066. /**
  97067. * Defines the list of mesh's names you want to load
  97068. */
  97069. meshesNames,
  97070. /**
  97071. * Defines the root url to use as a base to load your meshes and associated resources
  97072. */
  97073. rootUrl,
  97074. /**
  97075. * Defines the filename of the scene to load from
  97076. */
  97077. sceneFilename) {
  97078. var _this = _super.call(this, name) || this;
  97079. _this.name = name;
  97080. _this.meshesNames = meshesNames;
  97081. _this.rootUrl = rootUrl;
  97082. _this.sceneFilename = sceneFilename;
  97083. return _this;
  97084. }
  97085. /**
  97086. * Execute the current task
  97087. * @param scene defines the scene where you want your assets to be loaded
  97088. * @param onSuccess is a callback called when the task is successfully executed
  97089. * @param onError is a callback called if an error occurs
  97090. */
  97091. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97092. var _this = this;
  97093. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97094. _this.loadedMeshes = meshes;
  97095. _this.loadedParticleSystems = particleSystems;
  97096. _this.loadedSkeletons = skeletons;
  97097. onSuccess();
  97098. }, null, function (scene, message, exception) {
  97099. onError(message, exception);
  97100. });
  97101. };
  97102. return MeshAssetTask;
  97103. }(AbstractAssetTask));
  97104. BABYLON.MeshAssetTask = MeshAssetTask;
  97105. /**
  97106. * Define a task used by {BABYLON.AssetsManager} to load text content
  97107. */
  97108. var TextFileAssetTask = /** @class */ (function (_super) {
  97109. __extends(TextFileAssetTask, _super);
  97110. /**
  97111. * Creates a new TextFileAssetTask object
  97112. * @param name defines the name of the task
  97113. * @param url defines the location of the file to load
  97114. */
  97115. function TextFileAssetTask(
  97116. /**
  97117. * Defines the name of the task
  97118. */
  97119. name,
  97120. /**
  97121. * Defines the location of the file to load
  97122. */
  97123. url) {
  97124. var _this = _super.call(this, name) || this;
  97125. _this.name = name;
  97126. _this.url = url;
  97127. return _this;
  97128. }
  97129. /**
  97130. * Execute the current task
  97131. * @param scene defines the scene where you want your assets to be loaded
  97132. * @param onSuccess is a callback called when the task is successfully executed
  97133. * @param onError is a callback called if an error occurs
  97134. */
  97135. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97136. var _this = this;
  97137. scene._loadFile(this.url, function (data) {
  97138. _this.text = data;
  97139. onSuccess();
  97140. }, undefined, false, false, function (request, exception) {
  97141. if (request) {
  97142. onError(request.status + " " + request.statusText, exception);
  97143. }
  97144. });
  97145. };
  97146. return TextFileAssetTask;
  97147. }(AbstractAssetTask));
  97148. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97149. /**
  97150. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97151. */
  97152. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97153. __extends(BinaryFileAssetTask, _super);
  97154. /**
  97155. * Creates a new BinaryFileAssetTask object
  97156. * @param name defines the name of the new task
  97157. * @param url defines the location of the file to load
  97158. */
  97159. function BinaryFileAssetTask(
  97160. /**
  97161. * Defines the name of the task
  97162. */
  97163. name,
  97164. /**
  97165. * Defines the location of the file to load
  97166. */
  97167. url) {
  97168. var _this = _super.call(this, name) || this;
  97169. _this.name = name;
  97170. _this.url = url;
  97171. return _this;
  97172. }
  97173. /**
  97174. * Execute the current task
  97175. * @param scene defines the scene where you want your assets to be loaded
  97176. * @param onSuccess is a callback called when the task is successfully executed
  97177. * @param onError is a callback called if an error occurs
  97178. */
  97179. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97180. var _this = this;
  97181. scene._loadFile(this.url, function (data) {
  97182. _this.data = data;
  97183. onSuccess();
  97184. }, undefined, true, true, function (request, exception) {
  97185. if (request) {
  97186. onError(request.status + " " + request.statusText, exception);
  97187. }
  97188. });
  97189. };
  97190. return BinaryFileAssetTask;
  97191. }(AbstractAssetTask));
  97192. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97193. /**
  97194. * Define a task used by {BABYLON.AssetsManager} to load images
  97195. */
  97196. var ImageAssetTask = /** @class */ (function (_super) {
  97197. __extends(ImageAssetTask, _super);
  97198. /**
  97199. * Creates a new ImageAssetTask
  97200. * @param name defines the name of the task
  97201. * @param url defines the location of the image to load
  97202. */
  97203. function ImageAssetTask(
  97204. /**
  97205. * Defines the name of the task
  97206. */
  97207. name,
  97208. /**
  97209. * Defines the location of the image to load
  97210. */
  97211. url) {
  97212. var _this = _super.call(this, name) || this;
  97213. _this.name = name;
  97214. _this.url = url;
  97215. return _this;
  97216. }
  97217. /**
  97218. * Execute the current task
  97219. * @param scene defines the scene where you want your assets to be loaded
  97220. * @param onSuccess is a callback called when the task is successfully executed
  97221. * @param onError is a callback called if an error occurs
  97222. */
  97223. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97224. var _this = this;
  97225. var img = new Image();
  97226. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97227. img.onload = function () {
  97228. _this.image = img;
  97229. onSuccess();
  97230. };
  97231. img.onerror = function (err) {
  97232. onError("Error loading image", err);
  97233. };
  97234. img.src = this.url;
  97235. };
  97236. return ImageAssetTask;
  97237. }(AbstractAssetTask));
  97238. BABYLON.ImageAssetTask = ImageAssetTask;
  97239. /**
  97240. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97241. */
  97242. var TextureAssetTask = /** @class */ (function (_super) {
  97243. __extends(TextureAssetTask, _super);
  97244. /**
  97245. * Creates a new TextureAssetTask object
  97246. * @param name defines the name of the task
  97247. * @param url defines the location of the file to load
  97248. * @param noMipmap defines if mipmap should not be generated (default is false)
  97249. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97250. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97251. */
  97252. function TextureAssetTask(
  97253. /**
  97254. * Defines the name of the task
  97255. */
  97256. name,
  97257. /**
  97258. * Defines the location of the file to load
  97259. */
  97260. url,
  97261. /**
  97262. * Defines if mipmap should not be generated (default is false)
  97263. */
  97264. noMipmap,
  97265. /**
  97266. * Defines if texture must be inverted on Y axis (default is false)
  97267. */
  97268. invertY,
  97269. /**
  97270. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97271. */
  97272. samplingMode) {
  97273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97274. var _this = _super.call(this, name) || this;
  97275. _this.name = name;
  97276. _this.url = url;
  97277. _this.noMipmap = noMipmap;
  97278. _this.invertY = invertY;
  97279. _this.samplingMode = samplingMode;
  97280. return _this;
  97281. }
  97282. /**
  97283. * Execute the current task
  97284. * @param scene defines the scene where you want your assets to be loaded
  97285. * @param onSuccess is a callback called when the task is successfully executed
  97286. * @param onError is a callback called if an error occurs
  97287. */
  97288. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97289. var onload = function () {
  97290. onSuccess();
  97291. };
  97292. var onerror = function (message, exception) {
  97293. onError(message, exception);
  97294. };
  97295. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97296. };
  97297. return TextureAssetTask;
  97298. }(AbstractAssetTask));
  97299. BABYLON.TextureAssetTask = TextureAssetTask;
  97300. /**
  97301. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97302. */
  97303. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97304. __extends(CubeTextureAssetTask, _super);
  97305. /**
  97306. * Creates a new CubeTextureAssetTask
  97307. * @param name defines the name of the task
  97308. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97309. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97310. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97311. * @param files defines the explicit list of files (undefined by default)
  97312. */
  97313. function CubeTextureAssetTask(
  97314. /**
  97315. * Defines the name of the task
  97316. */
  97317. name,
  97318. /**
  97319. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97320. */
  97321. url,
  97322. /**
  97323. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97324. */
  97325. extensions,
  97326. /**
  97327. * Defines if mipmaps should not be generated (default is false)
  97328. */
  97329. noMipmap,
  97330. /**
  97331. * Defines the explicit list of files (undefined by default)
  97332. */
  97333. files) {
  97334. var _this = _super.call(this, name) || this;
  97335. _this.name = name;
  97336. _this.url = url;
  97337. _this.extensions = extensions;
  97338. _this.noMipmap = noMipmap;
  97339. _this.files = files;
  97340. return _this;
  97341. }
  97342. /**
  97343. * Execute the current task
  97344. * @param scene defines the scene where you want your assets to be loaded
  97345. * @param onSuccess is a callback called when the task is successfully executed
  97346. * @param onError is a callback called if an error occurs
  97347. */
  97348. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97349. var onload = function () {
  97350. onSuccess();
  97351. };
  97352. var onerror = function (message, exception) {
  97353. onError(message, exception);
  97354. };
  97355. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97356. };
  97357. return CubeTextureAssetTask;
  97358. }(AbstractAssetTask));
  97359. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97360. /**
  97361. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97362. */
  97363. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97364. __extends(HDRCubeTextureAssetTask, _super);
  97365. /**
  97366. * Creates a new HDRCubeTextureAssetTask object
  97367. * @param name defines the name of the task
  97368. * @param url defines the location of the file to load
  97369. * @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.
  97370. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97371. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97372. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  97373. * @param reserved Internal use only
  97374. */
  97375. function HDRCubeTextureAssetTask(
  97376. /**
  97377. * Defines the name of the task
  97378. */
  97379. name,
  97380. /**
  97381. * Defines the location of the file to load
  97382. */
  97383. url,
  97384. /**
  97385. * Defines the desired size (the more it increases the longer the generation will be)
  97386. */
  97387. size,
  97388. /**
  97389. * Defines if mipmaps should not be generated (default is false)
  97390. */
  97391. noMipmap,
  97392. /**
  97393. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97394. */
  97395. generateHarmonics,
  97396. /**
  97397. * 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)
  97398. */
  97399. gammaSpace,
  97400. /**
  97401. * Internal Use Only
  97402. */
  97403. reserved) {
  97404. if (noMipmap === void 0) { noMipmap = false; }
  97405. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97406. if (gammaSpace === void 0) { gammaSpace = false; }
  97407. if (reserved === void 0) { reserved = false; }
  97408. var _this = _super.call(this, name) || this;
  97409. _this.name = name;
  97410. _this.url = url;
  97411. _this.size = size;
  97412. _this.noMipmap = noMipmap;
  97413. _this.generateHarmonics = generateHarmonics;
  97414. _this.gammaSpace = gammaSpace;
  97415. _this.reserved = reserved;
  97416. return _this;
  97417. }
  97418. /**
  97419. * Execute the current task
  97420. * @param scene defines the scene where you want your assets to be loaded
  97421. * @param onSuccess is a callback called when the task is successfully executed
  97422. * @param onError is a callback called if an error occurs
  97423. */
  97424. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97425. var onload = function () {
  97426. onSuccess();
  97427. };
  97428. var onerror = function (message, exception) {
  97429. onError(message, exception);
  97430. };
  97431. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97432. };
  97433. return HDRCubeTextureAssetTask;
  97434. }(AbstractAssetTask));
  97435. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97436. /**
  97437. * This class can be used to easily import assets into a scene
  97438. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97439. */
  97440. var AssetsManager = /** @class */ (function () {
  97441. /**
  97442. * Creates a new AssetsManager
  97443. * @param scene defines the scene to work on
  97444. */
  97445. function AssetsManager(scene) {
  97446. this._isLoading = false;
  97447. this._tasks = new Array();
  97448. this._waitingTasksCount = 0;
  97449. this._totalTasksCount = 0;
  97450. /**
  97451. * Observable called when all tasks are processed
  97452. */
  97453. this.onTaskSuccessObservable = new BABYLON.Observable();
  97454. /**
  97455. * Observable called when a task had an error
  97456. */
  97457. this.onTaskErrorObservable = new BABYLON.Observable();
  97458. /**
  97459. * Observable called when a task is successful
  97460. */
  97461. this.onTasksDoneObservable = new BABYLON.Observable();
  97462. /**
  97463. * Observable called when a task is done (whatever the result is)
  97464. */
  97465. this.onProgressObservable = new BABYLON.Observable();
  97466. /**
  97467. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97468. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97469. */
  97470. this.useDefaultLoadingScreen = true;
  97471. this._scene = scene;
  97472. }
  97473. /**
  97474. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97475. * @param taskName defines the name of the new task
  97476. * @param meshesNames defines the name of meshes to load
  97477. * @param rootUrl defines the root url to use to locate files
  97478. * @param sceneFilename defines the filename of the scene file
  97479. * @returns a new {BABYLON.MeshAssetTask} object
  97480. */
  97481. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97482. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97483. this._tasks.push(task);
  97484. return task;
  97485. };
  97486. /**
  97487. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97488. * @param taskName defines the name of the new task
  97489. * @param url defines the url of the file to load
  97490. * @returns a new {BABYLON.TextFileAssetTask} object
  97491. */
  97492. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97493. var task = new TextFileAssetTask(taskName, url);
  97494. this._tasks.push(task);
  97495. return task;
  97496. };
  97497. /**
  97498. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97499. * @param taskName defines the name of the new task
  97500. * @param url defines the url of the file to load
  97501. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97502. */
  97503. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97504. var task = new BinaryFileAssetTask(taskName, url);
  97505. this._tasks.push(task);
  97506. return task;
  97507. };
  97508. /**
  97509. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97510. * @param taskName defines the name of the new task
  97511. * @param url defines the url of the file to load
  97512. * @returns a new {BABYLON.ImageAssetTask} object
  97513. */
  97514. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97515. var task = new ImageAssetTask(taskName, url);
  97516. this._tasks.push(task);
  97517. return task;
  97518. };
  97519. /**
  97520. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97521. * @param taskName defines the name of the new task
  97522. * @param url defines the url of the file to load
  97523. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97524. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97525. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97526. * @returns a new {BABYLON.TextureAssetTask} object
  97527. */
  97528. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97530. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97531. this._tasks.push(task);
  97532. return task;
  97533. };
  97534. /**
  97535. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97536. * @param taskName defines the name of the new task
  97537. * @param url defines the url of the file to load
  97538. * @param extensions defines the extension to use to load the cube map (can be null)
  97539. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97540. * @param files defines the list of files to load (can be null)
  97541. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97542. */
  97543. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97544. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97545. this._tasks.push(task);
  97546. return task;
  97547. };
  97548. /**
  97549. *
  97550. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97551. * @param taskName defines the name of the new task
  97552. * @param url defines the url of the file to load
  97553. * @param size defines the size you want for the cubemap (can be null)
  97554. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97555. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97556. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  97557. * @param reserved Internal use only
  97558. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97559. */
  97560. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97561. if (noMipmap === void 0) { noMipmap = false; }
  97562. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97563. if (gammaSpace === void 0) { gammaSpace = false; }
  97564. if (reserved === void 0) { reserved = false; }
  97565. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97566. this._tasks.push(task);
  97567. return task;
  97568. };
  97569. /**
  97570. * Remove a task from the assets manager.
  97571. * @param task the task to remove
  97572. */
  97573. AssetsManager.prototype.removeTask = function (task) {
  97574. var index = this._tasks.indexOf(task);
  97575. if (index > -1) {
  97576. this._tasks.splice(index, 1);
  97577. }
  97578. };
  97579. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97580. this._waitingTasksCount--;
  97581. try {
  97582. if (this.onProgress) {
  97583. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97584. }
  97585. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97586. }
  97587. catch (e) {
  97588. BABYLON.Tools.Error("Error running progress callbacks.");
  97589. console.log(e);
  97590. }
  97591. if (this._waitingTasksCount === 0) {
  97592. try {
  97593. if (this.onFinish) {
  97594. this.onFinish(this._tasks);
  97595. }
  97596. // Let's remove successfull tasks
  97597. var currentTasks = this._tasks.slice();
  97598. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97599. var task = currentTasks_1[_i];
  97600. if (task.taskState === AssetTaskState.DONE) {
  97601. var index = this._tasks.indexOf(task);
  97602. if (index > -1) {
  97603. this._tasks.splice(index, 1);
  97604. }
  97605. }
  97606. }
  97607. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97608. }
  97609. catch (e) {
  97610. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97611. console.log(e);
  97612. }
  97613. this._isLoading = false;
  97614. this._scene.getEngine().hideLoadingUI();
  97615. }
  97616. };
  97617. AssetsManager.prototype._runTask = function (task) {
  97618. var _this = this;
  97619. var done = function () {
  97620. try {
  97621. if (_this.onTaskSuccess) {
  97622. _this.onTaskSuccess(task);
  97623. }
  97624. _this.onTaskSuccessObservable.notifyObservers(task);
  97625. _this._decreaseWaitingTasksCount(task);
  97626. }
  97627. catch (e) {
  97628. error("Error executing task success callbacks", e);
  97629. }
  97630. };
  97631. var error = function (message, exception) {
  97632. task._setErrorObject(message, exception);
  97633. if (_this.onTaskError) {
  97634. _this.onTaskError(task);
  97635. }
  97636. _this.onTaskErrorObservable.notifyObservers(task);
  97637. _this._decreaseWaitingTasksCount(task);
  97638. };
  97639. task.run(this._scene, done, error);
  97640. };
  97641. /**
  97642. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97643. * @return the current instance of the {BABYLON.AssetsManager}
  97644. */
  97645. AssetsManager.prototype.reset = function () {
  97646. this._isLoading = false;
  97647. this._tasks = new Array();
  97648. return this;
  97649. };
  97650. /**
  97651. * Start the loading process
  97652. * @return the current instance of the {BABYLON.AssetsManager}
  97653. */
  97654. AssetsManager.prototype.load = function () {
  97655. if (this._isLoading) {
  97656. return this;
  97657. }
  97658. this._isLoading = true;
  97659. this._waitingTasksCount = this._tasks.length;
  97660. this._totalTasksCount = this._tasks.length;
  97661. if (this._waitingTasksCount === 0) {
  97662. this._isLoading = false;
  97663. if (this.onFinish) {
  97664. this.onFinish(this._tasks);
  97665. }
  97666. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97667. return this;
  97668. }
  97669. if (this.useDefaultLoadingScreen) {
  97670. this._scene.getEngine().displayLoadingUI();
  97671. }
  97672. for (var index = 0; index < this._tasks.length; index++) {
  97673. var task = this._tasks[index];
  97674. if (task.taskState === AssetTaskState.INIT) {
  97675. this._runTask(task);
  97676. }
  97677. }
  97678. return this;
  97679. };
  97680. return AssetsManager;
  97681. }());
  97682. BABYLON.AssetsManager = AssetsManager;
  97683. })(BABYLON || (BABYLON = {}));
  97684. //# sourceMappingURL=babylon.assetsManager.js.map
  97685. var BABYLON;
  97686. (function (BABYLON) {
  97687. var serializedGeometries = [];
  97688. var serializeGeometry = function (geometry, serializationGeometries) {
  97689. if (serializedGeometries[geometry.id]) {
  97690. return;
  97691. }
  97692. if (geometry.doNotSerialize) {
  97693. return;
  97694. }
  97695. if (geometry instanceof BABYLON.BoxGeometry) {
  97696. serializationGeometries.boxes.push(geometry.serialize());
  97697. }
  97698. else if (geometry instanceof BABYLON.SphereGeometry) {
  97699. serializationGeometries.spheres.push(geometry.serialize());
  97700. }
  97701. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97702. serializationGeometries.cylinders.push(geometry.serialize());
  97703. }
  97704. else if (geometry instanceof BABYLON.TorusGeometry) {
  97705. serializationGeometries.toruses.push(geometry.serialize());
  97706. }
  97707. else if (geometry instanceof BABYLON.GroundGeometry) {
  97708. serializationGeometries.grounds.push(geometry.serialize());
  97709. }
  97710. else if (geometry instanceof BABYLON.Plane) {
  97711. serializationGeometries.planes.push(geometry.serialize());
  97712. }
  97713. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97714. serializationGeometries.torusKnots.push(geometry.serialize());
  97715. }
  97716. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97717. throw new Error("Unknown primitive type");
  97718. }
  97719. else {
  97720. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97721. }
  97722. serializedGeometries[geometry.id] = true;
  97723. };
  97724. var serializeMesh = function (mesh, serializationScene) {
  97725. var serializationObject = {};
  97726. // Geometry
  97727. var geometry = mesh._geometry;
  97728. if (geometry) {
  97729. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97730. // 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
  97731. serializeGeometry(geometry, serializationScene.geometries);
  97732. }
  97733. }
  97734. // Custom
  97735. if (mesh.serialize) {
  97736. mesh.serialize(serializationObject);
  97737. }
  97738. return serializationObject;
  97739. };
  97740. var finalizeSingleMesh = function (mesh, serializationObject) {
  97741. //only works if the mesh is already loaded
  97742. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97743. //serialize material
  97744. if (mesh.material) {
  97745. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97746. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97747. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97748. serializationObject.multiMaterials.push(mesh.material.serialize());
  97749. }
  97750. }
  97751. else {
  97752. serializationObject.materials = serializationObject.materials || [];
  97753. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97754. serializationObject.materials.push(mesh.material.serialize());
  97755. }
  97756. }
  97757. }
  97758. //serialize geometry
  97759. var geometry = mesh._geometry;
  97760. if (geometry) {
  97761. if (!serializationObject.geometries) {
  97762. serializationObject.geometries = {};
  97763. serializationObject.geometries.boxes = [];
  97764. serializationObject.geometries.spheres = [];
  97765. serializationObject.geometries.cylinders = [];
  97766. serializationObject.geometries.toruses = [];
  97767. serializationObject.geometries.grounds = [];
  97768. serializationObject.geometries.planes = [];
  97769. serializationObject.geometries.torusKnots = [];
  97770. serializationObject.geometries.vertexData = [];
  97771. }
  97772. serializeGeometry(geometry, serializationObject.geometries);
  97773. }
  97774. // Skeletons
  97775. if (mesh.skeleton) {
  97776. serializationObject.skeletons = serializationObject.skeletons || [];
  97777. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97778. }
  97779. //serialize the actual mesh
  97780. serializationObject.meshes = serializationObject.meshes || [];
  97781. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97782. }
  97783. };
  97784. var SceneSerializer = /** @class */ (function () {
  97785. function SceneSerializer() {
  97786. }
  97787. SceneSerializer.ClearCache = function () {
  97788. serializedGeometries = [];
  97789. };
  97790. SceneSerializer.Serialize = function (scene) {
  97791. var serializationObject = {};
  97792. SceneSerializer.ClearCache();
  97793. // Scene
  97794. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97795. serializationObject.autoClear = scene.autoClear;
  97796. serializationObject.clearColor = scene.clearColor.asArray();
  97797. serializationObject.ambientColor = scene.ambientColor.asArray();
  97798. serializationObject.gravity = scene.gravity.asArray();
  97799. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97800. serializationObject.workerCollisions = scene.workerCollisions;
  97801. // Fog
  97802. if (scene.fogMode && scene.fogMode !== 0) {
  97803. serializationObject.fogMode = scene.fogMode;
  97804. serializationObject.fogColor = scene.fogColor.asArray();
  97805. serializationObject.fogStart = scene.fogStart;
  97806. serializationObject.fogEnd = scene.fogEnd;
  97807. serializationObject.fogDensity = scene.fogDensity;
  97808. }
  97809. //Physics
  97810. if (scene.isPhysicsEnabled()) {
  97811. var physicEngine = scene.getPhysicsEngine();
  97812. if (physicEngine) {
  97813. serializationObject.physicsEnabled = true;
  97814. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97815. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97816. }
  97817. }
  97818. // Metadata
  97819. if (scene.metadata) {
  97820. serializationObject.metadata = scene.metadata;
  97821. }
  97822. // Morph targets
  97823. serializationObject.morphTargetManagers = [];
  97824. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97825. var abstractMesh = _a[_i];
  97826. var manager = abstractMesh.morphTargetManager;
  97827. if (manager) {
  97828. serializationObject.morphTargetManagers.push(manager.serialize());
  97829. }
  97830. }
  97831. // Lights
  97832. serializationObject.lights = [];
  97833. var index;
  97834. var light;
  97835. for (index = 0; index < scene.lights.length; index++) {
  97836. light = scene.lights[index];
  97837. if (!light.doNotSerialize) {
  97838. serializationObject.lights.push(light.serialize());
  97839. }
  97840. }
  97841. // Cameras
  97842. serializationObject.cameras = [];
  97843. for (index = 0; index < scene.cameras.length; index++) {
  97844. var camera = scene.cameras[index];
  97845. if (!camera.doNotSerialize) {
  97846. serializationObject.cameras.push(camera.serialize());
  97847. }
  97848. }
  97849. if (scene.activeCamera) {
  97850. serializationObject.activeCameraID = scene.activeCamera.id;
  97851. }
  97852. // Animations
  97853. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97854. // Materials
  97855. serializationObject.materials = [];
  97856. serializationObject.multiMaterials = [];
  97857. var material;
  97858. for (index = 0; index < scene.materials.length; index++) {
  97859. material = scene.materials[index];
  97860. if (!material.doNotSerialize) {
  97861. serializationObject.materials.push(material.serialize());
  97862. }
  97863. }
  97864. // MultiMaterials
  97865. serializationObject.multiMaterials = [];
  97866. for (index = 0; index < scene.multiMaterials.length; index++) {
  97867. var multiMaterial = scene.multiMaterials[index];
  97868. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97869. }
  97870. // Environment texture
  97871. if (scene.environmentTexture) {
  97872. serializationObject.environmentTexture = scene.environmentTexture.name;
  97873. }
  97874. // Skeletons
  97875. serializationObject.skeletons = [];
  97876. for (index = 0; index < scene.skeletons.length; index++) {
  97877. var skeleton = scene.skeletons[index];
  97878. if (!skeleton.doNotSerialize) {
  97879. serializationObject.skeletons.push(skeleton.serialize());
  97880. }
  97881. }
  97882. // Transform nodes
  97883. serializationObject.transformNodes = [];
  97884. for (index = 0; index < scene.transformNodes.length; index++) {
  97885. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97886. }
  97887. // Geometries
  97888. serializationObject.geometries = {};
  97889. serializationObject.geometries.boxes = [];
  97890. serializationObject.geometries.spheres = [];
  97891. serializationObject.geometries.cylinders = [];
  97892. serializationObject.geometries.toruses = [];
  97893. serializationObject.geometries.grounds = [];
  97894. serializationObject.geometries.planes = [];
  97895. serializationObject.geometries.torusKnots = [];
  97896. serializationObject.geometries.vertexData = [];
  97897. serializedGeometries = [];
  97898. var geometries = scene.getGeometries();
  97899. for (index = 0; index < geometries.length; index++) {
  97900. var geometry = geometries[index];
  97901. if (geometry.isReady()) {
  97902. serializeGeometry(geometry, serializationObject.geometries);
  97903. }
  97904. }
  97905. // Meshes
  97906. serializationObject.meshes = [];
  97907. for (index = 0; index < scene.meshes.length; index++) {
  97908. var abstractMesh = scene.meshes[index];
  97909. if (abstractMesh instanceof BABYLON.Mesh) {
  97910. var mesh = abstractMesh;
  97911. if (!mesh.doNotSerialize) {
  97912. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97913. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97914. }
  97915. }
  97916. }
  97917. }
  97918. // Particles Systems
  97919. serializationObject.particleSystems = [];
  97920. for (index = 0; index < scene.particleSystems.length; index++) {
  97921. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97922. }
  97923. // Lens flares
  97924. serializationObject.lensFlareSystems = [];
  97925. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97926. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97927. }
  97928. // Shadows
  97929. serializationObject.shadowGenerators = [];
  97930. for (index = 0; index < scene.lights.length; index++) {
  97931. light = scene.lights[index];
  97932. var shadowGenerator = light.getShadowGenerator();
  97933. if (shadowGenerator) {
  97934. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97935. }
  97936. }
  97937. // Action Manager
  97938. if (scene.actionManager) {
  97939. serializationObject.actions = scene.actionManager.serialize("scene");
  97940. }
  97941. // Audio
  97942. serializationObject.sounds = [];
  97943. for (index = 0; index < scene.soundTracks.length; index++) {
  97944. var soundtrack = scene.soundTracks[index];
  97945. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97946. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97947. }
  97948. }
  97949. // Effect layers
  97950. serializationObject.effectLayers = [];
  97951. for (index = 0; index < scene.effectLayers.length; index++) {
  97952. var layer = scene.effectLayers[index];
  97953. if (layer.serialize) {
  97954. serializationObject.effectLayers.push(layer.serialize());
  97955. }
  97956. }
  97957. return serializationObject;
  97958. };
  97959. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97960. if (withParents === void 0) { withParents = false; }
  97961. if (withChildren === void 0) { withChildren = false; }
  97962. var serializationObject = {};
  97963. SceneSerializer.ClearCache();
  97964. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97965. if (withParents || withChildren) {
  97966. //deliberate for loop! not for each, appended should be processed as well.
  97967. for (var i = 0; i < toSerialize.length; ++i) {
  97968. if (withChildren) {
  97969. toSerialize[i].getDescendants().forEach(function (node) {
  97970. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97971. toSerialize.push(node);
  97972. }
  97973. });
  97974. }
  97975. //make sure the array doesn't contain the object already
  97976. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97977. toSerialize.push(toSerialize[i].parent);
  97978. }
  97979. }
  97980. }
  97981. toSerialize.forEach(function (mesh) {
  97982. finalizeSingleMesh(mesh, serializationObject);
  97983. });
  97984. return serializationObject;
  97985. };
  97986. return SceneSerializer;
  97987. }());
  97988. BABYLON.SceneSerializer = SceneSerializer;
  97989. })(BABYLON || (BABYLON = {}));
  97990. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97991. var BABYLON;
  97992. (function (BABYLON) {
  97993. var ReflectionProbe = /** @class */ (function () {
  97994. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97995. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97996. var _this = this;
  97997. this.name = name;
  97998. this._viewMatrix = BABYLON.Matrix.Identity();
  97999. this._target = BABYLON.Vector3.Zero();
  98000. this._add = BABYLON.Vector3.Zero();
  98001. this._invertYAxis = false;
  98002. this.position = BABYLON.Vector3.Zero();
  98003. this._scene = scene;
  98004. this._scene.reflectionProbes.push(this);
  98005. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98006. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98007. switch (faceIndex) {
  98008. case 0:
  98009. _this._add.copyFromFloats(1, 0, 0);
  98010. break;
  98011. case 1:
  98012. _this._add.copyFromFloats(-1, 0, 0);
  98013. break;
  98014. case 2:
  98015. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98016. break;
  98017. case 3:
  98018. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98019. break;
  98020. case 4:
  98021. _this._add.copyFromFloats(0, 0, 1);
  98022. break;
  98023. case 5:
  98024. _this._add.copyFromFloats(0, 0, -1);
  98025. break;
  98026. }
  98027. if (_this._attachedMesh) {
  98028. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98029. }
  98030. _this.position.addToRef(_this._add, _this._target);
  98031. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98032. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98033. scene._forcedViewPosition = _this.position;
  98034. });
  98035. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98036. scene._forcedViewPosition = null;
  98037. scene.updateTransformMatrix(true);
  98038. });
  98039. if (scene.activeCamera) {
  98040. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98041. }
  98042. }
  98043. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98044. get: function () {
  98045. return this._renderTargetTexture.samples;
  98046. },
  98047. set: function (value) {
  98048. this._renderTargetTexture.samples = value;
  98049. },
  98050. enumerable: true,
  98051. configurable: true
  98052. });
  98053. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98054. get: function () {
  98055. return this._renderTargetTexture.refreshRate;
  98056. },
  98057. set: function (value) {
  98058. this._renderTargetTexture.refreshRate = value;
  98059. },
  98060. enumerable: true,
  98061. configurable: true
  98062. });
  98063. ReflectionProbe.prototype.getScene = function () {
  98064. return this._scene;
  98065. };
  98066. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98067. get: function () {
  98068. return this._renderTargetTexture;
  98069. },
  98070. enumerable: true,
  98071. configurable: true
  98072. });
  98073. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98074. get: function () {
  98075. return this._renderTargetTexture.renderList;
  98076. },
  98077. enumerable: true,
  98078. configurable: true
  98079. });
  98080. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98081. this._attachedMesh = mesh;
  98082. };
  98083. /**
  98084. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98085. *
  98086. * @param renderingGroupId The rendering group id corresponding to its index
  98087. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98088. */
  98089. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98090. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98091. };
  98092. ReflectionProbe.prototype.dispose = function () {
  98093. var index = this._scene.reflectionProbes.indexOf(this);
  98094. if (index !== -1) {
  98095. // Remove from the scene if found
  98096. this._scene.reflectionProbes.splice(index, 1);
  98097. }
  98098. if (this._renderTargetTexture) {
  98099. this._renderTargetTexture.dispose();
  98100. this._renderTargetTexture = null;
  98101. }
  98102. };
  98103. return ReflectionProbe;
  98104. }());
  98105. BABYLON.ReflectionProbe = ReflectionProbe;
  98106. })(BABYLON || (BABYLON = {}));
  98107. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98108. var BABYLON;
  98109. (function (BABYLON) {
  98110. var Layer = /** @class */ (function () {
  98111. function Layer(name, imgUrl, scene, isBackground, color) {
  98112. this.name = name;
  98113. this.scale = new BABYLON.Vector2(1, 1);
  98114. this.offset = new BABYLON.Vector2(0, 0);
  98115. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98116. this.layerMask = 0x0FFFFFFF;
  98117. this._vertexBuffers = {};
  98118. // Events
  98119. /**
  98120. * An event triggered when the layer is disposed.
  98121. */
  98122. this.onDisposeObservable = new BABYLON.Observable();
  98123. /**
  98124. * An event triggered before rendering the scene
  98125. */
  98126. this.onBeforeRenderObservable = new BABYLON.Observable();
  98127. /**
  98128. * An event triggered after rendering the scene
  98129. */
  98130. this.onAfterRenderObservable = new BABYLON.Observable();
  98131. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98132. this.isBackground = isBackground === undefined ? true : isBackground;
  98133. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98134. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98135. this._scene.layers.push(this);
  98136. var engine = this._scene.getEngine();
  98137. // VBO
  98138. var vertices = [];
  98139. vertices.push(1, 1);
  98140. vertices.push(-1, 1);
  98141. vertices.push(-1, -1);
  98142. vertices.push(1, -1);
  98143. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98144. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98145. this._createIndexBuffer();
  98146. // Effects
  98147. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98148. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98149. }
  98150. Object.defineProperty(Layer.prototype, "onDispose", {
  98151. set: function (callback) {
  98152. if (this._onDisposeObserver) {
  98153. this.onDisposeObservable.remove(this._onDisposeObserver);
  98154. }
  98155. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98156. },
  98157. enumerable: true,
  98158. configurable: true
  98159. });
  98160. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98161. set: function (callback) {
  98162. if (this._onBeforeRenderObserver) {
  98163. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98164. }
  98165. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98166. },
  98167. enumerable: true,
  98168. configurable: true
  98169. });
  98170. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98171. set: function (callback) {
  98172. if (this._onAfterRenderObserver) {
  98173. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98174. }
  98175. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98176. },
  98177. enumerable: true,
  98178. configurable: true
  98179. });
  98180. Layer.prototype._createIndexBuffer = function () {
  98181. var engine = this._scene.getEngine();
  98182. // Indices
  98183. var indices = [];
  98184. indices.push(0);
  98185. indices.push(1);
  98186. indices.push(2);
  98187. indices.push(0);
  98188. indices.push(2);
  98189. indices.push(3);
  98190. this._indexBuffer = engine.createIndexBuffer(indices);
  98191. };
  98192. Layer.prototype._rebuild = function () {
  98193. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98194. if (vb) {
  98195. vb._rebuild();
  98196. }
  98197. this._createIndexBuffer();
  98198. };
  98199. Layer.prototype.render = function () {
  98200. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98201. // Check
  98202. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98203. return;
  98204. var engine = this._scene.getEngine();
  98205. this.onBeforeRenderObservable.notifyObservers(this);
  98206. // Render
  98207. engine.enableEffect(currentEffect);
  98208. engine.setState(false);
  98209. // Texture
  98210. currentEffect.setTexture("textureSampler", this.texture);
  98211. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98212. // Color
  98213. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98214. // Scale / offset
  98215. currentEffect.setVector2("offset", this.offset);
  98216. currentEffect.setVector2("scale", this.scale);
  98217. // VBOs
  98218. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98219. // Draw order
  98220. if (!this.alphaTest) {
  98221. engine.setAlphaMode(this.alphaBlendingMode);
  98222. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98223. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98224. }
  98225. else {
  98226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98227. }
  98228. this.onAfterRenderObservable.notifyObservers(this);
  98229. };
  98230. Layer.prototype.dispose = function () {
  98231. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98232. if (vertexBuffer) {
  98233. vertexBuffer.dispose();
  98234. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98235. }
  98236. if (this._indexBuffer) {
  98237. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98238. this._indexBuffer = null;
  98239. }
  98240. if (this.texture) {
  98241. this.texture.dispose();
  98242. this.texture = null;
  98243. }
  98244. // Remove from scene
  98245. var index = this._scene.layers.indexOf(this);
  98246. this._scene.layers.splice(index, 1);
  98247. // Callback
  98248. this.onDisposeObservable.notifyObservers(this);
  98249. this.onDisposeObservable.clear();
  98250. this.onAfterRenderObservable.clear();
  98251. this.onBeforeRenderObservable.clear();
  98252. };
  98253. return Layer;
  98254. }());
  98255. BABYLON.Layer = Layer;
  98256. })(BABYLON || (BABYLON = {}));
  98257. //# sourceMappingURL=babylon.layer.js.map
  98258. var BABYLON;
  98259. (function (BABYLON) {
  98260. var TextureTools = /** @class */ (function () {
  98261. function TextureTools() {
  98262. }
  98263. /**
  98264. * Uses the GPU to create a copy texture rescaled at a given size
  98265. * @param texture Texture to copy from
  98266. * @param width Desired width
  98267. * @param height Desired height
  98268. * @return Generated texture
  98269. */
  98270. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  98271. if (useBilinearMode === void 0) { useBilinearMode = true; }
  98272. var scene = texture.getScene();
  98273. var engine = scene.getEngine();
  98274. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  98275. rtt.wrapU = texture.wrapU;
  98276. rtt.wrapV = texture.wrapV;
  98277. rtt.uOffset = texture.uOffset;
  98278. rtt.vOffset = texture.vOffset;
  98279. rtt.uScale = texture.uScale;
  98280. rtt.vScale = texture.vScale;
  98281. rtt.uAng = texture.uAng;
  98282. rtt.vAng = texture.vAng;
  98283. rtt.wAng = texture.wAng;
  98284. rtt.coordinatesIndex = texture.coordinatesIndex;
  98285. rtt.level = texture.level;
  98286. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98287. rtt._texture.isReady = false;
  98288. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98289. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98290. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98291. passPostProcess.getEffect().executeWhenCompiled(function () {
  98292. passPostProcess.onApply = function (effect) {
  98293. effect.setTexture("textureSampler", texture);
  98294. };
  98295. var internalTexture = rtt.getInternalTexture();
  98296. if (internalTexture) {
  98297. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98298. engine.unBindFramebuffer(internalTexture);
  98299. rtt.disposeFramebufferObjects();
  98300. passPostProcess.dispose();
  98301. internalTexture.isReady = true;
  98302. }
  98303. });
  98304. return rtt;
  98305. };
  98306. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98307. if (!scene._environmentBRDFTexture) {
  98308. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98309. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98310. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98311. scene._environmentBRDFTexture = texture;
  98312. }
  98313. return scene._environmentBRDFTexture;
  98314. };
  98315. 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/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj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lgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  98316. return TextureTools;
  98317. }());
  98318. BABYLON.TextureTools = TextureTools;
  98319. })(BABYLON || (BABYLON = {}));
  98320. //# sourceMappingURL=babylon.textureTools.js.map
  98321. var BABYLON;
  98322. (function (BABYLON) {
  98323. var FramingBehavior = /** @class */ (function () {
  98324. function FramingBehavior() {
  98325. this._mode = FramingBehavior.FitFrustumSidesMode;
  98326. this._radiusScale = 1.0;
  98327. this._positionScale = 0.5;
  98328. this._defaultElevation = 0.3;
  98329. this._elevationReturnTime = 1500;
  98330. this._elevationReturnWaitTime = 1000;
  98331. this._zoomStopsAnimation = false;
  98332. this._framingTime = 1500;
  98333. this._isPointerDown = false;
  98334. this._lastInteractionTime = -Infinity;
  98335. // Framing control
  98336. this._animatables = new Array();
  98337. this._betaIsAnimating = false;
  98338. }
  98339. Object.defineProperty(FramingBehavior.prototype, "name", {
  98340. get: function () {
  98341. return "Framing";
  98342. },
  98343. enumerable: true,
  98344. configurable: true
  98345. });
  98346. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98347. /**
  98348. * Gets current mode used by the behavior.
  98349. */
  98350. get: function () {
  98351. return this._mode;
  98352. },
  98353. /**
  98354. * Sets the current mode used by the behavior
  98355. */
  98356. set: function (mode) {
  98357. this._mode = mode;
  98358. },
  98359. enumerable: true,
  98360. configurable: true
  98361. });
  98362. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98363. /**
  98364. * Gets the scale applied to the radius
  98365. */
  98366. get: function () {
  98367. return this._radiusScale;
  98368. },
  98369. /**
  98370. * Sets the scale applied to the radius (1 by default)
  98371. */
  98372. set: function (radius) {
  98373. this._radiusScale = radius;
  98374. },
  98375. enumerable: true,
  98376. configurable: true
  98377. });
  98378. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98379. /**
  98380. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98381. */
  98382. get: function () {
  98383. return this._positionScale;
  98384. },
  98385. /**
  98386. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98387. */
  98388. set: function (scale) {
  98389. this._positionScale = scale;
  98390. },
  98391. enumerable: true,
  98392. configurable: true
  98393. });
  98394. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98395. /**
  98396. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98397. * behaviour is triggered, in radians.
  98398. */
  98399. get: function () {
  98400. return this._defaultElevation;
  98401. },
  98402. /**
  98403. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98404. * behaviour is triggered, in radians.
  98405. */
  98406. set: function (elevation) {
  98407. this._defaultElevation = elevation;
  98408. },
  98409. enumerable: true,
  98410. configurable: true
  98411. });
  98412. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98413. /**
  98414. * Gets the time (in milliseconds) taken to return to the default beta position.
  98415. * Negative value indicates camera should not return to default.
  98416. */
  98417. get: function () {
  98418. return this._elevationReturnTime;
  98419. },
  98420. /**
  98421. * Sets the time (in milliseconds) taken to return to the default beta position.
  98422. * Negative value indicates camera should not return to default.
  98423. */
  98424. set: function (speed) {
  98425. this._elevationReturnTime = speed;
  98426. },
  98427. enumerable: true,
  98428. configurable: true
  98429. });
  98430. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98431. /**
  98432. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98433. */
  98434. get: function () {
  98435. return this._elevationReturnWaitTime;
  98436. },
  98437. /**
  98438. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98439. */
  98440. set: function (time) {
  98441. this._elevationReturnWaitTime = time;
  98442. },
  98443. enumerable: true,
  98444. configurable: true
  98445. });
  98446. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98447. /**
  98448. * Gets the flag that indicates if user zooming should stop animation.
  98449. */
  98450. get: function () {
  98451. return this._zoomStopsAnimation;
  98452. },
  98453. /**
  98454. * Sets the flag that indicates if user zooming should stop animation.
  98455. */
  98456. set: function (flag) {
  98457. this._zoomStopsAnimation = flag;
  98458. },
  98459. enumerable: true,
  98460. configurable: true
  98461. });
  98462. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98463. /**
  98464. * Gets the transition time when framing the mesh, in milliseconds
  98465. */
  98466. get: function () {
  98467. return this._framingTime;
  98468. },
  98469. /**
  98470. * Sets the transition time when framing the mesh, in milliseconds
  98471. */
  98472. set: function (time) {
  98473. this._framingTime = time;
  98474. },
  98475. enumerable: true,
  98476. configurable: true
  98477. });
  98478. FramingBehavior.prototype.init = function () {
  98479. // Do notihng
  98480. };
  98481. FramingBehavior.prototype.attach = function (camera) {
  98482. var _this = this;
  98483. this._attachedCamera = camera;
  98484. var scene = this._attachedCamera.getScene();
  98485. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98486. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98487. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98488. _this._isPointerDown = true;
  98489. return;
  98490. }
  98491. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98492. _this._isPointerDown = false;
  98493. }
  98494. });
  98495. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98496. if (mesh) {
  98497. _this.zoomOnMesh(mesh);
  98498. }
  98499. });
  98500. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98501. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98502. _this._applyUserInteraction();
  98503. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98504. // back to the default position after a given timeout
  98505. _this._maintainCameraAboveGround();
  98506. });
  98507. };
  98508. FramingBehavior.prototype.detach = function () {
  98509. if (!this._attachedCamera) {
  98510. return;
  98511. }
  98512. var scene = this._attachedCamera.getScene();
  98513. if (this._onPrePointerObservableObserver) {
  98514. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98515. }
  98516. if (this._onAfterCheckInputsObserver) {
  98517. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98518. }
  98519. if (this._onMeshTargetChangedObserver) {
  98520. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98521. }
  98522. this._attachedCamera = null;
  98523. };
  98524. /**
  98525. * Targets the given mesh and updates zoom level accordingly.
  98526. * @param mesh The mesh to target.
  98527. * @param radius Optional. If a cached radius position already exists, overrides default.
  98528. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98529. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98530. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98531. */
  98532. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98533. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98534. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98535. mesh.computeWorldMatrix(true);
  98536. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98537. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98538. };
  98539. /**
  98540. * Targets the given mesh with its children and updates zoom level accordingly.
  98541. * @param mesh The mesh to target.
  98542. * @param radius Optional. If a cached radius position already exists, overrides default.
  98543. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98544. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98545. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98546. */
  98547. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98548. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98549. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98550. mesh.computeWorldMatrix(true);
  98551. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98552. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98553. };
  98554. /**
  98555. * Targets the given meshes with their children and updates zoom level accordingly.
  98556. * @param meshes The mesh to target.
  98557. * @param radius Optional. If a cached radius position already exists, overrides default.
  98558. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98559. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98560. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98561. */
  98562. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98563. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98564. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98565. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98566. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98567. for (var i = 0; i < meshes.length; i++) {
  98568. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98569. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98570. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98571. }
  98572. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98573. };
  98574. /**
  98575. * Targets the given mesh and updates zoom level accordingly.
  98576. * @param mesh The mesh to target.
  98577. * @param radius Optional. If a cached radius position already exists, overrides default.
  98578. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98579. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98580. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98581. */
  98582. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98583. var _this = this;
  98584. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98585. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98586. var zoomTarget;
  98587. if (!this._attachedCamera) {
  98588. return;
  98589. }
  98590. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98591. var bottom = minimumWorld.y;
  98592. var top = maximumWorld.y;
  98593. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98594. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98595. if (focusOnOriginXZ) {
  98596. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98597. }
  98598. else {
  98599. var centerWorld = minimumWorld.add(radiusWorld);
  98600. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98601. }
  98602. if (!this._vectorTransition) {
  98603. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98604. }
  98605. this._betaIsAnimating = true;
  98606. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98607. if (animatable) {
  98608. this._animatables.push(animatable);
  98609. }
  98610. // sets the radius and lower radius bounds
  98611. // Small delta ensures camera is not always at lower zoom limit.
  98612. var radius = 0;
  98613. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98614. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98615. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98616. radius = position;
  98617. }
  98618. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98619. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98620. if (this._attachedCamera.lowerRadiusLimit === null) {
  98621. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98622. }
  98623. }
  98624. // Set sensibilities
  98625. var extend = maximumWorld.subtract(minimumWorld).length();
  98626. this._attachedCamera.panningSensibility = 5000 / extend;
  98627. this._attachedCamera.wheelPrecision = 100 / radius;
  98628. // transition to new radius
  98629. if (!this._radiusTransition) {
  98630. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98631. }
  98632. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98633. _this.stopAllAnimations();
  98634. if (onAnimationEnd) {
  98635. onAnimationEnd();
  98636. }
  98637. if (_this._attachedCamera) {
  98638. _this._attachedCamera.storeState();
  98639. }
  98640. });
  98641. if (animatable) {
  98642. this._animatables.push(animatable);
  98643. }
  98644. };
  98645. /**
  98646. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98647. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98648. * frustum width.
  98649. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98650. * to fully enclose the mesh in the viewing frustum.
  98651. */
  98652. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98653. var size = maximumWorld.subtract(minimumWorld);
  98654. var boxVectorGlobalDiagonal = size.length();
  98655. var frustumSlope = this._getFrustumSlope();
  98656. // Formula for setting distance
  98657. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98658. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98659. // Horizon distance
  98660. var radius = radiusWithoutFraming * this._radiusScale;
  98661. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98662. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98663. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98664. var camera = this._attachedCamera;
  98665. if (!camera) {
  98666. return 0;
  98667. }
  98668. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98669. // Don't exceed the requested limit
  98670. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98671. }
  98672. // Don't exceed the upper radius limit
  98673. if (camera.upperRadiusLimit) {
  98674. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98675. }
  98676. return distance;
  98677. };
  98678. /**
  98679. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98680. * is automatically returned to its default position (expected to be above ground plane).
  98681. */
  98682. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98683. var _this = this;
  98684. if (this._elevationReturnTime < 0) {
  98685. return;
  98686. }
  98687. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98688. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98689. var limitBeta = Math.PI * 0.5;
  98690. // Bring the camera back up if below the ground plane
  98691. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98692. this._betaIsAnimating = true;
  98693. //Transition to new position
  98694. this.stopAllAnimations();
  98695. if (!this._betaTransition) {
  98696. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98697. }
  98698. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98699. _this._clearAnimationLocks();
  98700. _this.stopAllAnimations();
  98701. });
  98702. if (animatabe) {
  98703. this._animatables.push(animatabe);
  98704. }
  98705. }
  98706. };
  98707. /**
  98708. * Returns the frustum slope based on the canvas ratio and camera FOV
  98709. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98710. */
  98711. FramingBehavior.prototype._getFrustumSlope = function () {
  98712. // Calculate the viewport ratio
  98713. // Aspect Ratio is Height/Width.
  98714. var camera = this._attachedCamera;
  98715. if (!camera) {
  98716. return BABYLON.Vector2.Zero();
  98717. }
  98718. var engine = camera.getScene().getEngine();
  98719. var aspectRatio = engine.getAspectRatio(camera);
  98720. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98721. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98722. var frustumSlopeY = Math.tan(camera.fov / 2);
  98723. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98724. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98725. // along the forward vector.
  98726. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98727. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98728. };
  98729. /**
  98730. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98731. */
  98732. FramingBehavior.prototype._clearAnimationLocks = function () {
  98733. this._betaIsAnimating = false;
  98734. };
  98735. /**
  98736. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98737. */
  98738. FramingBehavior.prototype._applyUserInteraction = function () {
  98739. if (this.isUserIsMoving) {
  98740. this._lastInteractionTime = BABYLON.Tools.Now;
  98741. this.stopAllAnimations();
  98742. this._clearAnimationLocks();
  98743. }
  98744. };
  98745. /**
  98746. * Stops and removes all animations that have been applied to the camera
  98747. */
  98748. FramingBehavior.prototype.stopAllAnimations = function () {
  98749. if (this._attachedCamera) {
  98750. this._attachedCamera.animations = [];
  98751. }
  98752. while (this._animatables.length) {
  98753. if (this._animatables[0]) {
  98754. this._animatables[0].onAnimationEnd = null;
  98755. this._animatables[0].stop();
  98756. }
  98757. this._animatables.shift();
  98758. }
  98759. };
  98760. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98761. /**
  98762. * Gets a value indicating if the user is moving the camera
  98763. */
  98764. get: function () {
  98765. if (!this._attachedCamera) {
  98766. return false;
  98767. }
  98768. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98769. this._attachedCamera.inertialBetaOffset !== 0 ||
  98770. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98771. this._attachedCamera.inertialPanningX !== 0 ||
  98772. this._attachedCamera.inertialPanningY !== 0 ||
  98773. this._isPointerDown;
  98774. },
  98775. enumerable: true,
  98776. configurable: true
  98777. });
  98778. /**
  98779. * The easing function used by animations
  98780. */
  98781. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98782. /**
  98783. * The easing mode used by animations
  98784. */
  98785. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98786. // Statics
  98787. /**
  98788. * The camera can move all the way towards the mesh.
  98789. */
  98790. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98791. /**
  98792. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98793. */
  98794. FramingBehavior.FitFrustumSidesMode = 1;
  98795. return FramingBehavior;
  98796. }());
  98797. BABYLON.FramingBehavior = FramingBehavior;
  98798. })(BABYLON || (BABYLON = {}));
  98799. //# sourceMappingURL=babylon.framingBehavior.js.map
  98800. var BABYLON;
  98801. (function (BABYLON) {
  98802. /**
  98803. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98804. */
  98805. var BouncingBehavior = /** @class */ (function () {
  98806. function BouncingBehavior() {
  98807. /**
  98808. * The duration of the animation, in milliseconds
  98809. */
  98810. this.transitionDuration = 450;
  98811. /**
  98812. * Length of the distance animated by the transition when lower radius is reached
  98813. */
  98814. this.lowerRadiusTransitionRange = 2;
  98815. /**
  98816. * Length of the distance animated by the transition when upper radius is reached
  98817. */
  98818. this.upperRadiusTransitionRange = -2;
  98819. this._autoTransitionRange = false;
  98820. // Animations
  98821. this._radiusIsAnimating = false;
  98822. this._radiusBounceTransition = null;
  98823. this._animatables = new Array();
  98824. }
  98825. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98826. get: function () {
  98827. return "Bouncing";
  98828. },
  98829. enumerable: true,
  98830. configurable: true
  98831. });
  98832. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98833. /**
  98834. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98835. */
  98836. get: function () {
  98837. return this._autoTransitionRange;
  98838. },
  98839. /**
  98840. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98841. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98842. */
  98843. set: function (value) {
  98844. var _this = this;
  98845. if (this._autoTransitionRange === value) {
  98846. return;
  98847. }
  98848. this._autoTransitionRange = value;
  98849. var camera = this._attachedCamera;
  98850. if (!camera) {
  98851. return;
  98852. }
  98853. if (value) {
  98854. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98855. if (!mesh) {
  98856. return;
  98857. }
  98858. mesh.computeWorldMatrix(true);
  98859. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98860. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98861. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98862. });
  98863. }
  98864. else if (this._onMeshTargetChangedObserver) {
  98865. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98866. }
  98867. },
  98868. enumerable: true,
  98869. configurable: true
  98870. });
  98871. BouncingBehavior.prototype.init = function () {
  98872. // Do notihng
  98873. };
  98874. BouncingBehavior.prototype.attach = function (camera) {
  98875. var _this = this;
  98876. this._attachedCamera = camera;
  98877. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98878. if (!_this._attachedCamera) {
  98879. return;
  98880. }
  98881. // Add the bounce animation to the lower radius limit
  98882. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98883. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98884. }
  98885. // Add the bounce animation to the upper radius limit
  98886. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98887. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98888. }
  98889. });
  98890. };
  98891. BouncingBehavior.prototype.detach = function () {
  98892. if (!this._attachedCamera) {
  98893. return;
  98894. }
  98895. if (this._onAfterCheckInputsObserver) {
  98896. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98897. }
  98898. if (this._onMeshTargetChangedObserver) {
  98899. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98900. }
  98901. this._attachedCamera = null;
  98902. };
  98903. /**
  98904. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98905. * @param radiusLimit The limit to check against.
  98906. * @return Bool to indicate if at limit.
  98907. */
  98908. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98909. if (!this._attachedCamera) {
  98910. return false;
  98911. }
  98912. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98913. return true;
  98914. }
  98915. return false;
  98916. };
  98917. /**
  98918. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98919. * @param radiusDelta The delta by which to animate to. Can be negative.
  98920. */
  98921. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98922. var _this = this;
  98923. if (!this._attachedCamera) {
  98924. return;
  98925. }
  98926. if (!this._radiusBounceTransition) {
  98927. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98928. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98929. }
  98930. // Prevent zoom until bounce has completed
  98931. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98932. this._attachedCamera.wheelPrecision = Infinity;
  98933. this._attachedCamera.inertialRadiusOffset = 0;
  98934. // Animate to the radius limit
  98935. this.stopAllAnimations();
  98936. this._radiusIsAnimating = true;
  98937. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98938. if (animatable) {
  98939. this._animatables.push(animatable);
  98940. }
  98941. };
  98942. /**
  98943. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98944. */
  98945. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98946. this._radiusIsAnimating = false;
  98947. if (this._attachedCamera) {
  98948. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98949. }
  98950. };
  98951. /**
  98952. * Stops and removes all animations that have been applied to the camera
  98953. */
  98954. BouncingBehavior.prototype.stopAllAnimations = function () {
  98955. if (this._attachedCamera) {
  98956. this._attachedCamera.animations = [];
  98957. }
  98958. while (this._animatables.length) {
  98959. this._animatables[0].onAnimationEnd = null;
  98960. this._animatables[0].stop();
  98961. this._animatables.shift();
  98962. }
  98963. };
  98964. /**
  98965. * The easing function used by animations
  98966. */
  98967. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98968. /**
  98969. * The easing mode used by animations
  98970. */
  98971. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98972. return BouncingBehavior;
  98973. }());
  98974. BABYLON.BouncingBehavior = BouncingBehavior;
  98975. })(BABYLON || (BABYLON = {}));
  98976. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98977. var BABYLON;
  98978. (function (BABYLON) {
  98979. var AutoRotationBehavior = /** @class */ (function () {
  98980. function AutoRotationBehavior() {
  98981. this._zoomStopsAnimation = false;
  98982. this._idleRotationSpeed = 0.05;
  98983. this._idleRotationWaitTime = 2000;
  98984. this._idleRotationSpinupTime = 2000;
  98985. this._isPointerDown = false;
  98986. this._lastFrameTime = null;
  98987. this._lastInteractionTime = -Infinity;
  98988. this._cameraRotationSpeed = 0;
  98989. this._lastFrameRadius = 0;
  98990. }
  98991. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98992. get: function () {
  98993. return "AutoRotation";
  98994. },
  98995. enumerable: true,
  98996. configurable: true
  98997. });
  98998. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98999. /**
  99000. * Gets the flag that indicates if user zooming should stop animation.
  99001. */
  99002. get: function () {
  99003. return this._zoomStopsAnimation;
  99004. },
  99005. /**
  99006. * Sets the flag that indicates if user zooming should stop animation.
  99007. */
  99008. set: function (flag) {
  99009. this._zoomStopsAnimation = flag;
  99010. },
  99011. enumerable: true,
  99012. configurable: true
  99013. });
  99014. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99015. /**
  99016. * Gets the default speed at which the camera rotates around the model.
  99017. */
  99018. get: function () {
  99019. return this._idleRotationSpeed;
  99020. },
  99021. /**
  99022. * Sets the default speed at which the camera rotates around the model.
  99023. */
  99024. set: function (speed) {
  99025. this._idleRotationSpeed = speed;
  99026. },
  99027. enumerable: true,
  99028. configurable: true
  99029. });
  99030. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99031. /**
  99032. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99033. */
  99034. get: function () {
  99035. return this._idleRotationWaitTime;
  99036. },
  99037. /**
  99038. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99039. */
  99040. set: function (time) {
  99041. this._idleRotationWaitTime = time;
  99042. },
  99043. enumerable: true,
  99044. configurable: true
  99045. });
  99046. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99047. /**
  99048. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99049. */
  99050. get: function () {
  99051. return this._idleRotationSpinupTime;
  99052. },
  99053. /**
  99054. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99055. */
  99056. set: function (time) {
  99057. this._idleRotationSpinupTime = time;
  99058. },
  99059. enumerable: true,
  99060. configurable: true
  99061. });
  99062. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99063. /**
  99064. * Gets a value indicating if the camera is currently rotating because of this behavior
  99065. */
  99066. get: function () {
  99067. return Math.abs(this._cameraRotationSpeed) > 0;
  99068. },
  99069. enumerable: true,
  99070. configurable: true
  99071. });
  99072. AutoRotationBehavior.prototype.init = function () {
  99073. // Do notihng
  99074. };
  99075. AutoRotationBehavior.prototype.attach = function (camera) {
  99076. var _this = this;
  99077. this._attachedCamera = camera;
  99078. var scene = this._attachedCamera.getScene();
  99079. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99080. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99081. _this._isPointerDown = true;
  99082. return;
  99083. }
  99084. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99085. _this._isPointerDown = false;
  99086. }
  99087. });
  99088. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99089. var now = BABYLON.Tools.Now;
  99090. var dt = 0;
  99091. if (_this._lastFrameTime != null) {
  99092. dt = now - _this._lastFrameTime;
  99093. }
  99094. _this._lastFrameTime = now;
  99095. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99096. _this._applyUserInteraction();
  99097. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99098. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99099. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99100. // Step camera rotation by rotation speed
  99101. if (_this._attachedCamera) {
  99102. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99103. }
  99104. });
  99105. };
  99106. AutoRotationBehavior.prototype.detach = function () {
  99107. if (!this._attachedCamera) {
  99108. return;
  99109. }
  99110. var scene = this._attachedCamera.getScene();
  99111. if (this._onPrePointerObservableObserver) {
  99112. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99113. }
  99114. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99115. this._attachedCamera = null;
  99116. };
  99117. /**
  99118. * Returns true if user is scrolling.
  99119. * @return true if user is scrolling.
  99120. */
  99121. AutoRotationBehavior.prototype._userIsZooming = function () {
  99122. if (!this._attachedCamera) {
  99123. return false;
  99124. }
  99125. return this._attachedCamera.inertialRadiusOffset !== 0;
  99126. };
  99127. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99128. if (!this._attachedCamera) {
  99129. return false;
  99130. }
  99131. var zoomHasHitLimit = false;
  99132. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99133. zoomHasHitLimit = true;
  99134. }
  99135. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99136. this._lastFrameRadius = this._attachedCamera.radius;
  99137. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99138. };
  99139. /**
  99140. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99141. */
  99142. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99143. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99144. this._lastInteractionTime = BABYLON.Tools.Now;
  99145. }
  99146. };
  99147. // Tools
  99148. AutoRotationBehavior.prototype._userIsMoving = function () {
  99149. if (!this._attachedCamera) {
  99150. return false;
  99151. }
  99152. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99153. this._attachedCamera.inertialBetaOffset !== 0 ||
  99154. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99155. this._attachedCamera.inertialPanningX !== 0 ||
  99156. this._attachedCamera.inertialPanningY !== 0 ||
  99157. this._isPointerDown;
  99158. };
  99159. return AutoRotationBehavior;
  99160. }());
  99161. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99162. })(BABYLON || (BABYLON = {}));
  99163. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99164. var BABYLON;
  99165. (function (BABYLON) {
  99166. var NullEngineOptions = /** @class */ (function () {
  99167. function NullEngineOptions() {
  99168. this.renderWidth = 512;
  99169. this.renderHeight = 256;
  99170. this.textureSize = 512;
  99171. this.deterministicLockstep = false;
  99172. this.lockstepMaxSteps = 4;
  99173. }
  99174. return NullEngineOptions;
  99175. }());
  99176. BABYLON.NullEngineOptions = NullEngineOptions;
  99177. /**
  99178. * The null engine class provides support for headless version of babylon.js.
  99179. * This can be used in server side scenario or for testing purposes
  99180. */
  99181. var NullEngine = /** @class */ (function (_super) {
  99182. __extends(NullEngine, _super);
  99183. function NullEngine(options) {
  99184. if (options === void 0) { options = new NullEngineOptions(); }
  99185. var _this = _super.call(this, null) || this;
  99186. if (options.deterministicLockstep === undefined) {
  99187. options.deterministicLockstep = false;
  99188. }
  99189. if (options.lockstepMaxSteps === undefined) {
  99190. options.lockstepMaxSteps = 4;
  99191. }
  99192. _this._options = options;
  99193. // Init caps
  99194. // We consider we are on a webgl1 capable device
  99195. _this._caps = new BABYLON.EngineCapabilities();
  99196. _this._caps.maxTexturesImageUnits = 16;
  99197. _this._caps.maxVertexTextureImageUnits = 16;
  99198. _this._caps.maxTextureSize = 512;
  99199. _this._caps.maxCubemapTextureSize = 512;
  99200. _this._caps.maxRenderTextureSize = 512;
  99201. _this._caps.maxVertexAttribs = 16;
  99202. _this._caps.maxVaryingVectors = 16;
  99203. _this._caps.maxFragmentUniformVectors = 16;
  99204. _this._caps.maxVertexUniformVectors = 16;
  99205. // Extensions
  99206. _this._caps.standardDerivatives = false;
  99207. _this._caps.astc = null;
  99208. _this._caps.s3tc = null;
  99209. _this._caps.pvrtc = null;
  99210. _this._caps.etc1 = null;
  99211. _this._caps.etc2 = null;
  99212. _this._caps.textureAnisotropicFilterExtension = null;
  99213. _this._caps.maxAnisotropy = 0;
  99214. _this._caps.uintIndices = false;
  99215. _this._caps.fragmentDepthSupported = false;
  99216. _this._caps.highPrecisionShaderSupported = true;
  99217. _this._caps.colorBufferFloat = false;
  99218. _this._caps.textureFloat = false;
  99219. _this._caps.textureFloatLinearFiltering = false;
  99220. _this._caps.textureFloatRender = false;
  99221. _this._caps.textureHalfFloat = false;
  99222. _this._caps.textureHalfFloatLinearFiltering = false;
  99223. _this._caps.textureHalfFloatRender = false;
  99224. _this._caps.textureLOD = false;
  99225. _this._caps.drawBuffersExtension = false;
  99226. _this._caps.depthTextureExtension = false;
  99227. _this._caps.vertexArrayObject = false;
  99228. _this._caps.instancedArrays = false;
  99229. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99230. // Wrappers
  99231. if (typeof URL === "undefined") {
  99232. URL = {
  99233. createObjectURL: function () { },
  99234. revokeObjectURL: function () { }
  99235. };
  99236. }
  99237. if (typeof Blob === "undefined") {
  99238. Blob = function () { };
  99239. }
  99240. return _this;
  99241. }
  99242. NullEngine.prototype.isDeterministicLockStep = function () {
  99243. return this._options.deterministicLockstep;
  99244. };
  99245. NullEngine.prototype.getLockstepMaxSteps = function () {
  99246. return this._options.lockstepMaxSteps;
  99247. };
  99248. NullEngine.prototype.getHardwareScalingLevel = function () {
  99249. return 1.0;
  99250. };
  99251. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99252. return {
  99253. capacity: 0,
  99254. references: 1,
  99255. is32Bits: false
  99256. };
  99257. };
  99258. NullEngine.prototype.createIndexBuffer = function (indices) {
  99259. return {
  99260. capacity: 0,
  99261. references: 1,
  99262. is32Bits: false
  99263. };
  99264. };
  99265. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99266. if (stencil === void 0) { stencil = false; }
  99267. };
  99268. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99269. if (useScreen === void 0) { useScreen = false; }
  99270. if (!useScreen && this._currentRenderTarget) {
  99271. return this._currentRenderTarget.width;
  99272. }
  99273. return this._options.renderWidth;
  99274. };
  99275. NullEngine.prototype.getRenderHeight = function (useScreen) {
  99276. if (useScreen === void 0) { useScreen = false; }
  99277. if (!useScreen && this._currentRenderTarget) {
  99278. return this._currentRenderTarget.height;
  99279. }
  99280. return this._options.renderHeight;
  99281. };
  99282. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  99283. this._cachedViewport = viewport;
  99284. };
  99285. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99286. return {
  99287. transformFeedback: null,
  99288. __SPECTOR_rebuildProgram: null
  99289. };
  99290. };
  99291. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99292. return [];
  99293. };
  99294. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99295. return [];
  99296. };
  99297. NullEngine.prototype.bindSamplers = function (effect) {
  99298. this._currentEffect = null;
  99299. };
  99300. NullEngine.prototype.enableEffect = function (effect) {
  99301. this._currentEffect = effect;
  99302. if (effect.onBind) {
  99303. effect.onBind(effect);
  99304. }
  99305. effect.onBindObservable.notifyObservers(effect);
  99306. };
  99307. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99308. if (zOffset === void 0) { zOffset = 0; }
  99309. if (reverseSide === void 0) { reverseSide = false; }
  99310. };
  99311. NullEngine.prototype.setIntArray = function (uniform, array) {
  99312. };
  99313. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99314. };
  99315. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99316. };
  99317. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99318. };
  99319. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99320. };
  99321. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99322. };
  99323. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99324. };
  99325. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99326. };
  99327. NullEngine.prototype.setArray = function (uniform, array) {
  99328. };
  99329. NullEngine.prototype.setArray2 = function (uniform, array) {
  99330. };
  99331. NullEngine.prototype.setArray3 = function (uniform, array) {
  99332. };
  99333. NullEngine.prototype.setArray4 = function (uniform, array) {
  99334. };
  99335. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99336. };
  99337. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99338. };
  99339. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99340. };
  99341. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99342. };
  99343. NullEngine.prototype.setFloat = function (uniform, value) {
  99344. };
  99345. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99346. };
  99347. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99348. };
  99349. NullEngine.prototype.setBool = function (uniform, bool) {
  99350. };
  99351. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99352. };
  99353. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99354. };
  99355. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99356. };
  99357. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99358. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99359. if (this._alphaMode === mode) {
  99360. return;
  99361. }
  99362. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99363. if (!noDepthWriteChange) {
  99364. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99365. }
  99366. this._alphaMode = mode;
  99367. };
  99368. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99369. };
  99370. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99371. if (this.preventCacheWipeBetweenFrames) {
  99372. return;
  99373. }
  99374. this.resetTextureCache();
  99375. this._currentEffect = null;
  99376. if (bruteForce) {
  99377. this._currentProgram = null;
  99378. this._stencilState.reset();
  99379. this._depthCullingState.reset();
  99380. this._alphaState.reset();
  99381. }
  99382. this._cachedVertexBuffers = null;
  99383. this._cachedIndexBuffer = null;
  99384. this._cachedEffectForVertexBuffers = null;
  99385. };
  99386. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99387. };
  99388. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99389. };
  99390. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99391. };
  99392. NullEngine.prototype._createTexture = function () {
  99393. return {};
  99394. };
  99395. NullEngine.prototype._releaseTexture = function (texture) {
  99396. };
  99397. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99399. if (onLoad === void 0) { onLoad = null; }
  99400. if (onError === void 0) { onError = null; }
  99401. if (buffer === void 0) { buffer = null; }
  99402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99403. var url = String(urlArg);
  99404. texture.url = url;
  99405. texture.generateMipMaps = !noMipmap;
  99406. texture.samplingMode = samplingMode;
  99407. texture.invertY = invertY;
  99408. texture.baseWidth = this._options.textureSize;
  99409. texture.baseHeight = this._options.textureSize;
  99410. texture.width = this._options.textureSize;
  99411. texture.height = this._options.textureSize;
  99412. if (format) {
  99413. texture.format = format;
  99414. }
  99415. texture.isReady = true;
  99416. if (onLoad) {
  99417. onLoad();
  99418. }
  99419. this._internalTexturesCache.push(texture);
  99420. return texture;
  99421. };
  99422. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99423. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99424. if (options !== undefined && typeof options === "object") {
  99425. fullOptions.generateMipMaps = options.generateMipMaps;
  99426. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99427. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99428. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99429. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99430. }
  99431. else {
  99432. fullOptions.generateMipMaps = options;
  99433. fullOptions.generateDepthBuffer = true;
  99434. fullOptions.generateStencilBuffer = false;
  99435. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99436. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99437. }
  99438. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99439. var width = size.width || size;
  99440. var height = size.height || size;
  99441. texture._depthStencilBuffer = {};
  99442. texture._framebuffer = {};
  99443. texture.baseWidth = width;
  99444. texture.baseHeight = height;
  99445. texture.width = width;
  99446. texture.height = height;
  99447. texture.isReady = true;
  99448. texture.samples = 1;
  99449. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99450. texture.samplingMode = fullOptions.samplingMode;
  99451. texture.type = fullOptions.type;
  99452. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99453. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99454. this._internalTexturesCache.push(texture);
  99455. return texture;
  99456. };
  99457. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99458. texture.samplingMode = samplingMode;
  99459. };
  99460. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99461. if (this._currentRenderTarget) {
  99462. this.unBindFramebuffer(this._currentRenderTarget);
  99463. }
  99464. this._currentRenderTarget = texture;
  99465. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99466. if (this._cachedViewport && !forceFullscreenViewport) {
  99467. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99468. }
  99469. };
  99470. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99471. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99472. this._currentRenderTarget = null;
  99473. if (onBeforeUnbind) {
  99474. if (texture._MSAAFramebuffer) {
  99475. this._currentFramebuffer = texture._framebuffer;
  99476. }
  99477. onBeforeUnbind();
  99478. }
  99479. this._currentFramebuffer = null;
  99480. };
  99481. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99482. var vbo = {
  99483. capacity: 1,
  99484. references: 1,
  99485. is32Bits: false
  99486. };
  99487. return vbo;
  99488. };
  99489. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99490. if (offset === void 0) { offset = 0; }
  99491. };
  99492. /**
  99493. * Updates a dynamic vertex buffer.
  99494. * @param vertexBuffer the vertex buffer to update
  99495. * @param data the data used to update the vertex buffer
  99496. * @param byteOffset the byte offset of the data (optional)
  99497. * @param byteLength the byte length of the data (optional)
  99498. */
  99499. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99500. };
  99501. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99502. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99503. this._boundTexturesCache[this._activeChannel] = texture;
  99504. return true;
  99505. }
  99506. return false;
  99507. };
  99508. NullEngine.prototype._bindTexture = function (channel, texture) {
  99509. if (channel < 0) {
  99510. return;
  99511. }
  99512. this._bindTextureDirectly(0, texture);
  99513. };
  99514. NullEngine.prototype._releaseBuffer = function (buffer) {
  99515. buffer.references--;
  99516. if (buffer.references === 0) {
  99517. return true;
  99518. }
  99519. return false;
  99520. };
  99521. NullEngine.prototype.releaseEffects = function () {
  99522. };
  99523. return NullEngine;
  99524. }(BABYLON.Engine));
  99525. BABYLON.NullEngine = NullEngine;
  99526. })(BABYLON || (BABYLON = {}));
  99527. //# sourceMappingURL=babylon.nullEngine.js.map
  99528. var BABYLON;
  99529. (function (BABYLON) {
  99530. /**
  99531. * This class can be used to get instrumentation data from a Babylon engine
  99532. */
  99533. var EngineInstrumentation = /** @class */ (function () {
  99534. function EngineInstrumentation(engine) {
  99535. this.engine = engine;
  99536. this._captureGPUFrameTime = false;
  99537. this._gpuFrameTime = new BABYLON.PerfCounter();
  99538. this._captureShaderCompilationTime = false;
  99539. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99540. // Observers
  99541. this._onBeginFrameObserver = null;
  99542. this._onEndFrameObserver = null;
  99543. this._onBeforeShaderCompilationObserver = null;
  99544. this._onAfterShaderCompilationObserver = null;
  99545. }
  99546. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99547. // Properties
  99548. /**
  99549. * Gets the perf counter used for GPU frame time
  99550. */
  99551. get: function () {
  99552. return this._gpuFrameTime;
  99553. },
  99554. enumerable: true,
  99555. configurable: true
  99556. });
  99557. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99558. /**
  99559. * Gets the GPU frame time capture status
  99560. */
  99561. get: function () {
  99562. return this._captureGPUFrameTime;
  99563. },
  99564. /**
  99565. * Enable or disable the GPU frame time capture
  99566. */
  99567. set: function (value) {
  99568. var _this = this;
  99569. if (value === this._captureGPUFrameTime) {
  99570. return;
  99571. }
  99572. this._captureGPUFrameTime = value;
  99573. if (value) {
  99574. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99575. if (!_this._gpuFrameTimeToken) {
  99576. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99577. }
  99578. });
  99579. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99580. if (!_this._gpuFrameTimeToken) {
  99581. return;
  99582. }
  99583. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99584. if (time > -1) {
  99585. _this._gpuFrameTimeToken = null;
  99586. _this._gpuFrameTime.fetchNewFrame();
  99587. _this._gpuFrameTime.addCount(time, true);
  99588. }
  99589. });
  99590. }
  99591. else {
  99592. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99593. this._onBeginFrameObserver = null;
  99594. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99595. this._onEndFrameObserver = null;
  99596. }
  99597. },
  99598. enumerable: true,
  99599. configurable: true
  99600. });
  99601. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99602. /**
  99603. * Gets the perf counter used for shader compilation time
  99604. */
  99605. get: function () {
  99606. return this._shaderCompilationTime;
  99607. },
  99608. enumerable: true,
  99609. configurable: true
  99610. });
  99611. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99612. /**
  99613. * Gets the shader compilation time capture status
  99614. */
  99615. get: function () {
  99616. return this._captureShaderCompilationTime;
  99617. },
  99618. /**
  99619. * Enable or disable the shader compilation time capture
  99620. */
  99621. set: function (value) {
  99622. var _this = this;
  99623. if (value === this._captureShaderCompilationTime) {
  99624. return;
  99625. }
  99626. this._captureShaderCompilationTime = value;
  99627. if (value) {
  99628. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99629. _this._shaderCompilationTime.fetchNewFrame();
  99630. _this._shaderCompilationTime.beginMonitoring();
  99631. });
  99632. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99633. _this._shaderCompilationTime.endMonitoring();
  99634. });
  99635. }
  99636. else {
  99637. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99638. this._onBeforeShaderCompilationObserver = null;
  99639. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99640. this._onAfterShaderCompilationObserver = null;
  99641. }
  99642. },
  99643. enumerable: true,
  99644. configurable: true
  99645. });
  99646. EngineInstrumentation.prototype.dispose = function () {
  99647. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99648. this._onBeginFrameObserver = null;
  99649. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99650. this._onEndFrameObserver = null;
  99651. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99652. this._onBeforeShaderCompilationObserver = null;
  99653. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99654. this._onAfterShaderCompilationObserver = null;
  99655. this.engine = null;
  99656. };
  99657. return EngineInstrumentation;
  99658. }());
  99659. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99660. })(BABYLON || (BABYLON = {}));
  99661. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99662. var BABYLON;
  99663. (function (BABYLON) {
  99664. /**
  99665. * This class can be used to get instrumentation data from a Babylon engine
  99666. */
  99667. var SceneInstrumentation = /** @class */ (function () {
  99668. function SceneInstrumentation(scene) {
  99669. var _this = this;
  99670. this.scene = scene;
  99671. this._captureActiveMeshesEvaluationTime = false;
  99672. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99673. this._captureRenderTargetsRenderTime = false;
  99674. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99675. this._captureFrameTime = false;
  99676. this._frameTime = new BABYLON.PerfCounter();
  99677. this._captureRenderTime = false;
  99678. this._renderTime = new BABYLON.PerfCounter();
  99679. this._captureInterFrameTime = false;
  99680. this._interFrameTime = new BABYLON.PerfCounter();
  99681. this._captureParticlesRenderTime = false;
  99682. this._particlesRenderTime = new BABYLON.PerfCounter();
  99683. this._captureSpritesRenderTime = false;
  99684. this._spritesRenderTime = new BABYLON.PerfCounter();
  99685. this._capturePhysicsTime = false;
  99686. this._physicsTime = new BABYLON.PerfCounter();
  99687. this._captureAnimationsTime = false;
  99688. this._animationsTime = new BABYLON.PerfCounter();
  99689. this._captureCameraRenderTime = false;
  99690. this._cameraRenderTime = new BABYLON.PerfCounter();
  99691. // Observers
  99692. this._onBeforeActiveMeshesEvaluationObserver = null;
  99693. this._onAfterActiveMeshesEvaluationObserver = null;
  99694. this._onBeforeRenderTargetsRenderObserver = null;
  99695. this._onAfterRenderTargetsRenderObserver = null;
  99696. this._onAfterRenderObserver = null;
  99697. this._onBeforeDrawPhaseObserver = null;
  99698. this._onAfterDrawPhaseObserver = null;
  99699. this._onBeforeAnimationsObserver = null;
  99700. this._onBeforeParticlesRenderingObserver = null;
  99701. this._onAfterParticlesRenderingObserver = null;
  99702. this._onBeforeSpritesRenderingObserver = null;
  99703. this._onAfterSpritesRenderingObserver = null;
  99704. this._onBeforePhysicsObserver = null;
  99705. this._onAfterPhysicsObserver = null;
  99706. this._onAfterAnimationsObserver = null;
  99707. this._onBeforeCameraRenderObserver = null;
  99708. this._onAfterCameraRenderObserver = null;
  99709. // Before render
  99710. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99711. if (_this._captureActiveMeshesEvaluationTime) {
  99712. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99713. }
  99714. if (_this._captureRenderTargetsRenderTime) {
  99715. _this._renderTargetsRenderTime.fetchNewFrame();
  99716. }
  99717. if (_this._captureFrameTime) {
  99718. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99719. _this._frameTime.beginMonitoring();
  99720. }
  99721. if (_this._captureInterFrameTime) {
  99722. _this._interFrameTime.endMonitoring();
  99723. }
  99724. if (_this._captureParticlesRenderTime) {
  99725. _this._particlesRenderTime.fetchNewFrame();
  99726. }
  99727. if (_this._captureSpritesRenderTime) {
  99728. _this._spritesRenderTime.fetchNewFrame();
  99729. }
  99730. if (_this._captureAnimationsTime) {
  99731. _this._animationsTime.beginMonitoring();
  99732. }
  99733. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99734. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99735. });
  99736. // After render
  99737. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99738. if (_this._captureFrameTime) {
  99739. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99740. _this._frameTime.endMonitoring();
  99741. }
  99742. if (_this._captureRenderTime) {
  99743. _this._renderTime.endMonitoring(false);
  99744. }
  99745. if (_this._captureInterFrameTime) {
  99746. _this._interFrameTime.beginMonitoring();
  99747. }
  99748. });
  99749. }
  99750. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99751. // Properties
  99752. /**
  99753. * Gets the perf counter used for active meshes evaluation time
  99754. */
  99755. get: function () {
  99756. return this._activeMeshesEvaluationTime;
  99757. },
  99758. enumerable: true,
  99759. configurable: true
  99760. });
  99761. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99762. /**
  99763. * Gets the active meshes evaluation time capture status
  99764. */
  99765. get: function () {
  99766. return this._captureActiveMeshesEvaluationTime;
  99767. },
  99768. /**
  99769. * Enable or disable the active meshes evaluation time capture
  99770. */
  99771. set: function (value) {
  99772. var _this = this;
  99773. if (value === this._captureActiveMeshesEvaluationTime) {
  99774. return;
  99775. }
  99776. this._captureActiveMeshesEvaluationTime = value;
  99777. if (value) {
  99778. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99779. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99780. _this._activeMeshesEvaluationTime.beginMonitoring();
  99781. });
  99782. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99783. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99784. _this._activeMeshesEvaluationTime.endMonitoring();
  99785. });
  99786. }
  99787. else {
  99788. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99789. this._onBeforeActiveMeshesEvaluationObserver = null;
  99790. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99791. this._onAfterActiveMeshesEvaluationObserver = null;
  99792. }
  99793. },
  99794. enumerable: true,
  99795. configurable: true
  99796. });
  99797. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99798. /**
  99799. * Gets the perf counter used for render targets render time
  99800. */
  99801. get: function () {
  99802. return this._renderTargetsRenderTime;
  99803. },
  99804. enumerable: true,
  99805. configurable: true
  99806. });
  99807. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99808. /**
  99809. * Gets the render targets render time capture status
  99810. */
  99811. get: function () {
  99812. return this._captureRenderTargetsRenderTime;
  99813. },
  99814. /**
  99815. * Enable or disable the render targets render time capture
  99816. */
  99817. set: function (value) {
  99818. var _this = this;
  99819. if (value === this._captureRenderTargetsRenderTime) {
  99820. return;
  99821. }
  99822. this._captureRenderTargetsRenderTime = value;
  99823. if (value) {
  99824. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99825. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99826. _this._renderTargetsRenderTime.beginMonitoring();
  99827. });
  99828. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99829. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99830. _this._renderTargetsRenderTime.endMonitoring(false);
  99831. });
  99832. }
  99833. else {
  99834. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99835. this._onBeforeRenderTargetsRenderObserver = null;
  99836. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99837. this._onAfterRenderTargetsRenderObserver = null;
  99838. }
  99839. },
  99840. enumerable: true,
  99841. configurable: true
  99842. });
  99843. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99844. /**
  99845. * Gets the perf counter used for particles render time
  99846. */
  99847. get: function () {
  99848. return this._particlesRenderTime;
  99849. },
  99850. enumerable: true,
  99851. configurable: true
  99852. });
  99853. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99854. /**
  99855. * Gets the particles render time capture status
  99856. */
  99857. get: function () {
  99858. return this._captureParticlesRenderTime;
  99859. },
  99860. /**
  99861. * Enable or disable the particles render time capture
  99862. */
  99863. set: function (value) {
  99864. var _this = this;
  99865. if (value === this._captureParticlesRenderTime) {
  99866. return;
  99867. }
  99868. this._captureParticlesRenderTime = value;
  99869. if (value) {
  99870. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99871. BABYLON.Tools.StartPerformanceCounter("Particles");
  99872. _this._particlesRenderTime.beginMonitoring();
  99873. });
  99874. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99875. BABYLON.Tools.EndPerformanceCounter("Particles");
  99876. _this._particlesRenderTime.endMonitoring(false);
  99877. });
  99878. }
  99879. else {
  99880. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99881. this._onBeforeParticlesRenderingObserver = null;
  99882. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99883. this._onAfterParticlesRenderingObserver = null;
  99884. }
  99885. },
  99886. enumerable: true,
  99887. configurable: true
  99888. });
  99889. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99890. /**
  99891. * Gets the perf counter used for sprites render time
  99892. */
  99893. get: function () {
  99894. return this._spritesRenderTime;
  99895. },
  99896. enumerable: true,
  99897. configurable: true
  99898. });
  99899. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99900. /**
  99901. * Gets the sprites render time capture status
  99902. */
  99903. get: function () {
  99904. return this._captureSpritesRenderTime;
  99905. },
  99906. /**
  99907. * Enable or disable the sprites render time capture
  99908. */
  99909. set: function (value) {
  99910. var _this = this;
  99911. if (value === this._captureSpritesRenderTime) {
  99912. return;
  99913. }
  99914. this._captureSpritesRenderTime = value;
  99915. if (value) {
  99916. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99917. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99918. _this._spritesRenderTime.beginMonitoring();
  99919. });
  99920. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99921. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99922. _this._spritesRenderTime.endMonitoring(false);
  99923. });
  99924. }
  99925. else {
  99926. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99927. this._onBeforeSpritesRenderingObserver = null;
  99928. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99929. this._onAfterSpritesRenderingObserver = null;
  99930. }
  99931. },
  99932. enumerable: true,
  99933. configurable: true
  99934. });
  99935. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99936. /**
  99937. * Gets the perf counter used for physics time
  99938. */
  99939. get: function () {
  99940. return this._physicsTime;
  99941. },
  99942. enumerable: true,
  99943. configurable: true
  99944. });
  99945. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99946. /**
  99947. * Gets the physics time capture status
  99948. */
  99949. get: function () {
  99950. return this._capturePhysicsTime;
  99951. },
  99952. /**
  99953. * Enable or disable the physics time capture
  99954. */
  99955. set: function (value) {
  99956. var _this = this;
  99957. if (value === this._capturePhysicsTime) {
  99958. return;
  99959. }
  99960. this._capturePhysicsTime = value;
  99961. if (value) {
  99962. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99963. BABYLON.Tools.StartPerformanceCounter("Physics");
  99964. _this._physicsTime.beginMonitoring();
  99965. });
  99966. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99967. BABYLON.Tools.EndPerformanceCounter("Physics");
  99968. _this._physicsTime.endMonitoring();
  99969. });
  99970. }
  99971. else {
  99972. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99973. this._onBeforePhysicsObserver = null;
  99974. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99975. this._onAfterPhysicsObserver = null;
  99976. }
  99977. },
  99978. enumerable: true,
  99979. configurable: true
  99980. });
  99981. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99982. /**
  99983. * Gets the perf counter used for animations time
  99984. */
  99985. get: function () {
  99986. return this._animationsTime;
  99987. },
  99988. enumerable: true,
  99989. configurable: true
  99990. });
  99991. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99992. /**
  99993. * Gets the animations time capture status
  99994. */
  99995. get: function () {
  99996. return this._captureAnimationsTime;
  99997. },
  99998. /**
  99999. * Enable or disable the animations time capture
  100000. */
  100001. set: function (value) {
  100002. var _this = this;
  100003. if (value === this._captureAnimationsTime) {
  100004. return;
  100005. }
  100006. this._captureAnimationsTime = value;
  100007. if (value) {
  100008. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100009. _this._animationsTime.endMonitoring();
  100010. });
  100011. }
  100012. else {
  100013. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100014. this._onAfterAnimationsObserver = null;
  100015. }
  100016. },
  100017. enumerable: true,
  100018. configurable: true
  100019. });
  100020. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100021. /**
  100022. * Gets the perf counter used for frame time capture
  100023. */
  100024. get: function () {
  100025. return this._frameTime;
  100026. },
  100027. enumerable: true,
  100028. configurable: true
  100029. });
  100030. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100031. /**
  100032. * Gets the frame time capture status
  100033. */
  100034. get: function () {
  100035. return this._captureFrameTime;
  100036. },
  100037. /**
  100038. * Enable or disable the frame time capture
  100039. */
  100040. set: function (value) {
  100041. this._captureFrameTime = value;
  100042. },
  100043. enumerable: true,
  100044. configurable: true
  100045. });
  100046. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100047. /**
  100048. * Gets the perf counter used for inter-frames time capture
  100049. */
  100050. get: function () {
  100051. return this._interFrameTime;
  100052. },
  100053. enumerable: true,
  100054. configurable: true
  100055. });
  100056. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100057. /**
  100058. * Gets the inter-frames time capture status
  100059. */
  100060. get: function () {
  100061. return this._captureInterFrameTime;
  100062. },
  100063. /**
  100064. * Enable or disable the inter-frames time capture
  100065. */
  100066. set: function (value) {
  100067. this._captureInterFrameTime = value;
  100068. },
  100069. enumerable: true,
  100070. configurable: true
  100071. });
  100072. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100073. /**
  100074. * Gets the perf counter used for render time capture
  100075. */
  100076. get: function () {
  100077. return this._renderTime;
  100078. },
  100079. enumerable: true,
  100080. configurable: true
  100081. });
  100082. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100083. /**
  100084. * Gets the render time capture status
  100085. */
  100086. get: function () {
  100087. return this._captureRenderTime;
  100088. },
  100089. /**
  100090. * Enable or disable the render time capture
  100091. */
  100092. set: function (value) {
  100093. var _this = this;
  100094. if (value === this._captureRenderTime) {
  100095. return;
  100096. }
  100097. this._captureRenderTime = value;
  100098. if (value) {
  100099. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100100. _this._renderTime.beginMonitoring();
  100101. BABYLON.Tools.StartPerformanceCounter("Main render");
  100102. });
  100103. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100104. _this._renderTime.endMonitoring(false);
  100105. BABYLON.Tools.EndPerformanceCounter("Main render");
  100106. });
  100107. }
  100108. else {
  100109. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100110. this._onBeforeDrawPhaseObserver = null;
  100111. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100112. this._onAfterDrawPhaseObserver = null;
  100113. }
  100114. },
  100115. enumerable: true,
  100116. configurable: true
  100117. });
  100118. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100119. /**
  100120. * Gets the perf counter used for camera render time capture
  100121. */
  100122. get: function () {
  100123. return this._cameraRenderTime;
  100124. },
  100125. enumerable: true,
  100126. configurable: true
  100127. });
  100128. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100129. /**
  100130. * Gets the camera render time capture status
  100131. */
  100132. get: function () {
  100133. return this._captureCameraRenderTime;
  100134. },
  100135. /**
  100136. * Enable or disable the camera render time capture
  100137. */
  100138. set: function (value) {
  100139. var _this = this;
  100140. if (value === this._captureCameraRenderTime) {
  100141. return;
  100142. }
  100143. this._captureCameraRenderTime = value;
  100144. if (value) {
  100145. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100146. _this._cameraRenderTime.beginMonitoring();
  100147. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100148. });
  100149. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100150. _this._cameraRenderTime.endMonitoring(false);
  100151. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100152. });
  100153. }
  100154. else {
  100155. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100156. this._onBeforeCameraRenderObserver = null;
  100157. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100158. this._onAfterCameraRenderObserver = null;
  100159. }
  100160. },
  100161. enumerable: true,
  100162. configurable: true
  100163. });
  100164. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100165. /**
  100166. * Gets the perf counter used for draw calls
  100167. */
  100168. get: function () {
  100169. return this.scene.getEngine()._drawCalls;
  100170. },
  100171. enumerable: true,
  100172. configurable: true
  100173. });
  100174. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100175. /**
  100176. * Gets the perf counter used for texture collisions
  100177. */
  100178. get: function () {
  100179. return this.scene.getEngine()._textureCollisions;
  100180. },
  100181. enumerable: true,
  100182. configurable: true
  100183. });
  100184. SceneInstrumentation.prototype.dispose = function () {
  100185. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100186. this._onAfterRenderObserver = null;
  100187. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100188. this._onBeforeActiveMeshesEvaluationObserver = null;
  100189. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100190. this._onAfterActiveMeshesEvaluationObserver = null;
  100191. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100192. this._onBeforeRenderTargetsRenderObserver = null;
  100193. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100194. this._onAfterRenderTargetsRenderObserver = null;
  100195. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100196. this._onBeforeAnimationsObserver = null;
  100197. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100198. this._onBeforeParticlesRenderingObserver = null;
  100199. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100200. this._onAfterParticlesRenderingObserver = null;
  100201. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100202. this._onBeforeSpritesRenderingObserver = null;
  100203. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100204. this._onAfterSpritesRenderingObserver = null;
  100205. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100206. this._onBeforeDrawPhaseObserver = null;
  100207. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100208. this._onAfterDrawPhaseObserver = null;
  100209. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100210. this._onBeforePhysicsObserver = null;
  100211. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100212. this._onAfterPhysicsObserver = null;
  100213. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100214. this._onAfterAnimationsObserver = null;
  100215. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100216. this._onBeforeCameraRenderObserver = null;
  100217. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100218. this._onAfterCameraRenderObserver = null;
  100219. this.scene = null;
  100220. };
  100221. return SceneInstrumentation;
  100222. }());
  100223. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100224. })(BABYLON || (BABYLON = {}));
  100225. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100226. var BABYLON;
  100227. (function (BABYLON) {
  100228. /**
  100229. * @hidden
  100230. **/
  100231. var _TimeToken = /** @class */ (function () {
  100232. function _TimeToken() {
  100233. this._timeElapsedQueryEnded = false;
  100234. }
  100235. return _TimeToken;
  100236. }());
  100237. BABYLON._TimeToken = _TimeToken;
  100238. })(BABYLON || (BABYLON = {}));
  100239. //# sourceMappingURL=babylon.timeToken.js.map
  100240. var BABYLON;
  100241. (function (BABYLON) {
  100242. /**
  100243. * Background material defines definition.
  100244. * @hidden Mainly internal Use
  100245. */
  100246. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100247. __extends(BackgroundMaterialDefines, _super);
  100248. /**
  100249. * Constructor of the defines.
  100250. */
  100251. function BackgroundMaterialDefines() {
  100252. var _this = _super.call(this) || this;
  100253. /**
  100254. * True if the diffuse texture is in use.
  100255. */
  100256. _this.DIFFUSE = false;
  100257. /**
  100258. * The direct UV channel to use.
  100259. */
  100260. _this.DIFFUSEDIRECTUV = 0;
  100261. /**
  100262. * True if the diffuse texture is in gamma space.
  100263. */
  100264. _this.GAMMADIFFUSE = false;
  100265. /**
  100266. * True if the diffuse texture has opacity in the alpha channel.
  100267. */
  100268. _this.DIFFUSEHASALPHA = false;
  100269. /**
  100270. * True if you want the material to fade to transparent at grazing angle.
  100271. */
  100272. _this.OPACITYFRESNEL = false;
  100273. /**
  100274. * True if an extra blur needs to be added in the reflection.
  100275. */
  100276. _this.REFLECTIONBLUR = false;
  100277. /**
  100278. * True if you want the material to fade to reflection at grazing angle.
  100279. */
  100280. _this.REFLECTIONFRESNEL = false;
  100281. /**
  100282. * True if you want the material to falloff as far as you move away from the scene center.
  100283. */
  100284. _this.REFLECTIONFALLOFF = false;
  100285. /**
  100286. * False if the current Webgl implementation does not support the texture lod extension.
  100287. */
  100288. _this.TEXTURELODSUPPORT = false;
  100289. /**
  100290. * True to ensure the data are premultiplied.
  100291. */
  100292. _this.PREMULTIPLYALPHA = false;
  100293. /**
  100294. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100295. */
  100296. _this.USERGBCOLOR = false;
  100297. /**
  100298. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100299. * stays aligned with the desired configuration.
  100300. */
  100301. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100302. /**
  100303. * True to add noise in order to reduce the banding effect.
  100304. */
  100305. _this.NOISE = false;
  100306. /**
  100307. * is the reflection texture in BGR color scheme?
  100308. * Mainly used to solve a bug in ios10 video tag
  100309. */
  100310. _this.REFLECTIONBGR = false;
  100311. _this.IMAGEPROCESSING = false;
  100312. _this.VIGNETTE = false;
  100313. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100314. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100315. _this.TONEMAPPING = false;
  100316. _this.CONTRAST = false;
  100317. _this.COLORCURVES = false;
  100318. _this.COLORGRADING = false;
  100319. _this.COLORGRADING3D = false;
  100320. _this.SAMPLER3DGREENDEPTH = false;
  100321. _this.SAMPLER3DBGRMAP = false;
  100322. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100323. _this.EXPOSURE = false;
  100324. // Reflection.
  100325. _this.REFLECTION = false;
  100326. _this.REFLECTIONMAP_3D = false;
  100327. _this.REFLECTIONMAP_SPHERICAL = false;
  100328. _this.REFLECTIONMAP_PLANAR = false;
  100329. _this.REFLECTIONMAP_CUBIC = false;
  100330. _this.REFLECTIONMAP_PROJECTION = false;
  100331. _this.REFLECTIONMAP_SKYBOX = false;
  100332. _this.REFLECTIONMAP_EXPLICIT = false;
  100333. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100334. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100335. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100336. _this.INVERTCUBICMAP = false;
  100337. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100338. _this.LODINREFLECTIONALPHA = false;
  100339. _this.GAMMAREFLECTION = false;
  100340. _this.RGBDREFLECTION = false;
  100341. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100342. // Default BJS.
  100343. _this.MAINUV1 = false;
  100344. _this.MAINUV2 = false;
  100345. _this.UV1 = false;
  100346. _this.UV2 = false;
  100347. _this.CLIPPLANE = false;
  100348. _this.POINTSIZE = false;
  100349. _this.FOG = false;
  100350. _this.NORMAL = false;
  100351. _this.NUM_BONE_INFLUENCERS = 0;
  100352. _this.BonesPerMesh = 0;
  100353. _this.INSTANCES = false;
  100354. _this.SHADOWFLOAT = false;
  100355. _this.rebuild();
  100356. return _this;
  100357. }
  100358. return BackgroundMaterialDefines;
  100359. }(BABYLON.MaterialDefines));
  100360. /**
  100361. * Background material used to create an efficient environement around your scene.
  100362. */
  100363. var BackgroundMaterial = /** @class */ (function (_super) {
  100364. __extends(BackgroundMaterial, _super);
  100365. /**
  100366. * Instantiates a Background Material in the given scene
  100367. * @param name The friendly name of the material
  100368. * @param scene The scene to add the material to
  100369. */
  100370. function BackgroundMaterial(name, scene) {
  100371. var _this = _super.call(this, name, scene) || this;
  100372. /**
  100373. * Key light Color (multiply against the environement texture)
  100374. */
  100375. _this.primaryColor = BABYLON.Color3.White();
  100376. _this._primaryColorShadowLevel = 0;
  100377. _this._primaryColorHighlightLevel = 0;
  100378. /**
  100379. * Reflection Texture used in the material.
  100380. * Should be author in a specific way for the best result (refer to the documentation).
  100381. */
  100382. _this.reflectionTexture = null;
  100383. /**
  100384. * Reflection Texture level of blur.
  100385. *
  100386. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100387. * texture twice.
  100388. */
  100389. _this.reflectionBlur = 0;
  100390. /**
  100391. * Diffuse Texture used in the material.
  100392. * Should be author in a specific way for the best result (refer to the documentation).
  100393. */
  100394. _this.diffuseTexture = null;
  100395. _this._shadowLights = null;
  100396. /**
  100397. * Specify the list of lights casting shadow on the material.
  100398. * All scene shadow lights will be included if null.
  100399. */
  100400. _this.shadowLights = null;
  100401. /**
  100402. * Helps adjusting the shadow to a softer level if required.
  100403. * 0 means black shadows and 1 means no shadows.
  100404. */
  100405. _this.shadowLevel = 0;
  100406. /**
  100407. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100408. * It is usually zero but might be interesting to modify according to your setup.
  100409. */
  100410. _this.sceneCenter = BABYLON.Vector3.Zero();
  100411. /**
  100412. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100413. * This helps ensuring a nice transition when the camera goes under the ground.
  100414. */
  100415. _this.opacityFresnel = true;
  100416. /**
  100417. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100418. * This helps adding a mirror texture on the ground.
  100419. */
  100420. _this.reflectionFresnel = false;
  100421. /**
  100422. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100423. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100424. */
  100425. _this.reflectionFalloffDistance = 0.0;
  100426. /**
  100427. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100428. */
  100429. _this.reflectionAmount = 1.0;
  100430. /**
  100431. * This specifies the weight of the reflection at grazing angle.
  100432. */
  100433. _this.reflectionReflectance0 = 0.05;
  100434. /**
  100435. * This specifies the weight of the reflection at a perpendicular point of view.
  100436. */
  100437. _this.reflectionReflectance90 = 0.5;
  100438. /**
  100439. * Helps to directly use the maps channels instead of their level.
  100440. */
  100441. _this.useRGBColor = true;
  100442. /**
  100443. * This helps reducing the banding effect that could occur on the background.
  100444. */
  100445. _this.enableNoise = false;
  100446. _this._fovMultiplier = 1.0;
  100447. /**
  100448. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100449. */
  100450. _this.useEquirectangularFOV = false;
  100451. _this._maxSimultaneousLights = 4;
  100452. /**
  100453. * Number of Simultaneous lights allowed on the material.
  100454. */
  100455. _this.maxSimultaneousLights = 4;
  100456. /**
  100457. * Keep track of the image processing observer to allow dispose and replace.
  100458. */
  100459. _this._imageProcessingObserver = null;
  100460. /**
  100461. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100462. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100463. */
  100464. _this.switchToBGR = false;
  100465. // Temp values kept as cache in the material.
  100466. _this._renderTargets = new BABYLON.SmartArray(16);
  100467. _this._reflectionControls = BABYLON.Vector4.Zero();
  100468. _this._white = BABYLON.Color3.White();
  100469. _this._primaryShadowColor = BABYLON.Color3.Black();
  100470. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100471. // Setup the default processing configuration to the scene.
  100472. _this._attachImageProcessingConfiguration(null);
  100473. _this.getRenderTargetTextures = function () {
  100474. _this._renderTargets.reset();
  100475. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100476. _this._renderTargets.push(_this._diffuseTexture);
  100477. }
  100478. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100479. _this._renderTargets.push(_this._reflectionTexture);
  100480. }
  100481. return _this._renderTargets;
  100482. };
  100483. return _this;
  100484. }
  100485. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100486. /**
  100487. * Experimental Internal Use Only.
  100488. *
  100489. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100490. * This acts as a helper to set the primary color to a more "human friendly" value.
  100491. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100492. * output color as close as possible from the chosen value.
  100493. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100494. * part of lighting setup.)
  100495. */
  100496. get: function () {
  100497. return this.__perceptualColor;
  100498. },
  100499. set: function (value) {
  100500. this.__perceptualColor = value;
  100501. this._computePrimaryColorFromPerceptualColor();
  100502. this._markAllSubMeshesAsLightsDirty();
  100503. },
  100504. enumerable: true,
  100505. configurable: true
  100506. });
  100507. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100508. /**
  100509. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100510. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100511. */
  100512. get: function () {
  100513. return this._primaryColorShadowLevel;
  100514. },
  100515. set: function (value) {
  100516. this._primaryColorShadowLevel = value;
  100517. this._computePrimaryColors();
  100518. this._markAllSubMeshesAsLightsDirty();
  100519. },
  100520. enumerable: true,
  100521. configurable: true
  100522. });
  100523. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100524. /**
  100525. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100526. * The primary color is used at the level chosen to define what the white area would look.
  100527. */
  100528. get: function () {
  100529. return this._primaryColorHighlightLevel;
  100530. },
  100531. set: function (value) {
  100532. this._primaryColorHighlightLevel = value;
  100533. this._computePrimaryColors();
  100534. this._markAllSubMeshesAsLightsDirty();
  100535. },
  100536. enumerable: true,
  100537. configurable: true
  100538. });
  100539. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100540. /**
  100541. * Sets the reflection reflectance fresnel values according to the default standard
  100542. * empirically know to work well :-)
  100543. */
  100544. set: function (value) {
  100545. var reflectionWeight = value;
  100546. if (reflectionWeight < 0.5) {
  100547. reflectionWeight = reflectionWeight * 2.0;
  100548. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100549. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100550. }
  100551. else {
  100552. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100553. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100554. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100555. }
  100556. },
  100557. enumerable: true,
  100558. configurable: true
  100559. });
  100560. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100561. /**
  100562. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100563. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100564. * Recommended to be keep at 1.0 except for special cases.
  100565. */
  100566. get: function () {
  100567. return this._fovMultiplier;
  100568. },
  100569. set: function (value) {
  100570. if (isNaN(value)) {
  100571. value = 1.0;
  100572. }
  100573. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100574. },
  100575. enumerable: true,
  100576. configurable: true
  100577. });
  100578. /**
  100579. * Attaches a new image processing configuration to the PBR Material.
  100580. * @param configuration (if null the scene configuration will be use)
  100581. */
  100582. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100583. var _this = this;
  100584. if (configuration === this._imageProcessingConfiguration) {
  100585. return;
  100586. }
  100587. // Detaches observer.
  100588. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100589. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100590. }
  100591. // Pick the scene configuration if needed.
  100592. if (!configuration) {
  100593. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100594. }
  100595. else {
  100596. this._imageProcessingConfiguration = configuration;
  100597. }
  100598. // Attaches observer.
  100599. if (this._imageProcessingConfiguration) {
  100600. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100601. _this._computePrimaryColorFromPerceptualColor();
  100602. _this._markAllSubMeshesAsImageProcessingDirty();
  100603. });
  100604. }
  100605. };
  100606. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100607. /**
  100608. * Gets the image processing configuration used either in this material.
  100609. */
  100610. get: function () {
  100611. return this._imageProcessingConfiguration;
  100612. },
  100613. /**
  100614. * Sets the Default image processing configuration used either in the this material.
  100615. *
  100616. * If sets to null, the scene one is in use.
  100617. */
  100618. set: function (value) {
  100619. this._attachImageProcessingConfiguration(value);
  100620. // Ensure the effect will be rebuilt.
  100621. this._markAllSubMeshesAsTexturesDirty();
  100622. },
  100623. enumerable: true,
  100624. configurable: true
  100625. });
  100626. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100627. /**
  100628. * Gets wether the color curves effect is enabled.
  100629. */
  100630. get: function () {
  100631. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100632. },
  100633. /**
  100634. * Sets wether the color curves effect is enabled.
  100635. */
  100636. set: function (value) {
  100637. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100638. },
  100639. enumerable: true,
  100640. configurable: true
  100641. });
  100642. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100643. /**
  100644. * Gets wether the color grading effect is enabled.
  100645. */
  100646. get: function () {
  100647. return this.imageProcessingConfiguration.colorGradingEnabled;
  100648. },
  100649. /**
  100650. * Gets wether the color grading effect is enabled.
  100651. */
  100652. set: function (value) {
  100653. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100654. },
  100655. enumerable: true,
  100656. configurable: true
  100657. });
  100658. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100659. /**
  100660. * Gets wether tonemapping is enabled or not.
  100661. */
  100662. get: function () {
  100663. return this._imageProcessingConfiguration.toneMappingEnabled;
  100664. },
  100665. /**
  100666. * Sets wether tonemapping is enabled or not
  100667. */
  100668. set: function (value) {
  100669. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100670. },
  100671. enumerable: true,
  100672. configurable: true
  100673. });
  100674. ;
  100675. ;
  100676. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100677. /**
  100678. * The camera exposure used on this material.
  100679. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100680. * This corresponds to a photographic exposure.
  100681. */
  100682. get: function () {
  100683. return this._imageProcessingConfiguration.exposure;
  100684. },
  100685. /**
  100686. * The camera exposure used on this material.
  100687. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100688. * This corresponds to a photographic exposure.
  100689. */
  100690. set: function (value) {
  100691. this._imageProcessingConfiguration.exposure = value;
  100692. },
  100693. enumerable: true,
  100694. configurable: true
  100695. });
  100696. ;
  100697. ;
  100698. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100699. /**
  100700. * Gets The camera contrast used on this material.
  100701. */
  100702. get: function () {
  100703. return this._imageProcessingConfiguration.contrast;
  100704. },
  100705. /**
  100706. * Sets The camera contrast used on this material.
  100707. */
  100708. set: function (value) {
  100709. this._imageProcessingConfiguration.contrast = value;
  100710. },
  100711. enumerable: true,
  100712. configurable: true
  100713. });
  100714. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100715. /**
  100716. * Gets the Color Grading 2D Lookup Texture.
  100717. */
  100718. get: function () {
  100719. return this._imageProcessingConfiguration.colorGradingTexture;
  100720. },
  100721. /**
  100722. * Sets the Color Grading 2D Lookup Texture.
  100723. */
  100724. set: function (value) {
  100725. this.imageProcessingConfiguration.colorGradingTexture = value;
  100726. },
  100727. enumerable: true,
  100728. configurable: true
  100729. });
  100730. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100731. /**
  100732. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100733. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100734. * 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;
  100735. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100736. */
  100737. get: function () {
  100738. return this.imageProcessingConfiguration.colorCurves;
  100739. },
  100740. /**
  100741. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100742. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100743. * 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;
  100744. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100745. */
  100746. set: function (value) {
  100747. this.imageProcessingConfiguration.colorCurves = value;
  100748. },
  100749. enumerable: true,
  100750. configurable: true
  100751. });
  100752. /**
  100753. * The entire material has been created in order to prevent overdraw.
  100754. * @returns false
  100755. */
  100756. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100757. return true;
  100758. };
  100759. /**
  100760. * The entire material has been created in order to prevent overdraw.
  100761. * @returns true if blending is enable
  100762. */
  100763. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100764. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100765. };
  100766. /**
  100767. * Checks wether the material is ready to be rendered for a given mesh.
  100768. * @param mesh The mesh to render
  100769. * @param subMesh The submesh to check against
  100770. * @param useInstances Specify wether or not the material is used with instances
  100771. * @returns true if all the dependencies are ready (Textures, Effects...)
  100772. */
  100773. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100774. var _this = this;
  100775. if (useInstances === void 0) { useInstances = false; }
  100776. if (subMesh.effect && this.isFrozen) {
  100777. if (this._wasPreviouslyReady) {
  100778. return true;
  100779. }
  100780. }
  100781. if (!subMesh._materialDefines) {
  100782. subMesh._materialDefines = new BackgroundMaterialDefines();
  100783. }
  100784. var scene = this.getScene();
  100785. var defines = subMesh._materialDefines;
  100786. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100787. if (defines._renderId === scene.getRenderId()) {
  100788. return true;
  100789. }
  100790. }
  100791. var engine = scene.getEngine();
  100792. // Lights
  100793. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100794. defines._needNormals = true;
  100795. // Textures
  100796. if (defines._areTexturesDirty) {
  100797. defines._needUVs = false;
  100798. if (scene.texturesEnabled) {
  100799. if (scene.getEngine().getCaps().textureLOD) {
  100800. defines.TEXTURELODSUPPORT = true;
  100801. }
  100802. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100803. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100804. return false;
  100805. }
  100806. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100807. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100808. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100809. defines.OPACITYFRESNEL = this._opacityFresnel;
  100810. }
  100811. else {
  100812. defines.DIFFUSE = false;
  100813. defines.DIFFUSEHASALPHA = false;
  100814. defines.GAMMADIFFUSE = false;
  100815. defines.OPACITYFRESNEL = false;
  100816. }
  100817. var reflectionTexture = this._reflectionTexture;
  100818. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100819. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100820. return false;
  100821. }
  100822. defines.REFLECTION = true;
  100823. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100824. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100825. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100826. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100827. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100828. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100829. defines.REFLECTIONBGR = this.switchToBGR;
  100830. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100831. defines.INVERTCUBICMAP = true;
  100832. }
  100833. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100834. switch (reflectionTexture.coordinatesMode) {
  100835. case BABYLON.Texture.EXPLICIT_MODE:
  100836. defines.REFLECTIONMAP_EXPLICIT = true;
  100837. break;
  100838. case BABYLON.Texture.PLANAR_MODE:
  100839. defines.REFLECTIONMAP_PLANAR = true;
  100840. break;
  100841. case BABYLON.Texture.PROJECTION_MODE:
  100842. defines.REFLECTIONMAP_PROJECTION = true;
  100843. break;
  100844. case BABYLON.Texture.SKYBOX_MODE:
  100845. defines.REFLECTIONMAP_SKYBOX = true;
  100846. break;
  100847. case BABYLON.Texture.SPHERICAL_MODE:
  100848. defines.REFLECTIONMAP_SPHERICAL = true;
  100849. break;
  100850. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100851. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100852. break;
  100853. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100854. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100855. break;
  100856. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100857. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100858. break;
  100859. case BABYLON.Texture.CUBIC_MODE:
  100860. case BABYLON.Texture.INVCUBIC_MODE:
  100861. default:
  100862. defines.REFLECTIONMAP_CUBIC = true;
  100863. break;
  100864. }
  100865. if (this.reflectionFresnel) {
  100866. defines.REFLECTIONFRESNEL = true;
  100867. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100868. this._reflectionControls.x = this.reflectionAmount;
  100869. this._reflectionControls.y = this.reflectionReflectance0;
  100870. this._reflectionControls.z = this.reflectionReflectance90;
  100871. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100872. }
  100873. else {
  100874. defines.REFLECTIONFRESNEL = false;
  100875. defines.REFLECTIONFALLOFF = false;
  100876. }
  100877. }
  100878. else {
  100879. defines.REFLECTION = false;
  100880. defines.REFLECTIONFRESNEL = false;
  100881. defines.REFLECTIONFALLOFF = false;
  100882. defines.REFLECTIONBLUR = false;
  100883. defines.REFLECTIONMAP_3D = false;
  100884. defines.REFLECTIONMAP_SPHERICAL = false;
  100885. defines.REFLECTIONMAP_PLANAR = false;
  100886. defines.REFLECTIONMAP_CUBIC = false;
  100887. defines.REFLECTIONMAP_PROJECTION = false;
  100888. defines.REFLECTIONMAP_SKYBOX = false;
  100889. defines.REFLECTIONMAP_EXPLICIT = false;
  100890. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100891. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100892. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100893. defines.INVERTCUBICMAP = false;
  100894. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100895. defines.LODINREFLECTIONALPHA = false;
  100896. defines.GAMMAREFLECTION = false;
  100897. defines.RGBDREFLECTION = false;
  100898. }
  100899. }
  100900. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100901. defines.USERGBCOLOR = this._useRGBColor;
  100902. defines.NOISE = this._enableNoise;
  100903. }
  100904. if (defines._areLightsDirty) {
  100905. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100906. }
  100907. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100908. if (!this._imageProcessingConfiguration.isReady()) {
  100909. return false;
  100910. }
  100911. this._imageProcessingConfiguration.prepareDefines(defines);
  100912. }
  100913. // Misc.
  100914. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100915. // Values that need to be evaluated on every frame
  100916. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100917. // Attribs
  100918. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100919. if (mesh) {
  100920. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100921. mesh.createNormals(true);
  100922. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100923. }
  100924. }
  100925. }
  100926. // Get correct effect
  100927. if (defines.isDirty) {
  100928. defines.markAsProcessed();
  100929. scene.resetCachedMaterial();
  100930. // Fallbacks
  100931. var fallbacks = new BABYLON.EffectFallbacks();
  100932. if (defines.FOG) {
  100933. fallbacks.addFallback(0, "FOG");
  100934. }
  100935. if (defines.POINTSIZE) {
  100936. fallbacks.addFallback(1, "POINTSIZE");
  100937. }
  100938. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100939. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100940. fallbacks.addCPUSkinningFallback(0, mesh);
  100941. }
  100942. //Attributes
  100943. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100944. if (defines.NORMAL) {
  100945. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100946. }
  100947. if (defines.UV1) {
  100948. attribs.push(BABYLON.VertexBuffer.UVKind);
  100949. }
  100950. if (defines.UV2) {
  100951. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100952. }
  100953. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100954. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100955. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100956. "vFogInfos", "vFogColor", "pointSize",
  100957. "vClipPlane", "mBones",
  100958. "vPrimaryColor", "vPrimaryColorShadow",
  100959. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100960. "shadowLevel", "alpha",
  100961. "vBackgroundCenter", "vReflectionControl",
  100962. "vDiffuseInfos", "diffuseMatrix",
  100963. ];
  100964. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100965. var uniformBuffers = ["Material", "Scene"];
  100966. if (BABYLON.ImageProcessingConfiguration) {
  100967. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100968. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100969. }
  100970. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100971. uniformsNames: uniforms,
  100972. uniformBuffersNames: uniformBuffers,
  100973. samplers: samplers,
  100974. defines: defines,
  100975. maxSimultaneousLights: this._maxSimultaneousLights
  100976. });
  100977. var onCompiled = function (effect) {
  100978. if (_this.onCompiled) {
  100979. _this.onCompiled(effect);
  100980. }
  100981. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100982. };
  100983. var join = defines.toString();
  100984. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100985. attributes: attribs,
  100986. uniformsNames: uniforms,
  100987. uniformBuffersNames: uniformBuffers,
  100988. samplers: samplers,
  100989. defines: join,
  100990. fallbacks: fallbacks,
  100991. onCompiled: onCompiled,
  100992. onError: this.onError,
  100993. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100994. }, engine), defines);
  100995. this.buildUniformLayout();
  100996. }
  100997. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100998. return false;
  100999. }
  101000. defines._renderId = scene.getRenderId();
  101001. this._wasPreviouslyReady = true;
  101002. return true;
  101003. };
  101004. /**
  101005. * Compute the primary color according to the chosen perceptual color.
  101006. */
  101007. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101008. if (!this.__perceptualColor) {
  101009. return;
  101010. }
  101011. this._primaryColor.copyFrom(this.__perceptualColor);
  101012. // Revert gamma space.
  101013. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101014. // Revert image processing configuration.
  101015. if (this._imageProcessingConfiguration) {
  101016. // Revert Exposure.
  101017. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101018. }
  101019. this._computePrimaryColors();
  101020. };
  101021. /**
  101022. * Compute the highlights and shadow colors according to their chosen levels.
  101023. */
  101024. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101025. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101026. return;
  101027. }
  101028. // Find the highlight color based on the configuration.
  101029. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101030. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101031. // Find the shadow color based on the configuration.
  101032. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101033. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101034. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101035. };
  101036. /**
  101037. * Build the uniform buffer used in the material.
  101038. */
  101039. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101040. // Order is important !
  101041. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101042. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101043. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101044. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101045. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101046. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101047. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101048. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101049. this._uniformBuffer.addUniform("pointSize", 1);
  101050. this._uniformBuffer.addUniform("shadowLevel", 1);
  101051. this._uniformBuffer.addUniform("alpha", 1);
  101052. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101053. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101054. this._uniformBuffer.create();
  101055. };
  101056. /**
  101057. * Unbind the material.
  101058. */
  101059. BackgroundMaterial.prototype.unbind = function () {
  101060. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101061. this._uniformBuffer.setTexture("diffuseSampler", null);
  101062. }
  101063. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101064. this._uniformBuffer.setTexture("reflectionSampler", null);
  101065. }
  101066. _super.prototype.unbind.call(this);
  101067. };
  101068. /**
  101069. * Bind only the world matrix to the material.
  101070. * @param world The world matrix to bind.
  101071. */
  101072. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101073. this._activeEffect.setMatrix("world", world);
  101074. };
  101075. /**
  101076. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101077. * @param world The world matrix to bind.
  101078. * @param subMesh The submesh to bind for.
  101079. */
  101080. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101081. var scene = this.getScene();
  101082. var defines = subMesh._materialDefines;
  101083. if (!defines) {
  101084. return;
  101085. }
  101086. var effect = subMesh.effect;
  101087. if (!effect) {
  101088. return;
  101089. }
  101090. this._activeEffect = effect;
  101091. // Matrices
  101092. this.bindOnlyWorldMatrix(world);
  101093. // Bones
  101094. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101095. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101096. if (mustRebind) {
  101097. this._uniformBuffer.bindToEffect(effect, "Material");
  101098. this.bindViewProjection(effect);
  101099. var reflectionTexture = this._reflectionTexture;
  101100. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101101. // Texture uniforms
  101102. if (scene.texturesEnabled) {
  101103. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101104. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101105. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101106. }
  101107. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101108. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101109. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101110. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101111. }
  101112. }
  101113. if (this.shadowLevel > 0) {
  101114. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101115. }
  101116. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101117. // Point size
  101118. if (this.pointsCloud) {
  101119. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101120. }
  101121. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101122. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101123. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101124. }
  101125. else {
  101126. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101127. }
  101128. }
  101129. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101130. // Textures
  101131. if (scene.texturesEnabled) {
  101132. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101133. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101134. }
  101135. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101136. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101137. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101138. }
  101139. else if (!defines.REFLECTIONBLUR) {
  101140. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101141. }
  101142. else {
  101143. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101144. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101145. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101146. }
  101147. if (defines.REFLECTIONFRESNEL) {
  101148. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101149. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101150. }
  101151. }
  101152. }
  101153. // Clip plane
  101154. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101155. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101156. }
  101157. if (mustRebind || !this.isFrozen) {
  101158. if (scene.lightsEnabled) {
  101159. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101160. }
  101161. // View
  101162. this.bindView(effect);
  101163. // Fog
  101164. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101165. // image processing
  101166. if (this._imageProcessingConfiguration) {
  101167. this._imageProcessingConfiguration.bind(this._activeEffect);
  101168. }
  101169. }
  101170. this._uniformBuffer.update();
  101171. this._afterBind(mesh, this._activeEffect);
  101172. };
  101173. /**
  101174. * Dispose the material.
  101175. * @param forceDisposeEffect Force disposal of the associated effect.
  101176. * @param forceDisposeTextures Force disposal of the associated textures.
  101177. */
  101178. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101179. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101180. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101181. if (forceDisposeTextures) {
  101182. if (this.diffuseTexture) {
  101183. this.diffuseTexture.dispose();
  101184. }
  101185. if (this.reflectionTexture) {
  101186. this.reflectionTexture.dispose();
  101187. }
  101188. }
  101189. this._renderTargets.dispose();
  101190. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101191. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101192. }
  101193. _super.prototype.dispose.call(this, forceDisposeEffect);
  101194. };
  101195. /**
  101196. * Clones the material.
  101197. * @param name The cloned name.
  101198. * @returns The cloned material.
  101199. */
  101200. BackgroundMaterial.prototype.clone = function (name) {
  101201. var _this = this;
  101202. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101203. };
  101204. /**
  101205. * Serializes the current material to its JSON representation.
  101206. * @returns The JSON representation.
  101207. */
  101208. BackgroundMaterial.prototype.serialize = function () {
  101209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101210. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101211. return serializationObject;
  101212. };
  101213. /**
  101214. * Gets the class name of the material
  101215. * @returns "BackgroundMaterial"
  101216. */
  101217. BackgroundMaterial.prototype.getClassName = function () {
  101218. return "BackgroundMaterial";
  101219. };
  101220. /**
  101221. * Parse a JSON input to create back a background material.
  101222. * @param source The JSON data to parse
  101223. * @param scene The scene to create the parsed material in
  101224. * @param rootUrl The root url of the assets the material depends upon
  101225. * @returns the instantiated BackgroundMaterial.
  101226. */
  101227. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101228. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101229. };
  101230. /**
  101231. * Standard reflectance value at parallel view angle.
  101232. */
  101233. BackgroundMaterial.StandardReflectance0 = 0.05;
  101234. /**
  101235. * Standard reflectance value at grazing angle.
  101236. */
  101237. BackgroundMaterial.StandardReflectance90 = 0.5;
  101238. __decorate([
  101239. BABYLON.serializeAsColor3()
  101240. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101241. __decorate([
  101242. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101243. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101244. __decorate([
  101245. BABYLON.serializeAsColor3()
  101246. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101247. __decorate([
  101248. BABYLON.serialize()
  101249. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101250. __decorate([
  101251. BABYLON.serialize()
  101252. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101253. __decorate([
  101254. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101255. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101256. __decorate([
  101257. BABYLON.serializeAsTexture()
  101258. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101259. __decorate([
  101260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101261. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101262. __decorate([
  101263. BABYLON.serialize()
  101264. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  101265. __decorate([
  101266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101267. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  101268. __decorate([
  101269. BABYLON.serializeAsTexture()
  101270. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  101271. __decorate([
  101272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101273. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  101274. __decorate([
  101275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101276. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  101277. __decorate([
  101278. BABYLON.serialize()
  101279. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  101280. __decorate([
  101281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101282. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  101283. __decorate([
  101284. BABYLON.serializeAsVector3()
  101285. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101286. __decorate([
  101287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101288. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101289. __decorate([
  101290. BABYLON.serialize()
  101291. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101292. __decorate([
  101293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101294. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101295. __decorate([
  101296. BABYLON.serialize()
  101297. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101298. __decorate([
  101299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101300. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101301. __decorate([
  101302. BABYLON.serialize()
  101303. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101304. __decorate([
  101305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101306. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101307. __decorate([
  101308. BABYLON.serialize()
  101309. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101310. __decorate([
  101311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101312. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101313. __decorate([
  101314. BABYLON.serialize()
  101315. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101316. __decorate([
  101317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101318. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101319. __decorate([
  101320. BABYLON.serialize()
  101321. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101322. __decorate([
  101323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101324. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101325. __decorate([
  101326. BABYLON.serialize()
  101327. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101328. __decorate([
  101329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101330. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101331. __decorate([
  101332. BABYLON.serialize()
  101333. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101334. __decorate([
  101335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101336. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101337. __decorate([
  101338. BABYLON.serialize()
  101339. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101340. __decorate([
  101341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101342. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101343. __decorate([
  101344. BABYLON.serializeAsImageProcessingConfiguration()
  101345. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101346. return BackgroundMaterial;
  101347. }(BABYLON.PushMaterial));
  101348. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101349. })(BABYLON || (BABYLON = {}));
  101350. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101351. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101352. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101353. s = arguments[i];
  101354. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101355. t[p] = s[p];
  101356. }
  101357. return t;
  101358. };
  101359. var BABYLON;
  101360. (function (BABYLON) {
  101361. /**
  101362. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101363. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101364. * It also helps with the default setup of your imageProcessing configuration.
  101365. */
  101366. var EnvironmentHelper = /** @class */ (function () {
  101367. /**
  101368. * constructor
  101369. * @param options
  101370. * @param scene The scene to add the material to
  101371. */
  101372. function EnvironmentHelper(options, scene) {
  101373. var _this = this;
  101374. this._errorHandler = function (message, exception) {
  101375. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101376. };
  101377. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101378. this._scene = scene;
  101379. this.onErrorObservable = new BABYLON.Observable();
  101380. this._setupBackground();
  101381. this._setupImageProcessing();
  101382. }
  101383. /**
  101384. * Creates the default options for the helper.
  101385. */
  101386. EnvironmentHelper._getDefaultOptions = function () {
  101387. return {
  101388. createGround: true,
  101389. groundSize: 15,
  101390. groundTexture: this._groundTextureCDNUrl,
  101391. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101392. groundOpacity: 0.9,
  101393. enableGroundShadow: true,
  101394. groundShadowLevel: 0.5,
  101395. enableGroundMirror: false,
  101396. groundMirrorSizeRatio: 0.3,
  101397. groundMirrorBlurKernel: 64,
  101398. groundMirrorAmount: 1,
  101399. groundMirrorFresnelWeight: 1,
  101400. groundMirrorFallOffDistance: 0,
  101401. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101402. groundYBias: 0.00001,
  101403. createSkybox: true,
  101404. skyboxSize: 20,
  101405. skyboxTexture: this._skyboxTextureCDNUrl,
  101406. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101407. backgroundYRotation: 0,
  101408. sizeAuto: true,
  101409. rootPosition: BABYLON.Vector3.Zero(),
  101410. setupImageProcessing: true,
  101411. environmentTexture: this._environmentTextureCDNUrl,
  101412. cameraExposure: 0.8,
  101413. cameraContrast: 1.2,
  101414. toneMappingEnabled: true,
  101415. };
  101416. };
  101417. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101418. /**
  101419. * Gets the root mesh created by the helper.
  101420. */
  101421. get: function () {
  101422. return this._rootMesh;
  101423. },
  101424. enumerable: true,
  101425. configurable: true
  101426. });
  101427. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101428. /**
  101429. * Gets the skybox created by the helper.
  101430. */
  101431. get: function () {
  101432. return this._skybox;
  101433. },
  101434. enumerable: true,
  101435. configurable: true
  101436. });
  101437. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101438. /**
  101439. * Gets the skybox texture created by the helper.
  101440. */
  101441. get: function () {
  101442. return this._skyboxTexture;
  101443. },
  101444. enumerable: true,
  101445. configurable: true
  101446. });
  101447. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101448. /**
  101449. * Gets the skybox material created by the helper.
  101450. */
  101451. get: function () {
  101452. return this._skyboxMaterial;
  101453. },
  101454. enumerable: true,
  101455. configurable: true
  101456. });
  101457. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101458. /**
  101459. * Gets the ground mesh created by the helper.
  101460. */
  101461. get: function () {
  101462. return this._ground;
  101463. },
  101464. enumerable: true,
  101465. configurable: true
  101466. });
  101467. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101468. /**
  101469. * Gets the ground texture created by the helper.
  101470. */
  101471. get: function () {
  101472. return this._groundTexture;
  101473. },
  101474. enumerable: true,
  101475. configurable: true
  101476. });
  101477. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101478. /**
  101479. * Gets the ground mirror created by the helper.
  101480. */
  101481. get: function () {
  101482. return this._groundMirror;
  101483. },
  101484. enumerable: true,
  101485. configurable: true
  101486. });
  101487. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101488. /**
  101489. * Gets the ground mirror render list to helps pushing the meshes
  101490. * you wish in the ground reflection.
  101491. */
  101492. get: function () {
  101493. if (this._groundMirror) {
  101494. return this._groundMirror.renderList;
  101495. }
  101496. return null;
  101497. },
  101498. enumerable: true,
  101499. configurable: true
  101500. });
  101501. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101502. /**
  101503. * Gets the ground material created by the helper.
  101504. */
  101505. get: function () {
  101506. return this._groundMaterial;
  101507. },
  101508. enumerable: true,
  101509. configurable: true
  101510. });
  101511. /**
  101512. * Updates the background according to the new options
  101513. * @param options
  101514. */
  101515. EnvironmentHelper.prototype.updateOptions = function (options) {
  101516. var newOptions = __assign({}, this._options, options);
  101517. if (this._ground && !newOptions.createGround) {
  101518. this._ground.dispose();
  101519. this._ground = null;
  101520. }
  101521. if (this._groundMaterial && !newOptions.createGround) {
  101522. this._groundMaterial.dispose();
  101523. this._groundMaterial = null;
  101524. }
  101525. if (this._groundTexture) {
  101526. if (this._options.groundTexture != newOptions.groundTexture) {
  101527. this._groundTexture.dispose();
  101528. this._groundTexture = null;
  101529. }
  101530. }
  101531. if (this._skybox && !newOptions.createSkybox) {
  101532. this._skybox.dispose();
  101533. this._skybox = null;
  101534. }
  101535. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101536. this._skyboxMaterial.dispose();
  101537. this._skyboxMaterial = null;
  101538. }
  101539. if (this._skyboxTexture) {
  101540. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101541. this._skyboxTexture.dispose();
  101542. this._skyboxTexture = null;
  101543. }
  101544. }
  101545. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101546. this._groundMirror.dispose();
  101547. this._groundMirror = null;
  101548. }
  101549. if (this._scene.environmentTexture) {
  101550. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101551. this._scene.environmentTexture.dispose();
  101552. }
  101553. }
  101554. this._options = newOptions;
  101555. this._setupBackground();
  101556. this._setupImageProcessing();
  101557. };
  101558. /**
  101559. * Sets the primary color of all the available elements.
  101560. * @param color the main color to affect to the ground and the background
  101561. */
  101562. EnvironmentHelper.prototype.setMainColor = function (color) {
  101563. if (this.groundMaterial) {
  101564. this.groundMaterial.primaryColor = color;
  101565. }
  101566. if (this.skyboxMaterial) {
  101567. this.skyboxMaterial.primaryColor = color;
  101568. }
  101569. if (this.groundMirror) {
  101570. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101571. }
  101572. };
  101573. /**
  101574. * Setup the image processing according to the specified options.
  101575. */
  101576. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101577. if (this._options.setupImageProcessing) {
  101578. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101579. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101580. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101581. this._setupEnvironmentTexture();
  101582. }
  101583. };
  101584. /**
  101585. * Setup the environment texture according to the specified options.
  101586. */
  101587. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101588. if (this._scene.environmentTexture) {
  101589. return;
  101590. }
  101591. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101592. this._scene.environmentTexture = this._options.environmentTexture;
  101593. return;
  101594. }
  101595. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101596. this._scene.environmentTexture = environmentTexture;
  101597. };
  101598. /**
  101599. * Setup the background according to the specified options.
  101600. */
  101601. EnvironmentHelper.prototype._setupBackground = function () {
  101602. if (!this._rootMesh) {
  101603. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101604. }
  101605. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101606. var sceneSize = this._getSceneSize();
  101607. if (this._options.createGround) {
  101608. this._setupGround(sceneSize);
  101609. this._setupGroundMaterial();
  101610. this._setupGroundDiffuseTexture();
  101611. if (this._options.enableGroundMirror) {
  101612. this._setupGroundMirrorTexture(sceneSize);
  101613. }
  101614. this._setupMirrorInGroundMaterial();
  101615. }
  101616. if (this._options.createSkybox) {
  101617. this._setupSkybox(sceneSize);
  101618. this._setupSkyboxMaterial();
  101619. this._setupSkyboxReflectionTexture();
  101620. }
  101621. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101622. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101623. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101624. };
  101625. /**
  101626. * Get the scene sizes according to the setup.
  101627. */
  101628. EnvironmentHelper.prototype._getSceneSize = function () {
  101629. var _this = this;
  101630. var groundSize = this._options.groundSize;
  101631. var skyboxSize = this._options.skyboxSize;
  101632. var rootPosition = this._options.rootPosition;
  101633. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101634. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101635. }
  101636. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101637. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101638. });
  101639. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101640. if (this._options.sizeAuto) {
  101641. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101642. this._scene.activeCamera.upperRadiusLimit) {
  101643. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101644. skyboxSize = groundSize;
  101645. }
  101646. var sceneDiagonalLenght = sceneDiagonal.length();
  101647. if (sceneDiagonalLenght > groundSize) {
  101648. groundSize = sceneDiagonalLenght * 2;
  101649. skyboxSize = groundSize;
  101650. }
  101651. // 10 % bigger.
  101652. groundSize *= 1.1;
  101653. skyboxSize *= 1.5;
  101654. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101655. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101656. }
  101657. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101658. };
  101659. /**
  101660. * Setup the ground according to the specified options.
  101661. */
  101662. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101663. var _this = this;
  101664. if (!this._ground || this._ground.isDisposed()) {
  101665. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101666. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101667. this._ground.parent = this._rootMesh;
  101668. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101669. }
  101670. this._ground.receiveShadows = this._options.enableGroundShadow;
  101671. };
  101672. /**
  101673. * Setup the ground material according to the specified options.
  101674. */
  101675. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101676. if (!this._groundMaterial) {
  101677. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101678. }
  101679. this._groundMaterial.alpha = this._options.groundOpacity;
  101680. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101681. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101682. this._groundMaterial.primaryColor = this._options.groundColor;
  101683. this._groundMaterial.useRGBColor = false;
  101684. this._groundMaterial.enableNoise = true;
  101685. if (this._ground) {
  101686. this._ground.material = this._groundMaterial;
  101687. }
  101688. };
  101689. /**
  101690. * Setup the ground diffuse texture according to the specified options.
  101691. */
  101692. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101693. if (!this._groundMaterial) {
  101694. return;
  101695. }
  101696. if (this._groundTexture) {
  101697. return;
  101698. }
  101699. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101700. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101701. return;
  101702. }
  101703. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101704. diffuseTexture.gammaSpace = false;
  101705. diffuseTexture.hasAlpha = true;
  101706. this._groundMaterial.diffuseTexture = diffuseTexture;
  101707. };
  101708. /**
  101709. * Setup the ground mirror texture according to the specified options.
  101710. */
  101711. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101712. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101713. if (!this._groundMirror) {
  101714. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101715. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101716. this._groundMirror.anisotropicFilteringLevel = 1;
  101717. this._groundMirror.wrapU = wrapping;
  101718. this._groundMirror.wrapV = wrapping;
  101719. this._groundMirror.gammaSpace = false;
  101720. if (this._groundMirror.renderList) {
  101721. for (var i = 0; i < this._scene.meshes.length; i++) {
  101722. var mesh = this._scene.meshes[i];
  101723. if (mesh !== this._ground &&
  101724. mesh !== this._skybox &&
  101725. mesh !== this._rootMesh) {
  101726. this._groundMirror.renderList.push(mesh);
  101727. }
  101728. }
  101729. }
  101730. }
  101731. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101732. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101733. };
  101734. /**
  101735. * Setup the ground to receive the mirror texture.
  101736. */
  101737. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101738. if (this._groundMaterial) {
  101739. this._groundMaterial.reflectionTexture = this._groundMirror;
  101740. this._groundMaterial.reflectionFresnel = true;
  101741. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101742. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101743. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101744. }
  101745. };
  101746. /**
  101747. * Setup the skybox according to the specified options.
  101748. */
  101749. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101750. var _this = this;
  101751. if (!this._skybox || this._skybox.isDisposed()) {
  101752. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101753. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101754. }
  101755. this._skybox.parent = this._rootMesh;
  101756. };
  101757. /**
  101758. * Setup the skybox material according to the specified options.
  101759. */
  101760. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101761. if (!this._skybox) {
  101762. return;
  101763. }
  101764. if (!this._skyboxMaterial) {
  101765. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101766. }
  101767. this._skyboxMaterial.useRGBColor = false;
  101768. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101769. this._skyboxMaterial.enableNoise = true;
  101770. this._skybox.material = this._skyboxMaterial;
  101771. };
  101772. /**
  101773. * Setup the skybox reflection texture according to the specified options.
  101774. */
  101775. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101776. if (!this._skyboxMaterial) {
  101777. return;
  101778. }
  101779. if (this._skyboxTexture) {
  101780. return;
  101781. }
  101782. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101783. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101784. return;
  101785. }
  101786. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101787. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101788. this._skyboxTexture.gammaSpace = false;
  101789. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101790. };
  101791. /**
  101792. * Dispose all the elements created by the Helper.
  101793. */
  101794. EnvironmentHelper.prototype.dispose = function () {
  101795. if (this._groundMaterial) {
  101796. this._groundMaterial.dispose(true, true);
  101797. }
  101798. if (this._skyboxMaterial) {
  101799. this._skyboxMaterial.dispose(true, true);
  101800. }
  101801. this._rootMesh.dispose(false);
  101802. };
  101803. /**
  101804. * Default ground texture URL.
  101805. */
  101806. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101807. /**
  101808. * Default skybox texture URL.
  101809. */
  101810. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101811. /**
  101812. * Default environment texture URL.
  101813. */
  101814. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101815. return EnvironmentHelper;
  101816. }());
  101817. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101818. })(BABYLON || (BABYLON = {}));
  101819. //# sourceMappingURL=babylon.environmentHelper.js.map
  101820. var BABYLON;
  101821. (function (BABYLON) {
  101822. /**
  101823. * This class is made for on one-liner static method to help creating particle systems.
  101824. */
  101825. var ParticleHelper = /** @class */ (function () {
  101826. function ParticleHelper() {
  101827. }
  101828. /**
  101829. * This is the main static method (one-liner) of this helper to create different particle systems.
  101830. * @param type This string represents the type to the particle system to create
  101831. * @param emitter The object where the particle system will start to emit from.
  101832. * @param scene The scene where the particle system should live.
  101833. * @param gpu If the system will use gpu.
  101834. * @returns the ParticleSystem created.
  101835. */
  101836. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101837. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101838. if (gpu === void 0) { gpu = false; }
  101839. return new Promise(function (resolve, reject) {
  101840. if (!scene) {
  101841. scene = BABYLON.Engine.LastCreatedScene;
  101842. ;
  101843. }
  101844. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101845. return reject("Particle system with GPU is not supported.");
  101846. }
  101847. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101848. var newData = JSON.parse(data.toString());
  101849. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101850. }, undefined, undefined, undefined, function (req, exception) {
  101851. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101852. });
  101853. });
  101854. };
  101855. /**
  101856. * Static function used to create a new particle system from a IParticleSystemData
  101857. * @param data defines the source data
  101858. * @param scene defines the hosting scene
  101859. * @param emitter defines the particle emitter
  101860. * @returns a new ParticleSystem based on referenced data
  101861. */
  101862. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101863. // Create a particle system
  101864. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101865. // Where the particles come from
  101866. system.emitter = emitter; // the starting object, the emitter
  101867. ParticleHelper.UpdateSystem(system, data, scene);
  101868. return system;
  101869. };
  101870. /**
  101871. * Static function used to update a particle system from a IParticleSystemData
  101872. * @param system defines the particle system to update
  101873. * @param data defines the source data
  101874. * @param scene defines the hosting scene
  101875. */
  101876. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101877. // Texture of each particle
  101878. if (data.textureFile) {
  101879. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101880. }
  101881. // Colors of all particles
  101882. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101883. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101884. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101885. // Size of each particle (random between...
  101886. system.minSize = data.minSize;
  101887. system.maxSize = data.maxSize;
  101888. system.minScaleX = data.minScaleX;
  101889. system.maxScaleX = data.maxScaleX;
  101890. system.minScaleY = data.minScaleY;
  101891. system.maxScaleY = data.maxScaleY;
  101892. // Life time of each particle (random between...
  101893. system.minLifeTime = data.minLifeTime;
  101894. system.maxLifeTime = data.maxLifeTime;
  101895. // Emission rate
  101896. system.emitRate = data.emitRate;
  101897. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101898. system.blendMode = data.blendMode;
  101899. // Set the gravity of all particles
  101900. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101901. // Angular speed, in radians
  101902. system.minAngularSpeed = data.minAngularSpeed;
  101903. system.maxAngularSpeed = data.maxAngularSpeed;
  101904. // Speed
  101905. system.minEmitPower = data.minEmitPower;
  101906. system.maxEmitPower = data.maxEmitPower;
  101907. system.updateSpeed = data.updateSpeed;
  101908. switch (data.emitterType) {
  101909. case "box":
  101910. if (!data.direction1 || !data.direction2) {
  101911. throw new Error("Directions are missing in this particle system.");
  101912. }
  101913. if (!data.minEmitBox || !data.maxEmitBox) {
  101914. throw new Error("EmitBox is missing in this particle system.");
  101915. }
  101916. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101917. break;
  101918. case "sphere":
  101919. system.createSphereEmitter(data.radius);
  101920. break;
  101921. case "directed_sphere":
  101922. if (!data.direction1 || !data.direction2) {
  101923. throw new Error("Directions are missing in this particle system.");
  101924. }
  101925. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101926. break;
  101927. case "cone":
  101928. system.createConeEmitter(data.radius, data.angle);
  101929. break;
  101930. default:
  101931. break;
  101932. }
  101933. };
  101934. /**
  101935. * Static function used to export a particle system to a IParticleSystemData variable.
  101936. * Please note that texture file name is not exported and must be added manually
  101937. * @param system defines the particle system to export
  101938. */
  101939. ParticleHelper.ExportSystem = function (system) {
  101940. var outData = {};
  101941. // Colors of all particles
  101942. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101943. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101944. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101945. // Size of each particle (random between...
  101946. outData.minSize = system.minSize;
  101947. outData.maxSize = system.maxSize;
  101948. outData.minScaleX = system.minScaleX;
  101949. outData.maxScaleX = system.maxScaleX;
  101950. outData.minScaleY = system.minScaleY;
  101951. outData.maxScaleY = system.maxScaleY;
  101952. // Life time of each particle (random between...
  101953. outData.minLifeTime = system.minLifeTime;
  101954. outData.maxLifeTime = system.maxLifeTime;
  101955. // Emission rate
  101956. outData.emitRate = system.emitRate;
  101957. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101958. outData.blendMode = system.blendMode;
  101959. // Set the gravity of all particles
  101960. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101961. // Angular speed, in radians
  101962. outData.minAngularSpeed = system.minAngularSpeed;
  101963. outData.maxAngularSpeed = system.maxAngularSpeed;
  101964. // Speed
  101965. outData.minEmitPower = system.minEmitPower;
  101966. outData.maxEmitPower = system.maxEmitPower;
  101967. outData.updateSpeed = system.updateSpeed;
  101968. switch (system.particleEmitterType.getClassName()) {
  101969. case "BoxEmitter":
  101970. outData.emitterType = "box";
  101971. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101972. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101973. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101974. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101975. break;
  101976. case "SphereParticleEmitter":
  101977. outData.emitterType = "sphere";
  101978. outData.radius = system.particleEmitterType.radius;
  101979. break;
  101980. case "SphereDirectedParticleEmitter":
  101981. outData.emitterType = "directed_sphere";
  101982. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101983. outData.radius = sphereDirectedParticleEmitter.radius;
  101984. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101985. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101986. break;
  101987. case "ConeEmitter":
  101988. outData.emitterType = "cone";
  101989. outData.radius = system.particleEmitterType.radius;
  101990. outData.angle = system.particleEmitterType.angle;
  101991. break;
  101992. default:
  101993. break;
  101994. }
  101995. return outData;
  101996. };
  101997. /**
  101998. * Base Assets URL.
  101999. */
  102000. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  102001. return ParticleHelper;
  102002. }());
  102003. BABYLON.ParticleHelper = ParticleHelper;
  102004. })(BABYLON || (BABYLON = {}));
  102005. //# sourceMappingURL=babylon.particleHelper.js.map
  102006. var BABYLON;
  102007. (function (BABYLON) {
  102008. /**
  102009. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102010. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102011. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102012. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102013. */
  102014. var VideoDome = /** @class */ (function (_super) {
  102015. __extends(VideoDome, _super);
  102016. /**
  102017. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102018. * @param name Element's name, child elements will append suffixes for their own names.
  102019. * @param urlsOrVideo defines the url(s) or the video element to use
  102020. * @param options An object containing optional or exposed sub element properties
  102021. */
  102022. function VideoDome(name, urlsOrVideo, options, scene) {
  102023. var _this = _super.call(this, name, scene) || this;
  102024. _this._useDirectMapping = false;
  102025. // set defaults and manage values
  102026. name = name || "videoDome";
  102027. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102028. options.clickToPlay = Boolean(options.clickToPlay);
  102029. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102030. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102031. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102032. if (options.useDirectMapping === undefined) {
  102033. _this._useDirectMapping = true;
  102034. }
  102035. else {
  102036. _this._useDirectMapping = options.useDirectMapping;
  102037. }
  102038. // create
  102039. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102040. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102041. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102042. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102043. // configure material
  102044. material.useEquirectangularFOV = true;
  102045. material.fovMultiplier = 1.0;
  102046. material.opacityFresnel = false;
  102047. if (_this._useDirectMapping) {
  102048. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102049. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102050. material.diffuseTexture = texture;
  102051. }
  102052. else {
  102053. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102054. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102055. material.reflectionTexture = texture;
  102056. }
  102057. // configure mesh
  102058. _this._mesh.material = material;
  102059. _this._mesh.parent = _this;
  102060. // optional configuration
  102061. if (options.clickToPlay) {
  102062. scene.onPointerUp = function () {
  102063. _this._videoTexture.video.play();
  102064. };
  102065. }
  102066. return _this;
  102067. }
  102068. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102069. /**
  102070. * Gets the video texture being displayed on the sphere
  102071. */
  102072. get: function () {
  102073. return this._videoTexture;
  102074. },
  102075. enumerable: true,
  102076. configurable: true
  102077. });
  102078. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102079. /**
  102080. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102081. * Also see the options.resolution property.
  102082. */
  102083. get: function () {
  102084. return this._material.fovMultiplier;
  102085. },
  102086. set: function (value) {
  102087. this._material.fovMultiplier = value;
  102088. },
  102089. enumerable: true,
  102090. configurable: true
  102091. });
  102092. /**
  102093. * Releases resources associated with this node.
  102094. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102095. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102096. */
  102097. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102098. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102099. this._videoTexture.dispose();
  102100. this._mesh.dispose();
  102101. this._material.dispose();
  102102. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102103. };
  102104. return VideoDome;
  102105. }(BABYLON.Node));
  102106. BABYLON.VideoDome = VideoDome;
  102107. })(BABYLON || (BABYLON = {}));
  102108. //# sourceMappingURL=babylon.videoDome.js.map
  102109. var BABYLON;
  102110. (function (BABYLON) {
  102111. /**
  102112. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102113. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102114. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102115. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102116. */
  102117. var PhotoDome = /** @class */ (function (_super) {
  102118. __extends(PhotoDome, _super);
  102119. /**
  102120. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102121. * @param name Element's name, child elements will append suffixes for their own names.
  102122. * @param urlsOfPhoto define the url of the photo to display
  102123. * @param options An object containing optional or exposed sub element properties
  102124. */
  102125. function PhotoDome(name, urlOfPhoto, options, scene) {
  102126. var _this = _super.call(this, name, scene) || this;
  102127. _this._useDirectMapping = false;
  102128. // set defaults and manage values
  102129. name = name || "photoDome";
  102130. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102131. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102132. if (options.useDirectMapping === undefined) {
  102133. _this._useDirectMapping = true;
  102134. }
  102135. else {
  102136. _this._useDirectMapping = options.useDirectMapping;
  102137. }
  102138. // create
  102139. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102140. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102141. // configure material
  102142. material.opacityFresnel = false;
  102143. material.useEquirectangularFOV = true;
  102144. material.fovMultiplier = 1.0;
  102145. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102146. // configure mesh
  102147. _this._mesh.material = material;
  102148. _this._mesh.parent = _this;
  102149. return _this;
  102150. }
  102151. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102152. /**
  102153. * Gets or sets the texture being displayed on the sphere
  102154. */
  102155. get: function () {
  102156. return this._photoTexture;
  102157. },
  102158. set: function (value) {
  102159. if (this._photoTexture === value) {
  102160. return;
  102161. }
  102162. this._photoTexture = value;
  102163. if (this._useDirectMapping) {
  102164. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102165. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102166. this._material.diffuseTexture = this._photoTexture;
  102167. }
  102168. else {
  102169. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102170. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102171. this._material.reflectionTexture = this._photoTexture;
  102172. }
  102173. },
  102174. enumerable: true,
  102175. configurable: true
  102176. });
  102177. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102178. /**
  102179. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102180. * Also see the options.resolution property.
  102181. */
  102182. get: function () {
  102183. return this._material.fovMultiplier;
  102184. },
  102185. set: function (value) {
  102186. this._material.fovMultiplier = value;
  102187. },
  102188. enumerable: true,
  102189. configurable: true
  102190. });
  102191. /**
  102192. * Releases resources associated with this node.
  102193. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102194. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102195. */
  102196. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102197. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102198. this._photoTexture.dispose();
  102199. this._mesh.dispose();
  102200. this._material.dispose();
  102201. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102202. };
  102203. return PhotoDome;
  102204. }(BABYLON.Node));
  102205. BABYLON.PhotoDome = PhotoDome;
  102206. })(BABYLON || (BABYLON = {}));
  102207. //# sourceMappingURL=babylon.photoDome.js.map
  102208. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nvec3 worldPos=position+alignedCorner; \ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=offset*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\n#endif \nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\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 (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  102209. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  102210. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  102211. globalObject["BABYLON"] = BABYLON;
  102212. //backwards compatibility
  102213. if(typeof earcut !== 'undefined') {
  102214. globalObject["Earcut"] = {
  102215. earcut: earcut
  102216. };
  102217. }
  102218. return BABYLON;
  102219. });
  102220. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  102221. /***/ }),
  102222. /* 1 */
  102223. /***/ (function(module, exports, __webpack_require__) {
  102224. "use strict";
  102225. Object.defineProperty(exports, "__esModule", { value: true });
  102226. var deepmerge = __webpack_require__(21);
  102227. var expDm = deepmerge['default'];
  102228. exports.deepmerge = expDm;
  102229. /**
  102230. * Is the provided string a URL?
  102231. *
  102232. * @param urlToCheck the url to inspect
  102233. */
  102234. function isUrl(urlToCheck) {
  102235. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  102236. return true;
  102237. }
  102238. return false;
  102239. }
  102240. exports.isUrl = isUrl;
  102241. /**
  102242. * Convert a string from kebab-case to camelCase
  102243. * @param s string to convert
  102244. */
  102245. function kebabToCamel(s) {
  102246. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  102247. }
  102248. exports.kebabToCamel = kebabToCamel;
  102249. //https://gist.github.com/youssman/745578062609e8acac9f
  102250. /**
  102251. * Convert a string from camelCase to kebab-case
  102252. * @param str string to convert
  102253. */
  102254. function camelToKebab(str) {
  102255. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  102256. }
  102257. exports.camelToKebab = camelToKebab;
  102258. /**
  102259. * This will extend an object with configuration values.
  102260. * What it practically does it take the keys from the configuration and set them on the object.
  102261. * I the configuration is a tree, it will traverse into the tree.
  102262. * @param object the object to extend
  102263. * @param config the configuration object that will extend the object
  102264. */
  102265. function extendClassWithConfig(object, config) {
  102266. if (!config)
  102267. return;
  102268. Object.keys(config).forEach(function (key) {
  102269. if (key in object && typeof object[key] !== 'function') {
  102270. // if (typeof object[key] === 'function') return;
  102271. // if it is an object, iterate internally until reaching basic types
  102272. if (typeof object[key] === 'object') {
  102273. extendClassWithConfig(object[key], config[key]);
  102274. }
  102275. else {
  102276. if (config[key] !== undefined) {
  102277. object[key] = config[key];
  102278. }
  102279. }
  102280. }
  102281. });
  102282. }
  102283. exports.extendClassWithConfig = extendClassWithConfig;
  102284. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQ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FJLE9BQU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  102285. /***/ }),
  102286. /* 2 */
  102287. /***/ (function(module, exports, __webpack_require__) {
  102288. "use strict";
  102289. function __export(m) {
  102290. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  102291. }
  102292. Object.defineProperty(exports, "__esModule", { value: true });
  102293. __export(__webpack_require__(31));
  102294. __export(__webpack_require__(33));
  102295. __export(__webpack_require__(39));
  102296. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  102297. /***/ }),
  102298. /* 3 */
  102299. /***/ (function(module, exports, __webpack_require__) {
  102300. "use strict";
  102301. Object.defineProperty(exports, "__esModule", { value: true });
  102302. var babylonjs_1 = __webpack_require__(0);
  102303. var _1 = __webpack_require__(1);
  102304. /**
  102305. * This is a simple HTML mapper.
  102306. * This mapper parses a single HTML element and returns the configuration from its attributes.
  102307. * it parses numbers and boolean values to the corresponding variable types.
  102308. * The following HTML element:
  102309. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  102310. *
  102311. * {
  102312. * test: 1, //a number!
  102313. * randomFlag: boolean, //camelCase and boolean
  102314. * a: {
  102315. * string: {
  102316. * object: "test" //dot-separated object levels
  102317. * }
  102318. * }
  102319. * }
  102320. */
  102321. var HTMLMapper = /** @class */ (function () {
  102322. function HTMLMapper() {
  102323. }
  102324. /**
  102325. * Map a specific element and get configuration from it
  102326. * @param element the HTML element to analyze.
  102327. */
  102328. HTMLMapper.prototype.map = function (element) {
  102329. var config = {};
  102330. var _loop_1 = function (attrIdx) {
  102331. var attr = element.attributes.item(attrIdx);
  102332. if (!attr) {
  102333. return "continue";
  102334. }
  102335. // map "object.property" to the right configuration place.
  102336. var split = attr.nodeName.split('.');
  102337. split.reduce(function (currentConfig, key, idx) {
  102338. //convert html-style to json-style
  102339. var camelKey = _1.kebabToCamel(key);
  102340. if (idx === split.length - 1) {
  102341. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  102342. if (val === "true") {
  102343. val = true;
  102344. }
  102345. else if (val === "false") {
  102346. val = false;
  102347. }
  102348. else if (val === "undefined") {
  102349. val = undefined;
  102350. }
  102351. else if (val === "null") {
  102352. val = null;
  102353. }
  102354. else {
  102355. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  102356. if (isnum) {
  102357. var number = parseFloat(val);
  102358. if (!isNaN(number)) {
  102359. val = number;
  102360. }
  102361. }
  102362. }
  102363. currentConfig[camelKey] = val;
  102364. }
  102365. else {
  102366. currentConfig[camelKey] = currentConfig[camelKey] || {};
  102367. }
  102368. return currentConfig[camelKey];
  102369. }, config);
  102370. };
  102371. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  102372. _loop_1(attrIdx);
  102373. }
  102374. return config;
  102375. };
  102376. return HTMLMapper;
  102377. }());
  102378. /**
  102379. * A simple string-to-JSON mapper.
  102380. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  102381. */
  102382. var JSONMapper = /** @class */ (function () {
  102383. function JSONMapper() {
  102384. }
  102385. JSONMapper.prototype.map = function (rawSource) {
  102386. return JSON.parse(rawSource);
  102387. };
  102388. return JSONMapper;
  102389. }());
  102390. /**
  102391. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  102392. * DOM elements and attributes.
  102393. */
  102394. var DOMMapper = /** @class */ (function () {
  102395. function DOMMapper() {
  102396. }
  102397. /**
  102398. * The mapping function that will convert HTML data to a viewer configuration object
  102399. * @param baseElement the baseElement from which to start traversing
  102400. * @returns a ViewerCOnfiguration object from the provided HTML Element
  102401. */
  102402. DOMMapper.prototype.map = function (baseElement) {
  102403. var htmlMapper = new HTMLMapper();
  102404. var config = htmlMapper.map(baseElement);
  102405. var traverseChildren = function (element, partConfig) {
  102406. var children = element.children;
  102407. if (children.length) {
  102408. for (var i = 0; i < children.length; ++i) {
  102409. var item = children.item(i);
  102410. // use the HTML Mapper to read configuration from a single element
  102411. var configMapped = htmlMapper.map(item);
  102412. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  102413. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  102414. partConfig[key] = [];
  102415. }
  102416. else {
  102417. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  102418. partConfig.push(configMapped);
  102419. }
  102420. else if (partConfig[key]) {
  102421. //exists already! probably an array
  102422. element.setAttribute('array', 'true');
  102423. var oldItem = partConfig[key];
  102424. partConfig = [oldItem, configMapped];
  102425. }
  102426. else {
  102427. partConfig[key] = configMapped;
  102428. }
  102429. }
  102430. traverseChildren(item, partConfig[key] || configMapped);
  102431. }
  102432. }
  102433. return partConfig;
  102434. };
  102435. traverseChildren(baseElement, config);
  102436. return config;
  102437. };
  102438. return DOMMapper;
  102439. }());
  102440. /**
  102441. * The MapperManager manages the different implemented mappers.
  102442. * It allows the user to register new mappers as well and use them to parse their own configuration data
  102443. */
  102444. var MapperManager = /** @class */ (function () {
  102445. function MapperManager() {
  102446. this._mappers = {
  102447. "html": new HTMLMapper(),
  102448. "json": new JSONMapper(),
  102449. "dom": new DOMMapper()
  102450. };
  102451. }
  102452. /**
  102453. * Get a specific configuration mapper.
  102454. *
  102455. * @param type the name of the mapper to load
  102456. */
  102457. MapperManager.prototype.getMapper = function (type) {
  102458. if (!this._mappers[type]) {
  102459. babylonjs_1.Tools.Error("No mapper defined for " + type);
  102460. }
  102461. return this._mappers[type];
  102462. };
  102463. /**
  102464. * Use this functio to register your own configuration mapper.
  102465. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  102466. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  102467. * @param mapper The implemented mapper
  102468. */
  102469. MapperManager.prototype.registerMapper = function (type, mapper) {
  102470. this._mappers[type] = mapper;
  102471. };
  102472. /**
  102473. * Dispose the mapper manager and all of its mappers.
  102474. */
  102475. MapperManager.prototype.dispose = function () {
  102476. this._mappers = {};
  102477. };
  102478. /**
  102479. * The default mapper is the JSON mapper.
  102480. */
  102481. MapperManager.DefaultMapper = 'json';
  102482. return MapperManager;
  102483. }());
  102484. exports.MapperManager = MapperManager;
  102485. /**
  102486. * mapperManager is a singleton of the type MapperManager.
  102487. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  102488. * or indirectly with using BabylonViewer.disposeAll()
  102489. */
  102490. exports.mapperManager = new MapperManager();
  102491. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwib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EIsTUFBTSxFQUFFLElBQUksVUFBVSxFQUFFO1lBQ3hCLEtBQUssRUFBRSxJQUFJLFNBQVMsRUFBRTtTQUN6QixDQUFBO0lBQ0wsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSxpQ0FBUyxHQUFoQixVQUFpQixJQUFZO1FBQ3pCLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  102492. /***/ }),
  102493. /* 4 */
  102494. /***/ (function(module, exports, __webpack_require__) {
  102495. "use strict";
  102496. Object.defineProperty(exports, "__esModule", { value: true });
  102497. var babylonjs_1 = __webpack_require__(0);
  102498. var ViewerGlobals = /** @class */ (function () {
  102499. function ViewerGlobals() {
  102500. this.disableInit = false;
  102501. this.disableWebGL2Support = false;
  102502. }
  102503. Object.defineProperty(ViewerGlobals.prototype, "version", {
  102504. get: function () {
  102505. return babylonjs_1.Engine.Version;
  102506. },
  102507. enumerable: true,
  102508. configurable: true
  102509. });
  102510. return ViewerGlobals;
  102511. }());
  102512. exports.ViewerGlobals = ViewerGlobals;
  102513. exports.viewerGlobals = new ViewerGlobals();
  102514. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  102515. /***/ }),
  102516. /* 5 */
  102517. /***/ (function(module, exports, __webpack_require__) {
  102518. "use strict";
  102519. Object.defineProperty(exports, "__esModule", { value: true });
  102520. var babylonjs_1 = __webpack_require__(0);
  102521. var modelAnimation_1 = __webpack_require__(23);
  102522. var _1 = __webpack_require__(1);
  102523. /**
  102524. * The current state of the model
  102525. */
  102526. var ModelState;
  102527. (function (ModelState) {
  102528. ModelState[ModelState["INIT"] = 0] = "INIT";
  102529. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  102530. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  102531. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  102532. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  102533. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  102534. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  102535. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  102536. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  102537. /**
  102538. * The viewer model is a container for all assets representing a sngle loaded model.
  102539. */
  102540. var ViewerModel = /** @class */ (function () {
  102541. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  102542. var _this = this;
  102543. this._observablesManager = _observablesManager;
  102544. this._configurationContainer = _configurationContainer;
  102545. /**
  102546. * the list of meshes that are a part of this model
  102547. */
  102548. this._meshes = [];
  102549. /**
  102550. * ParticleSystems connected to this model
  102551. */
  102552. this.particleSystems = [];
  102553. /**
  102554. * Skeletons defined in this model
  102555. */
  102556. this.skeletons = [];
  102557. this._loaderDone = false;
  102558. this._animatables = [];
  102559. this._frameRate = 60;
  102560. this._shadowsRenderedAfterLoad = false;
  102561. this.onLoadedObservable = new babylonjs_1.Observable();
  102562. this.onLoadErrorObservable = new babylonjs_1.Observable();
  102563. this.onLoadProgressObservable = new babylonjs_1.Observable();
  102564. this.onCompleteObservable = new babylonjs_1.Observable();
  102565. this.onAfterConfigure = new babylonjs_1.Observable();
  102566. this.state = ModelState.INIT;
  102567. var scene = this._configurationContainer && this._configurationContainer.scene;
  102568. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  102569. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  102570. this._pivotMesh.parent = this.rootMesh;
  102571. // rotate 180, gltf fun
  102572. this._pivotMesh.rotation.y += Math.PI;
  102573. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102574. this._animations = [];
  102575. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  102576. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  102577. if (this._observablesManager) {
  102578. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  102579. }
  102580. if (this._modelConfiguration.entryAnimation) {
  102581. this.rootMesh.setEnabled(false);
  102582. }
  102583. this.onLoadedObservable.add(function () {
  102584. _this.updateConfiguration(_this._modelConfiguration);
  102585. if (_this._observablesManager) {
  102586. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  102587. }
  102588. _this._initAnimations();
  102589. });
  102590. this.onCompleteObservable.add(function () {
  102591. _this.state = ModelState.COMPLETE;
  102592. });
  102593. }
  102594. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  102595. get: function () {
  102596. return this._shadowsRenderedAfterLoad;
  102597. },
  102598. set: function (rendered) {
  102599. if (!rendered) {
  102600. throw new Error("can only be enabled");
  102601. }
  102602. else {
  102603. this._shadowsRenderedAfterLoad = rendered;
  102604. }
  102605. },
  102606. enumerable: true,
  102607. configurable: true
  102608. });
  102609. ViewerModel.prototype.getViewerId = function () {
  102610. return this._configurationContainer && this._configurationContainer.viewerId;
  102611. };
  102612. Object.defineProperty(ViewerModel.prototype, "enabled", {
  102613. /**
  102614. * Is this model enabled?
  102615. */
  102616. get: function () {
  102617. return this.rootMesh.isEnabled();
  102618. },
  102619. /**
  102620. * Set whether this model is enabled or not.
  102621. */
  102622. set: function (enable) {
  102623. this.rootMesh.setEnabled(enable);
  102624. },
  102625. enumerable: true,
  102626. configurable: true
  102627. });
  102628. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  102629. set: function (done) {
  102630. this._loaderDone = done;
  102631. this._checkCompleteState();
  102632. },
  102633. enumerable: true,
  102634. configurable: true
  102635. });
  102636. ViewerModel.prototype._checkCompleteState = function () {
  102637. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  102638. this._modelComplete();
  102639. }
  102640. };
  102641. /**
  102642. * Add a mesh to this model.
  102643. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  102644. *
  102645. * @param mesh the new mesh to add
  102646. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  102647. */
  102648. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  102649. if (!mesh.parent) {
  102650. mesh.parent = this._pivotMesh;
  102651. }
  102652. mesh.receiveShadows = !!this.configuration.receiveShadows;
  102653. this._meshes.push(mesh);
  102654. if (triggerLoaded) {
  102655. return this.onLoadedObservable.notifyObserversWithPromise(this);
  102656. }
  102657. };
  102658. Object.defineProperty(ViewerModel.prototype, "meshes", {
  102659. /**
  102660. * get the list of meshes (excluding the root mesh)
  102661. */
  102662. get: function () {
  102663. return this._meshes;
  102664. },
  102665. enumerable: true,
  102666. configurable: true
  102667. });
  102668. Object.defineProperty(ViewerModel.prototype, "configuration", {
  102669. /**
  102670. * Get the model's configuration
  102671. */
  102672. get: function () {
  102673. return this._modelConfiguration;
  102674. },
  102675. /**
  102676. * (Re-)set the model's entire configuration
  102677. * @param newConfiguration the new configuration to replace the new one
  102678. */
  102679. set: function (newConfiguration) {
  102680. this._modelConfiguration = newConfiguration;
  102681. this._configureModel();
  102682. },
  102683. enumerable: true,
  102684. configurable: true
  102685. });
  102686. /**
  102687. * Update the current configuration with new values.
  102688. * Configuration will not be overwritten, but merged with the new configuration.
  102689. * Priority is to the new configuration
  102690. * @param newConfiguration the configuration to be merged into the current configuration;
  102691. */
  102692. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  102693. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  102694. this._configureModel();
  102695. };
  102696. ViewerModel.prototype._initAnimations = function () {
  102697. var _this = this;
  102698. // check if this is not a gltf loader and init the animations
  102699. if (this.skeletons.length) {
  102700. this.skeletons.forEach(function (skeleton, idx) {
  102701. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  102702. var add = false;
  102703. skeleton.getAnimatables().forEach(function (a) {
  102704. if (a.animations[0]) {
  102705. ag.addTargetedAnimation(a.animations[0], a);
  102706. add = true;
  102707. }
  102708. });
  102709. if (add) {
  102710. _this.addAnimationGroup(ag);
  102711. }
  102712. });
  102713. }
  102714. var completeCallback = function () {
  102715. };
  102716. if (this._modelConfiguration.animation) {
  102717. if (this._modelConfiguration.animation.playOnce) {
  102718. this._animations.forEach(function (a) {
  102719. a.playMode = 0 /* ONCE */;
  102720. });
  102721. }
  102722. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  102723. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  102724. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  102725. completeCallback = function () {
  102726. _this.playAnimation(animationName_1);
  102727. };
  102728. }
  102729. }
  102730. this._enterScene(completeCallback);
  102731. };
  102732. /**
  102733. * Animates the model from the current position to the default position
  102734. * @param completeCallback A function to call when the animation has completed
  102735. */
  102736. ViewerModel.prototype._enterScene = function (completeCallback) {
  102737. var _this = this;
  102738. var scene = this.rootMesh.getScene();
  102739. var previousValue = scene.animationPropertiesOverride.enableBlending;
  102740. var callback = function () {
  102741. _this.state = ModelState.ENTRYDONE;
  102742. scene.animationPropertiesOverride.enableBlending = previousValue;
  102743. _this._checkCompleteState();
  102744. if (completeCallback)
  102745. completeCallback();
  102746. };
  102747. if (!this._entryAnimation) {
  102748. callback();
  102749. return;
  102750. }
  102751. this.rootMesh.setEnabled(true);
  102752. // disable blending for the sake of the entry animation;
  102753. scene.animationPropertiesOverride.enableBlending = false;
  102754. this._applyAnimation(this._entryAnimation, true, callback);
  102755. };
  102756. /**
  102757. * Animates the model from the current position to the exit-screen position
  102758. * @param completeCallback A function to call when the animation has completed
  102759. */
  102760. ViewerModel.prototype._exitScene = function (completeCallback) {
  102761. if (!this._exitAnimation) {
  102762. completeCallback();
  102763. return;
  102764. }
  102765. this._applyAnimation(this._exitAnimation, false, completeCallback);
  102766. };
  102767. ViewerModel.prototype._modelComplete = function () {
  102768. var _this = this;
  102769. //reapply material defines to be sure:
  102770. var meshes = this._pivotMesh.getChildMeshes(false);
  102771. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102772. _this._applyModelMaterialConfiguration(mesh.material);
  102773. });
  102774. this.state = ModelState.COMPLETE;
  102775. this.onCompleteObservable.notifyObservers(this);
  102776. };
  102777. /**
  102778. * Add a new animation group to this model.
  102779. * @param animationGroup the new animation group to be added
  102780. */
  102781. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  102782. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  102783. };
  102784. /**
  102785. * Get the ModelAnimation array
  102786. */
  102787. ViewerModel.prototype.getAnimations = function () {
  102788. return this._animations;
  102789. };
  102790. /**
  102791. * Get the animations' names. Using the names you can play a specific animation.
  102792. */
  102793. ViewerModel.prototype.getAnimationNames = function () {
  102794. return this._animations.map(function (a) { return a.name; });
  102795. };
  102796. /**
  102797. * Get an animation by the provided name. Used mainly when playing n animation.
  102798. * @param name the name of the animation to find
  102799. */
  102800. ViewerModel.prototype._getAnimationByName = function (name) {
  102801. // can't use .find, noe available on IE
  102802. var filtered = this._animations.filter(function (a) { return a.name === name; });
  102803. // what the next line means - if two animations have the same name, they will not be returned!
  102804. if (filtered.length === 1) {
  102805. return filtered[0];
  102806. }
  102807. else {
  102808. return null;
  102809. }
  102810. };
  102811. /**
  102812. * Choose an initialized animation using its name and start playing it
  102813. * @param name the name of the animation to play
  102814. * @returns The model aniamtion to be played.
  102815. */
  102816. ViewerModel.prototype.playAnimation = function (name) {
  102817. var animation = this.setCurrentAnimationByName(name);
  102818. if (animation) {
  102819. animation.start();
  102820. }
  102821. return animation;
  102822. };
  102823. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  102824. var animation = this._getAnimationByName(name);
  102825. if (animation) {
  102826. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  102827. this.currentAnimation.stop();
  102828. }
  102829. this.currentAnimation = animation;
  102830. return animation;
  102831. }
  102832. else {
  102833. throw new Error("animation not found - " + name);
  102834. }
  102835. };
  102836. ViewerModel.prototype._configureModel = function () {
  102837. var _this = this;
  102838. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  102839. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  102840. var updateMeshesWithNoParent = function (variable, value, param) {
  102841. meshesWithNoParent.forEach(function (mesh) {
  102842. if (param) {
  102843. mesh[variable][param] = value;
  102844. }
  102845. else {
  102846. mesh[variable] = value;
  102847. }
  102848. });
  102849. };
  102850. var updateXYZ = function (variable, configValues) {
  102851. if (configValues.x !== undefined) {
  102852. updateMeshesWithNoParent(variable, configValues.x, 'x');
  102853. }
  102854. if (configValues.y !== undefined) {
  102855. updateMeshesWithNoParent(variable, configValues.y, 'y');
  102856. }
  102857. if (configValues.z !== undefined) {
  102858. updateMeshesWithNoParent(variable, configValues.z, 'z');
  102859. }
  102860. if (configValues.w !== undefined) {
  102861. updateMeshesWithNoParent(variable, configValues.w, 'w');
  102862. }
  102863. };
  102864. if (this._modelConfiguration.normalize) {
  102865. var center = false;
  102866. var unitSize = false;
  102867. var parentIndex = void 0;
  102868. if (this._modelConfiguration.normalize === true) {
  102869. center = true;
  102870. unitSize = true;
  102871. }
  102872. else {
  102873. center = !!this._modelConfiguration.normalize.center;
  102874. unitSize = !!this._modelConfiguration.normalize.unitSize;
  102875. parentIndex = this._modelConfiguration.normalize.parentIndex;
  102876. }
  102877. var meshesToNormalize = [];
  102878. if (parentIndex !== undefined) {
  102879. meshesToNormalize.push(this._meshes[parentIndex]);
  102880. }
  102881. else {
  102882. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  102883. }
  102884. if (unitSize) {
  102885. meshesToNormalize.forEach(function (mesh) {
  102886. mesh.normalizeToUnitCube(true);
  102887. mesh.computeWorldMatrix(true);
  102888. });
  102889. }
  102890. if (center) {
  102891. meshesToNormalize.forEach(function (mesh) {
  102892. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  102893. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  102894. var halfSizeVec = sizeVec.scale(0.5);
  102895. var center = boundingInfo.min.add(halfSizeVec);
  102896. mesh.position = center.scale(-1);
  102897. mesh.position.y += halfSizeVec.y;
  102898. // Recompute Info.
  102899. mesh.computeWorldMatrix(true);
  102900. });
  102901. }
  102902. }
  102903. else {
  102904. // if centered, should be done here
  102905. }
  102906. // position?
  102907. if (this._modelConfiguration.position) {
  102908. updateXYZ('position', this._modelConfiguration.position);
  102909. }
  102910. if (this._modelConfiguration.rotation) {
  102911. //quaternion?
  102912. if (this._modelConfiguration.rotation.w) {
  102913. meshesWithNoParent.forEach(function (mesh) {
  102914. if (!mesh.rotationQuaternion) {
  102915. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  102916. }
  102917. });
  102918. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  102919. }
  102920. else {
  102921. updateXYZ('rotation', this._modelConfiguration.rotation);
  102922. }
  102923. }
  102924. if (this._modelConfiguration.rotationOffsetAxis) {
  102925. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  102926. meshesWithNoParent.forEach(function (m) {
  102927. if (_this._modelConfiguration.rotationOffsetAngle) {
  102928. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  102929. }
  102930. });
  102931. }
  102932. if (this._modelConfiguration.scaling) {
  102933. updateXYZ('scaling', this._modelConfiguration.scaling);
  102934. }
  102935. if (this._modelConfiguration.castShadow) {
  102936. this._meshes.forEach(function (mesh) {
  102937. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  102938. });
  102939. }
  102940. var meshes = this._pivotMesh.getChildMeshes(false);
  102941. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102942. _this._applyModelMaterialConfiguration(mesh.material);
  102943. });
  102944. if (this._modelConfiguration.entryAnimation) {
  102945. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  102946. }
  102947. if (this._modelConfiguration.exitAnimation) {
  102948. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  102949. }
  102950. this.onAfterConfigure.notifyObservers(this);
  102951. };
  102952. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  102953. var anim = {
  102954. time: 0.5
  102955. };
  102956. if (animConfig.scaling) {
  102957. anim.scaling = babylonjs_1.Vector3.Zero();
  102958. }
  102959. if (animConfig.easingFunction !== undefined) {
  102960. anim.easingFunction = animConfig.easingFunction;
  102961. }
  102962. if (animConfig.easingMode !== undefined) {
  102963. anim.easingMode = animConfig.easingMode;
  102964. }
  102965. _1.extendClassWithConfig(anim, animConfig);
  102966. return anim;
  102967. };
  102968. /**
  102969. * Apply a material configuration to a material
  102970. * @param material Material to apply configuration to
  102971. */
  102972. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  102973. if (!this._modelConfiguration.material)
  102974. return;
  102975. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  102976. if (material instanceof babylonjs_1.PBRMaterial) {
  102977. if (this._modelConfiguration.material.directIntensity !== undefined) {
  102978. material.directIntensity = this._modelConfiguration.material.directIntensity;
  102979. }
  102980. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  102981. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  102982. }
  102983. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  102984. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  102985. }
  102986. if (this._modelConfiguration.material.directEnabled !== undefined) {
  102987. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  102988. }
  102989. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  102990. material.reflectionColor = this._configurationContainer.reflectionColor;
  102991. }
  102992. }
  102993. else if (material instanceof babylonjs_1.MultiMaterial) {
  102994. for (var i = 0; i < material.subMaterials.length; i++) {
  102995. var subMaterial = material.subMaterials[i];
  102996. if (subMaterial) {
  102997. this._applyModelMaterialConfiguration(subMaterial);
  102998. }
  102999. }
  103000. }
  103001. };
  103002. /**
  103003. * Start entry/exit animation given an animation configuration
  103004. * @param animationConfiguration Entry/Exit animation configuration
  103005. * @param isEntry Pass true if the animation is an entry animation
  103006. * @param completeCallback Callback to execute when the animation completes
  103007. */
  103008. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  103009. var animations = [];
  103010. //scale
  103011. if (animationConfiguration.scaling) {
  103012. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  103013. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  103014. if (!scaleStart.equals(scaleEnd)) {
  103015. this.rootMesh.scaling = scaleStart;
  103016. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  103017. animations.push(this._scaleTransition);
  103018. }
  103019. }
  103020. //Start the animation(s)
  103021. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  103022. completeCallback(); });
  103023. };
  103024. /**
  103025. * Begin @animations with the specified @easingFunction
  103026. * @param animations The BABYLON Animations to begin
  103027. * @param duration of transition, in seconds
  103028. * @param easingFunction An easing function to apply
  103029. * @param easingMode A easing mode to apply to the easingFunction
  103030. * @param onAnimationEnd Call back trigger at the end of the animation.
  103031. */
  103032. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  103033. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  103034. if (easingFunction) {
  103035. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103036. var animation = animations_1[_i];
  103037. easingFunction.setEasingMode(easingMode);
  103038. animation.setEasingFunction(easingFunction);
  103039. }
  103040. }
  103041. //Stop any current animations before starting the new one - merging not yet supported.
  103042. this.stopAllAnimations();
  103043. this.rootMesh.animations = animations;
  103044. if (this.rootMesh.getScene().beginAnimation) {
  103045. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  103046. if (onAnimationEnd) {
  103047. onAnimationEnd();
  103048. }
  103049. });
  103050. this._animatables.push(animatable);
  103051. }
  103052. };
  103053. /**
  103054. * Sets key values on an Animation from first to last frame.
  103055. * @param animation The Babylon animation object to set keys on
  103056. * @param startValue The value of the first key
  103057. * @param endValue The value of the last key
  103058. * @param duration The duration of the animation, used to determine the end frame
  103059. */
  103060. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  103061. animation.setKeys([
  103062. {
  103063. frame: 0,
  103064. value: startValue
  103065. },
  103066. {
  103067. frame: this._frameRate * duration,
  103068. value: endValue
  103069. }
  103070. ]);
  103071. };
  103072. /**
  103073. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  103074. * @param easingFunctionID The enum of the easing funtion to create
  103075. * @return The newly created Babylon easing function object
  103076. */
  103077. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  103078. var easingFunction;
  103079. switch (easingFunctionID) {
  103080. case 1 /* CircleEase */:
  103081. easingFunction = new babylonjs_1.CircleEase();
  103082. break;
  103083. case 2 /* BackEase */:
  103084. easingFunction = new babylonjs_1.BackEase(0.3);
  103085. break;
  103086. case 3 /* BounceEase */:
  103087. easingFunction = new babylonjs_1.BounceEase();
  103088. break;
  103089. case 4 /* CubicEase */:
  103090. easingFunction = new babylonjs_1.CubicEase();
  103091. break;
  103092. case 5 /* ElasticEase */:
  103093. easingFunction = new babylonjs_1.ElasticEase();
  103094. break;
  103095. case 6 /* ExponentialEase */:
  103096. easingFunction = new babylonjs_1.ExponentialEase();
  103097. break;
  103098. case 7 /* PowerEase */:
  103099. easingFunction = new babylonjs_1.PowerEase();
  103100. break;
  103101. case 8 /* QuadraticEase */:
  103102. easingFunction = new babylonjs_1.QuadraticEase();
  103103. break;
  103104. case 9 /* QuarticEase */:
  103105. easingFunction = new babylonjs_1.QuarticEase();
  103106. break;
  103107. case 10 /* QuinticEase */:
  103108. easingFunction = new babylonjs_1.QuinticEase();
  103109. break;
  103110. case 11 /* SineEase */:
  103111. easingFunction = new babylonjs_1.SineEase();
  103112. break;
  103113. default:
  103114. babylonjs_1.Tools.Log("No ease function found");
  103115. break;
  103116. }
  103117. return easingFunction;
  103118. };
  103119. /**
  103120. * Stops and removes all animations that have been applied to the model
  103121. */
  103122. ViewerModel.prototype.stopAllAnimations = function () {
  103123. if (this.rootMesh) {
  103124. this.rootMesh.animations = [];
  103125. }
  103126. if (this.currentAnimation) {
  103127. this.currentAnimation.stop();
  103128. }
  103129. while (this._animatables.length) {
  103130. this._animatables[0].onAnimationEnd = null;
  103131. this._animatables[0].stop();
  103132. this._animatables.shift();
  103133. }
  103134. };
  103135. /**
  103136. * Will remove this model from the viewer (but NOT dispose it).
  103137. */
  103138. ViewerModel.prototype.remove = function () {
  103139. this.stopAllAnimations();
  103140. // hide it
  103141. this.rootMesh.isVisible = false;
  103142. if (this._observablesManager) {
  103143. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  103144. }
  103145. };
  103146. /**
  103147. * Dispose this model, including all of its associated assets.
  103148. */
  103149. ViewerModel.prototype.dispose = function () {
  103150. this.remove();
  103151. this.onAfterConfigure.clear();
  103152. this.onLoadedObservable.clear();
  103153. this.onLoadErrorObservable.clear();
  103154. this.onLoadProgressObservable.clear();
  103155. if (this.loader && this.loader.name === "gltf") {
  103156. this.loader.dispose();
  103157. }
  103158. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  103159. this.particleSystems.length = 0;
  103160. this.skeletons.forEach(function (s) { return s.dispose(); });
  103161. this.skeletons.length = 0;
  103162. this._animations.forEach(function (ag) { return ag.dispose(); });
  103163. this._animations.length = 0;
  103164. this.rootMesh.dispose(false, true);
  103165. };
  103166. return ViewerModel;
  103167. }());
  103168. exports.ViewerModel = ViewerModel;
  103169. //# source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xPQUFBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  103170. /***/ }),
  103171. /* 6 */
  103172. /***/ (function(module, exports, __webpack_require__) {
  103173. "use strict";
  103174. Object.defineProperty(exports, "__esModule", { value: true });
  103175. var babylonjs_1 = __webpack_require__(0);
  103176. /**
  103177. * Receives Telemetry events and raises events to the API
  103178. */
  103179. var TelemetryManager = /** @class */ (function () {
  103180. function TelemetryManager() {
  103181. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  103182. this._event = this._eventEnabled;
  103183. }
  103184. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  103185. /**
  103186. * Receives a telemetry event
  103187. * @param event The name of the Telemetry event
  103188. * @param details An additional value, or an object containing a list of property/value pairs
  103189. */
  103190. get: function () {
  103191. return this._event;
  103192. },
  103193. enumerable: true,
  103194. configurable: true
  103195. });
  103196. /**
  103197. * Log a Telemetry event for errors raised on the WebGL context.
  103198. * @param engine The Babylon engine with the WebGL context.
  103199. */
  103200. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  103201. if (!engine) {
  103202. return;
  103203. }
  103204. var logErrors = true;
  103205. while (logErrors) {
  103206. var gl = engine._gl;
  103207. if (gl && gl.getError) {
  103208. var error = gl.getError();
  103209. if (error === gl.NO_ERROR) {
  103210. logErrors = false;
  103211. }
  103212. else {
  103213. this.broadcast("WebGL Error", viewerId, { error: error });
  103214. }
  103215. }
  103216. else {
  103217. logErrors = false;
  103218. }
  103219. }
  103220. };
  103221. Object.defineProperty(TelemetryManager.prototype, "enable", {
  103222. /**
  103223. * Enable or disable telemetry events
  103224. * @param enabled Boolan, true if events are enabled
  103225. */
  103226. set: function (enabled) {
  103227. if (enabled) {
  103228. this._event = this._eventEnabled;
  103229. }
  103230. else {
  103231. this._event = this._eventDisabled;
  103232. }
  103233. },
  103234. enumerable: true,
  103235. configurable: true
  103236. });
  103237. /**
  103238. * Called on event when disabled, typically do nothing here
  103239. */
  103240. TelemetryManager.prototype._eventDisabled = function () {
  103241. // nothing to do
  103242. };
  103243. /**
  103244. * Called on event when enabled
  103245. * @param event - The name of the Telemetry event
  103246. * @param details An additional value, or an object containing a list of property/value pairs
  103247. */
  103248. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  103249. var telemetryData = {
  103250. viewerId: viewerId,
  103251. event: event,
  103252. session: this.session,
  103253. date: new Date(),
  103254. now: window.performance ? window.performance.now() : Date.now(),
  103255. detail: null
  103256. };
  103257. if (typeof details === "object") {
  103258. for (var attr in details) {
  103259. if (details.hasOwnProperty(attr)) {
  103260. telemetryData[attr] = details[attr];
  103261. }
  103262. }
  103263. }
  103264. else if (details) {
  103265. telemetryData.detail = details;
  103266. }
  103267. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  103268. };
  103269. Object.defineProperty(TelemetryManager.prototype, "session", {
  103270. /**
  103271. * Returns the current session ID or creates one if it doesn't exixt
  103272. * @return The current session ID
  103273. */
  103274. get: function () {
  103275. if (!this._currentSessionId) {
  103276. //String + Timestamp + Random Integer
  103277. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  103278. }
  103279. return this._currentSessionId;
  103280. },
  103281. enumerable: true,
  103282. configurable: true
  103283. });
  103284. /**
  103285. * Disposes the telemetry manager
  103286. */
  103287. TelemetryManager.prototype.dispose = function () {
  103288. this.onEventBroadcastedObservable.clear();
  103289. delete this.onEventBroadcastedObservable;
  103290. };
  103291. return TelemetryManager;
  103292. }());
  103293. exports.TelemetryManager = TelemetryManager;
  103294. exports.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EVBQUU7b0JBQzlCLGFBQWEsQ0FBQyxJQUFJLENBQUMsR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7aUJBQ3ZDO2FBQ0o7U0FDSjthQUFNLElBQUksT0FBTyxFQUFFO1lBQ2hCLGFBQWEsQ0FBQyxNQUFNLEdBQUcsT0FBTyxDQUFDO1NBQ2xDO1FBRUQsSUFBSSxDQUFDLDRCQUE0QixDQUFDLGVBQWUsQ0FBQyxhQUFhLENBQUMsQ0FBQztJQUNyRSxDQUFDO0lBTUQsc0JBQVcscUNBQU87UUFKbEI7OztXQUdHO2FBQ0g7WUFDSSxJQUFJLENBQUMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  103296. /***/ }),
  103297. /* 7 */
  103298. /***/ (function(module, exports, __webpack_require__) {
  103299. "use strict";
  103300. Object.defineProperty(exports, "__esModule", { value: true });
  103301. var babylonjs_1 = __webpack_require__(0);
  103302. /**
  103303. * The viewer manager is the container for all viewers currently registered on this page.
  103304. * It is possible to have more than one viewer on a single page.
  103305. */
  103306. var ViewerManager = /** @class */ (function () {
  103307. function ViewerManager() {
  103308. this._viewers = {};
  103309. this.onViewerAddedObservable = new babylonjs_1.Observable();
  103310. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  103311. }
  103312. /**
  103313. * Adding a new viewer to the viewer manager and start tracking it.
  103314. * @param viewer the viewer to add
  103315. */
  103316. ViewerManager.prototype.addViewer = function (viewer) {
  103317. this._viewers[viewer.getBaseId()] = viewer;
  103318. this._onViewerAdded(viewer);
  103319. };
  103320. /**
  103321. * remove a viewer from the viewer manager
  103322. * @param viewer the viewer to remove
  103323. */
  103324. ViewerManager.prototype.removeViewer = function (viewer) {
  103325. var id = viewer.getBaseId();
  103326. delete this._viewers[id];
  103327. this.onViewerRemovedObservable.notifyObservers(id);
  103328. };
  103329. /**
  103330. * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned)
  103331. * @param id the id of the HTMl element (or the viewer's, if none provided)
  103332. */
  103333. ViewerManager.prototype.getViewerById = function (id) {
  103334. return this._viewers[id];
  103335. };
  103336. /**
  103337. * Get a viewer using a container element
  103338. * @param element the HTML element to search viewers associated with
  103339. */
  103340. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  103341. for (var id in this._viewers) {
  103342. if (this._viewers[id].containerElement === element) {
  103343. return this.getViewerById(id);
  103344. }
  103345. }
  103346. };
  103347. /**
  103348. * Get a promise that will fullfil when this viewer was initialized.
  103349. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  103350. * you will get the viewer after everything was already configured.
  103351. * @param id the viewer id to find
  103352. */
  103353. ViewerManager.prototype.getViewerPromiseById = function (id) {
  103354. var _this = this;
  103355. return new Promise(function (resolve, reject) {
  103356. var localViewer = _this.getViewerById(id);
  103357. if (localViewer) {
  103358. return resolve(localViewer);
  103359. }
  103360. var viewerFunction = function (viewer) {
  103361. if (viewer.getBaseId() === id) {
  103362. resolve(viewer);
  103363. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  103364. }
  103365. };
  103366. _this.onViewerAddedObservable.add(viewerFunction);
  103367. });
  103368. };
  103369. ViewerManager.prototype._onViewerAdded = function (viewer) {
  103370. this.onViewerAdded && this.onViewerAdded(viewer);
  103371. this.onViewerAddedObservable.notifyObservers(viewer);
  103372. };
  103373. /**
  103374. * dispose the manager and all of its associated viewers
  103375. */
  103376. ViewerManager.prototype.dispose = function () {
  103377. delete this._onViewerAdded;
  103378. for (var id in this._viewers) {
  103379. this._viewers[id].dispose();
  103380. }
  103381. this.onViewerAddedObservable.clear();
  103382. this.onViewerRemovedObservable.clear();
  103383. };
  103384. return ViewerManager;
  103385. }());
  103386. exports.ViewerManager = ViewerManager;
  103387. exports.viewerManager = new ViewerManager();
  103388. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQU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392. "use strict";
  103393. var __extends = (this && this.__extends) || (function () {
  103394. var extendStatics = Object.setPrototypeOf ||
  103395. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103396. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103397. return function (d, b) {
  103398. extendStatics(d, b);
  103399. function __() { this.constructor = d; }
  103400. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103401. };
  103402. })();
  103403. Object.defineProperty(exports, "__esModule", { value: true });
  103404. var viewer_1 = __webpack_require__(9);
  103405. var babylonjs_1 = __webpack_require__(0);
  103406. /**
  103407. * The Default viewer is the default implementation of the AbstractViewer.
  103408. * It uses the templating system to render a new canvas and controls.
  103409. */
  103410. var DefaultViewer = /** @class */ (function (_super) {
  103411. __extends(DefaultViewer, _super);
  103412. /**
  103413. * Create a new default viewer
  103414. * @param containerElement the element in which the templates will be rendered
  103415. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  103416. */
  103417. function DefaultViewer(containerElement, initialConfiguration) {
  103418. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  103419. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  103420. _this.containerElement = containerElement;
  103421. _this._handlePointerDown = function (event) {
  103422. var pointerDown = event.event;
  103423. if (pointerDown.button !== 0)
  103424. return;
  103425. var element = event.event.target;
  103426. if (!element) {
  103427. return;
  103428. }
  103429. var parentClasses = element.parentElement.classList;
  103430. var elementClasses = element.classList;
  103431. var elementName = "";
  103432. 0;
  103433. for (var i = 0; i < elementClasses.length; ++i) {
  103434. var className = elementClasses[i];
  103435. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  103436. elementName = className;
  103437. break;
  103438. }
  103439. }
  103440. switch (elementName) {
  103441. case "speed-button":
  103442. case "types-button":
  103443. if (parentClasses.contains("open")) {
  103444. parentClasses.remove("open");
  103445. }
  103446. else {
  103447. parentClasses.add("open");
  103448. }
  103449. break;
  103450. case "play-pause-button":
  103451. _this._togglePlayPause();
  103452. break;
  103453. case "label-option-button":
  103454. var label = element.dataset["value"];
  103455. if (label) {
  103456. _this._updateAnimationType(label);
  103457. }
  103458. break;
  103459. case "speed-option-button":
  103460. if (!_this._currentAnimation) {
  103461. return;
  103462. }
  103463. var speed = element.dataset["value"];
  103464. if (speed)
  103465. _this._updateAnimationSpeed(speed);
  103466. break;
  103467. case "progress-wrapper":
  103468. _this._resumePlay = !_this._isAnimationPaused;
  103469. if (_this._resumePlay) {
  103470. _this._togglePlayPause(true);
  103471. }
  103472. break;
  103473. case "fullscreen-button":
  103474. _this.toggleFullscreen();
  103475. break;
  103476. case "hd-button":
  103477. _this.toggleHD();
  103478. break;
  103479. default:
  103480. return;
  103481. }
  103482. };
  103483. /**
  103484. * Plays or Pauses animation
  103485. */
  103486. _this._togglePlayPause = function (noUiUpdate) {
  103487. if (!_this._currentAnimation) {
  103488. return;
  103489. }
  103490. if (_this._isAnimationPaused) {
  103491. _this._currentAnimation.restart();
  103492. }
  103493. else {
  103494. _this._currentAnimation.pause();
  103495. }
  103496. _this._isAnimationPaused = !_this._isAnimationPaused;
  103497. if (noUiUpdate)
  103498. return;
  103499. var navbar = _this.templateManager.getTemplate('navBar');
  103500. if (!navbar)
  103501. return;
  103502. navbar.updateParams({
  103503. paused: _this._isAnimationPaused,
  103504. });
  103505. };
  103506. /**
  103507. * Control progress bar position based on animation current frame
  103508. */
  103509. _this._updateProgressBar = function () {
  103510. var navbar = _this.templateManager.getTemplate('navBar');
  103511. if (!navbar)
  103512. return;
  103513. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  103514. if (progressSlider && _this._currentAnimation) {
  103515. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  103516. var currentValue = progressSlider.valueAsNumber;
  103517. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  103518. progressSlider.value = '' + progress;
  103519. }
  103520. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  103521. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  103522. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  103523. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  103524. }
  103525. }
  103526. else {
  103527. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  103528. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  103529. _this._oldIdleRotationValue = 0;
  103530. }
  103531. }
  103532. }
  103533. };
  103534. /**
  103535. * Update Current Animation Speed
  103536. */
  103537. _this._updateAnimationSpeed = function (speed, paramsObject) {
  103538. var navbar = _this.templateManager.getTemplate('navBar');
  103539. if (!navbar)
  103540. return;
  103541. if (speed && _this._currentAnimation) {
  103542. _this._currentAnimation.speedRatio = parseFloat(speed);
  103543. if (!_this._isAnimationPaused) {
  103544. _this._currentAnimation.restart();
  103545. }
  103546. if (paramsObject) {
  103547. paramsObject.selectedSpeed = speed + "x";
  103548. }
  103549. else {
  103550. navbar.updateParams({
  103551. selectedSpeed: speed + "x",
  103552. });
  103553. }
  103554. }
  103555. };
  103556. /**
  103557. * Update Current Animation Type
  103558. */
  103559. _this._updateAnimationType = function (label, paramsObject) {
  103560. var navbar = _this.templateManager.getTemplate('navBar');
  103561. if (!navbar)
  103562. return;
  103563. if (label) {
  103564. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  103565. }
  103566. if (paramsObject) {
  103567. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  103568. paramsObject.selectedAnimationName = label;
  103569. }
  103570. else {
  103571. navbar.updateParams({
  103572. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  103573. selectedAnimationName: label
  103574. });
  103575. }
  103576. _this._updateAnimationSpeed("1.0", paramsObject);
  103577. };
  103578. /**
  103579. * Toggle fullscreen of the entire viewer
  103580. */
  103581. _this.toggleFullscreen = function () {
  103582. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  103583. var viewerElement = viewerTemplate && viewerTemplate.parent;
  103584. if (viewerElement) {
  103585. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  103586. if (!fullscreenElement) {
  103587. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  103588. requestFullScreen.call(viewerElement);
  103589. }
  103590. else {
  103591. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  103592. exitFullscreen.call(document);
  103593. }
  103594. }
  103595. };
  103596. _this._onModelLoaded = function (model) {
  103597. _this._configureTemplate(model);
  103598. // with a short timeout, making sure everything is there already.
  103599. var hideLoadingDelay = 20;
  103600. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  103601. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  103602. }
  103603. setTimeout(function () {
  103604. _this.sceneManager.scene.executeWhenReady(function () {
  103605. _this.hideLoadingScreen();
  103606. });
  103607. }, hideLoadingDelay);
  103608. return;
  103609. };
  103610. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  103611. _this.onModelRemovedObservable.add(function () {
  103612. _this._configureTemplate();
  103613. });
  103614. _this.onEngineInitObservable.add(function () {
  103615. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  103616. _this._configureLights(data.newConfiguration, data.model);
  103617. });
  103618. });
  103619. return _this;
  103620. }
  103621. /**
  103622. * This will be executed when the templates initialize.
  103623. */
  103624. DefaultViewer.prototype._onTemplatesLoaded = function () {
  103625. var _this = this;
  103626. this.showLoadingScreen();
  103627. // navbar
  103628. this._initNavbar();
  103629. // close overlay button
  103630. var template = this.templateManager.getTemplate('overlay');
  103631. if (template) {
  103632. var closeButton = template.parent.querySelector('.close-button');
  103633. if (closeButton) {
  103634. closeButton.addEventListener('pointerdown', function () {
  103635. _this.hideOverlayScreen();
  103636. });
  103637. }
  103638. }
  103639. if (this.configuration.templates && this.configuration.templates.viewer) {
  103640. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  103641. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  103642. }, function () {
  103643. }, function () {
  103644. }, function () {
  103645. }, function () {
  103646. }, function (file) {
  103647. _this.loadModel(file);
  103648. }, function () {
  103649. });
  103650. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  103651. }
  103652. }
  103653. return _super.prototype._onTemplatesLoaded.call(this);
  103654. };
  103655. DefaultViewer.prototype._dropped = function (evt) {
  103656. };
  103657. DefaultViewer.prototype._initNavbar = function () {
  103658. var _this = this;
  103659. var navbar = this.templateManager.getTemplate('navBar');
  103660. if (navbar) {
  103661. this.onFrameRenderedObservable.add(this._updateProgressBar);
  103662. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  103663. // an example how to trigger the help button. publiclly available
  103664. this.templateManager.eventManager.registerCallback("navBar", function () {
  103665. // do your thing
  103666. }, "pointerdown", ".help-button");
  103667. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  103668. var evt = event.event;
  103669. var element = (evt.target);
  103670. if (!_this._currentAnimation)
  103671. return;
  103672. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  103673. if (isNaN(gotoFrame))
  103674. return;
  103675. _this._currentAnimation.goToFrame(gotoFrame);
  103676. }, "input");
  103677. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  103678. if (_this._resumePlay) {
  103679. _this._togglePlayPause(true);
  103680. }
  103681. _this._resumePlay = false;
  103682. }, "pointerup", ".progress-wrapper");
  103683. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  103684. navbar.updateParams({
  103685. hideHdButton: true
  103686. });
  103687. }
  103688. }
  103689. };
  103690. DefaultViewer.prototype.toggleHD = function () {
  103691. _super.prototype.toggleHD.call(this);
  103692. // update UI element
  103693. var navbar = this.templateManager.getTemplate('navBar');
  103694. if (!navbar)
  103695. return;
  103696. if (navbar.configuration.params) {
  103697. navbar.configuration.params.hdEnabled = this._hdToggled;
  103698. }
  103699. var span = navbar.parent.querySelector("button.hd-button span");
  103700. if (span) {
  103701. span.classList.remove(this._hdToggled ? "hd-icon" : "sd-icon");
  103702. span.classList.add(!this._hdToggled ? "hd-icon" : "sd-icon");
  103703. }
  103704. };
  103705. /**
  103706. * Preparing the container element to present the viewer
  103707. */
  103708. DefaultViewer.prototype._prepareContainerElement = function () {
  103709. this.containerElement.style.position = 'relative';
  103710. this.containerElement.style.height = '100%';
  103711. this.containerElement.style.display = 'flex';
  103712. };
  103713. /**
  103714. * This function will configure the templates and update them after a model was loaded
  103715. * It is mainly responsible to changing the title and subtitle etc'.
  103716. * @param model the model to be used to configure the templates by
  103717. */
  103718. DefaultViewer.prototype._configureTemplate = function (model) {
  103719. var navbar = this.templateManager.getTemplate('navBar');
  103720. if (!navbar)
  103721. return;
  103722. var newParams = navbar.configuration.params || {};
  103723. if (!model) {
  103724. newParams.animations = null;
  103725. }
  103726. else {
  103727. var animationNames = model.getAnimationNames();
  103728. newParams.animations = animationNames;
  103729. if (animationNames.length) {
  103730. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  103731. this._animationList = animationNames;
  103732. newParams.paused = this._isAnimationPaused;
  103733. var animationIndex = 0;
  103734. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  103735. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  103736. if (animationIndex === -1) {
  103737. animationIndex = 0;
  103738. }
  103739. }
  103740. this._updateAnimationType(animationNames[animationIndex], newParams);
  103741. }
  103742. else {
  103743. newParams.animations = null;
  103744. }
  103745. if (model.configuration.thumbnail) {
  103746. newParams.logoImage = model.configuration.thumbnail;
  103747. }
  103748. }
  103749. navbar.updateParams(newParams, false);
  103750. };
  103751. /**
  103752. * This will load a new model to the default viewer
  103753. * overriding the AbstractViewer's loadModel.
  103754. * The scene will automatically be cleared of the old models, if exist.
  103755. * @param model the configuration object (or URL) to load.
  103756. */
  103757. DefaultViewer.prototype.loadModel = function (model) {
  103758. var _this = this;
  103759. if (!model) {
  103760. model = this.configuration.model;
  103761. }
  103762. this.showLoadingScreen();
  103763. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  103764. console.log(error);
  103765. _this.hideLoadingScreen();
  103766. _this.showOverlayScreen('error');
  103767. return Promise.reject(error);
  103768. });
  103769. };
  103770. /**
  103771. * Show the overlay and the defined sub-screen.
  103772. * Mainly used for help and errors
  103773. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  103774. */
  103775. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  103776. var _this = this;
  103777. var template = this.templateManager.getTemplate('overlay');
  103778. if (!template)
  103779. return Promise.resolve('Overlay template not found');
  103780. return template.show((function (template) {
  103781. var canvasRect = _this.containerElement.getBoundingClientRect();
  103782. template.parent.style.display = 'flex';
  103783. template.parent.style.width = canvasRect.width + "px";
  103784. template.parent.style.height = canvasRect.height + "px";
  103785. template.parent.style.opacity = "1";
  103786. var subTemplate = _this.templateManager.getTemplate(subScreen);
  103787. if (!subTemplate) {
  103788. return Promise.reject(subScreen + ' template not found');
  103789. }
  103790. return subTemplate.show((function (template) {
  103791. template.parent.style.display = 'flex';
  103792. return Promise.resolve(template);
  103793. }));
  103794. }));
  103795. };
  103796. /**
  103797. * Hide the overlay screen.
  103798. */
  103799. DefaultViewer.prototype.hideOverlayScreen = function () {
  103800. var template = this.templateManager.getTemplate('overlay');
  103801. if (!template)
  103802. return Promise.resolve('Overlay template not found');
  103803. return template.hide((function (template) {
  103804. template.parent.style.opacity = "0";
  103805. var onTransitionEnd = function () {
  103806. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103807. template.parent.style.display = 'none';
  103808. };
  103809. template.parent.addEventListener("transitionend", onTransitionEnd);
  103810. var overlays = template.parent.querySelectorAll('.overlay');
  103811. if (overlays) {
  103812. for (var i = 0; i < overlays.length; ++i) {
  103813. var htmlElement = overlays.item(i);
  103814. htmlElement.style.display = 'none';
  103815. }
  103816. }
  103817. return Promise.resolve(template);
  103818. }));
  103819. };
  103820. /**
  103821. * show the viewer (in case it was hidden)
  103822. *
  103823. * @param visibilityFunction an optional function to execute in order to show the container
  103824. */
  103825. DefaultViewer.prototype.show = function (visibilityFunction) {
  103826. var template = this.templateManager.getTemplate('main');
  103827. //not possible, but yet:
  103828. if (!template)
  103829. return Promise.reject('Main template not found');
  103830. return template.show(visibilityFunction);
  103831. };
  103832. /**
  103833. * hide the viewer (in case it is visible)
  103834. *
  103835. * @param visibilityFunction an optional function to execute in order to hide the container
  103836. */
  103837. DefaultViewer.prototype.hide = function (visibilityFunction) {
  103838. var template = this.templateManager.getTemplate('main');
  103839. //not possible, but yet:
  103840. if (!template)
  103841. return Promise.reject('Main template not found');
  103842. return template.hide(visibilityFunction);
  103843. };
  103844. /**
  103845. * Show the loading screen.
  103846. * The loading screen can be configured using the configuration object
  103847. */
  103848. DefaultViewer.prototype.showLoadingScreen = function () {
  103849. var _this = this;
  103850. var template = this.templateManager.getTemplate('loadingScreen');
  103851. if (!template)
  103852. return Promise.resolve('Loading Screen template not found');
  103853. return template.show((function (template) {
  103854. var canvasRect = _this.containerElement.getBoundingClientRect();
  103855. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  103856. template.parent.style.display = 'flex';
  103857. template.parent.style.width = canvasRect.width + "px";
  103858. template.parent.style.height = canvasRect.height + "px";
  103859. template.parent.style.opacity = "1";
  103860. // from the configuration!!!
  103861. var color = "black";
  103862. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  103863. color = (_this.configuration.templates.loadingScreen.params &&
  103864. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  103865. }
  103866. template.parent.style.backgroundColor = color;
  103867. return Promise.resolve(template);
  103868. }));
  103869. };
  103870. /**
  103871. * Hide the loading screen
  103872. */
  103873. DefaultViewer.prototype.hideLoadingScreen = function () {
  103874. var template = this.templateManager.getTemplate('loadingScreen');
  103875. if (!template)
  103876. return Promise.resolve('Loading Screen template not found');
  103877. return template.hide((function (template) {
  103878. template.parent.style.opacity = "0";
  103879. var onTransitionEnd = function () {
  103880. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103881. template.parent.style.display = 'none';
  103882. };
  103883. template.parent.addEventListener("transitionend", onTransitionEnd);
  103884. return Promise.resolve(template);
  103885. }));
  103886. };
  103887. DefaultViewer.prototype.dispose = function () {
  103888. this.templateManager.dispose();
  103889. _super.prototype.dispose.call(this);
  103890. };
  103891. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  103892. var _this = this;
  103893. _super.prototype._onConfigurationLoaded.call(this, configuration);
  103894. // initialize the templates
  103895. var templateConfiguration = this.configuration.templates || {};
  103896. this.templateManager.initTemplate(templateConfiguration);
  103897. // when done, execute onTemplatesLoaded()
  103898. this.templateManager.onAllLoaded.add(function () {
  103899. var canvas = _this.templateManager.getCanvas();
  103900. if (canvas) {
  103901. _this._canvas = canvas;
  103902. }
  103903. _this._onTemplateLoaded();
  103904. });
  103905. };
  103906. /**
  103907. * An extension of the light configuration of the abstract viewer.
  103908. * @param lightsConfiguration the light configuration to use
  103909. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  103910. */
  103911. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  103912. var _this = this;
  103913. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  103914. // labs feature - flashlight
  103915. if (this.configuration.lab && this.configuration.lab.flashlight) {
  103916. var pointerPosition = babylonjs_1.Vector3.Zero();
  103917. var lightTarget_1;
  103918. var angle = 0.5;
  103919. var exponent = Math.PI / 2;
  103920. if (typeof this.configuration.lab.flashlight === "object") {
  103921. exponent = this.configuration.lab.flashlight.exponent || exponent;
  103922. angle = this.configuration.lab.flashlight.angle || angle;
  103923. }
  103924. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  103925. if (typeof this.configuration.lab.flashlight === "object") {
  103926. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  103927. if (this.configuration.lab.flashlight.diffuse) {
  103928. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  103929. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  103930. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  103931. }
  103932. if (this.configuration.lab.flashlight.specular) {
  103933. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  103934. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  103935. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  103936. }
  103937. }
  103938. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  103939. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  103940. if (eventData.type === 4 && eventData.pickInfo) {
  103941. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  103942. }
  103943. else {
  103944. lightTarget_1 = undefined;
  103945. }
  103946. });
  103947. var updateFlashlightFunction = function () {
  103948. if (_this.sceneManager.camera && flashlight) {
  103949. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  103950. if (lightTarget_1) {
  103951. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  103952. }
  103953. }
  103954. };
  103955. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  103956. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  103957. }
  103958. };
  103959. return DefaultViewer;
  103960. }(viewer_1.AbstractViewer));
  103961. exports.DefaultViewer = DefaultViewer;
  103962. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92a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U0sSUFBSSxVQUFVLEVBQUU7b0JBQ3hDLFVBQVUsQ0FBQyxRQUFRLENBQUMsUUFBUSxDQUFDLEtBQUksQ0FBQyxZQUFZLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxDQUFDO29CQUNoRSxJQUFJLGFBQVcsRUFBRTt3QkFDYixhQUFXLENBQUMsYUFBYSxDQUFDLFVBQVUsQ0FBQyxRQUFRLEVBQUUsVUFBVSxDQUFDLFNBQVMsQ0FBQyxDQUFDO3FCQUN4RTtpQkFDSjtZQUNMLENBQUMsQ0FBQTtZQUNELElBQUksQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixDQUFDLHdCQUF3QixDQUFDLENBQUM7WUFDdkUsSUFBSSxDQUFDLGtDQUFrQyxDQUFDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO1NBQzFFO0lBQ0wsQ0FBQztJQUNMLG9CQUFDO0FBQUQsQ0FBQyxBQXJsQkQsQ0FBbUMsdUJBQWMsR0FxbEJoRDtBQXJsQlksc0NBQWEifQ==
  103963. /***/ }),
  103964. /* 9 */
  103965. /***/ (function(module, exports, __webpack_require__) {
  103966. "use strict";
  103967. Object.defineProperty(exports, "__esModule", { value: true });
  103968. var viewerManager_1 = __webpack_require__(7);
  103969. var sceneManager_1 = __webpack_require__(22);
  103970. var loader_1 = __webpack_require__(28);
  103971. var babylonjs_1 = __webpack_require__(0);
  103972. var modelLoader_1 = __webpack_require__(13);
  103973. var globals_1 = __webpack_require__(4);
  103974. var telemetryManager_1 = __webpack_require__(6);
  103975. var _1 = __webpack_require__(1);
  103976. var observablesManager_1 = __webpack_require__(59);
  103977. var configurationContainer_1 = __webpack_require__(60);
  103978. var templateManager_1 = __webpack_require__(61);
  103979. /**
  103980. * The AbstractViewr is the center of Babylon's viewer.
  103981. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  103982. */
  103983. var AbstractViewer = /** @class */ (function () {
  103984. function AbstractViewer(containerElement, initialConfiguration) {
  103985. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  103986. var _this = this;
  103987. this.containerElement = containerElement;
  103988. /**
  103989. * A flag that controls whether or not the render loop should be executed
  103990. */
  103991. this.runRenderLoop = true;
  103992. /**
  103993. * is this viewer disposed?
  103994. */
  103995. this._isDisposed = false;
  103996. this._hdToggled = false;
  103997. /**
  103998. * The resize function that will be registered with the window object
  103999. */
  104000. this._resize = function () {
  104001. // Only resize if Canvas is in the DOM
  104002. if (!_this.isCanvasInDOM()) {
  104003. return;
  104004. }
  104005. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  104006. return;
  104007. }
  104008. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  104009. return;
  104010. }
  104011. _this.engine.resize();
  104012. };
  104013. /**
  104014. * render loop that will be executed by the engine
  104015. */
  104016. this._render = function (force) {
  104017. if (force === void 0) { force = false; }
  104018. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  104019. if (_this.runRenderLoop || force) {
  104020. _this.engine.performanceMonitor.enable();
  104021. _this.sceneManager.scene.render();
  104022. _this.onFrameRenderedObservable.notifyObservers(_this);
  104023. }
  104024. else {
  104025. _this.engine.performanceMonitor.disable();
  104026. // update camera instead of rendering
  104027. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  104028. }
  104029. }
  104030. };
  104031. // if exists, use the container id. otherwise, generate a random string.
  104032. if (containerElement.id) {
  104033. this.baseId = containerElement.id;
  104034. }
  104035. else {
  104036. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  104037. }
  104038. this._registeredOnBeforeRenderFunctions = [];
  104039. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  104040. // add this viewer to the viewer manager
  104041. viewerManager_1.viewerManager.addViewer(this);
  104042. this.observablesManager = new observablesManager_1.ObservablesManager();
  104043. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  104044. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  104045. // extend the configuration
  104046. this._configurationLoader = new loader_1.ConfigurationLoader();
  104047. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  104048. _this._onConfigurationLoaded(configuration);
  104049. });
  104050. this.onSceneInitObservable.add(function () {
  104051. _this.updateConfiguration();
  104052. });
  104053. this.onInitDoneObservable.add(function () {
  104054. _this._isInit = true;
  104055. _this.engine.runRenderLoop(_this._render);
  104056. });
  104057. this._prepareContainerElement();
  104058. }
  104059. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  104060. // observables
  104061. /**
  104062. * Will notify when the scene was initialized
  104063. */
  104064. get: function () {
  104065. return this.observablesManager.onSceneInitObservable;
  104066. },
  104067. enumerable: true,
  104068. configurable: true
  104069. });
  104070. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  104071. /**
  104072. * will notify when the engine was initialized
  104073. */
  104074. get: function () {
  104075. return this.observablesManager.onEngineInitObservable;
  104076. },
  104077. enumerable: true,
  104078. configurable: true
  104079. });
  104080. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  104081. /**
  104082. * Will notify when a new model was added to the scene.
  104083. * Note that added does not neccessarily mean loaded!
  104084. */
  104085. get: function () {
  104086. return this.observablesManager.onModelAddedObservable;
  104087. },
  104088. enumerable: true,
  104089. configurable: true
  104090. });
  104091. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  104092. /**
  104093. * will notify after every model load
  104094. */
  104095. get: function () {
  104096. return this.observablesManager.onModelLoadedObservable;
  104097. },
  104098. enumerable: true,
  104099. configurable: true
  104100. });
  104101. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  104102. /**
  104103. * will notify when any model notify of progress
  104104. */
  104105. get: function () {
  104106. return this.observablesManager.onModelLoadProgressObservable;
  104107. },
  104108. enumerable: true,
  104109. configurable: true
  104110. });
  104111. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  104112. /**
  104113. * will notify when any model load failed.
  104114. */
  104115. get: function () {
  104116. return this.observablesManager.onModelLoadErrorObservable;
  104117. },
  104118. enumerable: true,
  104119. configurable: true
  104120. });
  104121. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  104122. /**
  104123. * Will notify when a model was removed from the scene;
  104124. */
  104125. get: function () {
  104126. return this.observablesManager.onModelRemovedObservable;
  104127. },
  104128. enumerable: true,
  104129. configurable: true
  104130. });
  104131. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  104132. /**
  104133. * will notify when a new loader was initialized.
  104134. * Used mainly to know when a model starts loading.
  104135. */
  104136. get: function () {
  104137. return this.observablesManager.onLoaderInitObservable;
  104138. },
  104139. enumerable: true,
  104140. configurable: true
  104141. });
  104142. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  104143. /**
  104144. * Observers registered here will be executed when the entire load process has finished.
  104145. */
  104146. get: function () {
  104147. return this.observablesManager.onViewerInitDoneObservable;
  104148. },
  104149. enumerable: true,
  104150. configurable: true
  104151. });
  104152. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  104153. /**
  104154. * Functions added to this observable will be executed on each frame rendered.
  104155. */
  104156. get: function () {
  104157. return this.observablesManager.onFrameRenderedObservable;
  104158. },
  104159. enumerable: true,
  104160. configurable: true
  104161. });
  104162. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  104163. /**
  104164. * The (single) canvas of this viewer
  104165. */
  104166. get: function () {
  104167. return this._canvas;
  104168. },
  104169. enumerable: true,
  104170. configurable: true
  104171. });
  104172. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  104173. get: function () {
  104174. return this._configurationContainer;
  104175. },
  104176. enumerable: true,
  104177. configurable: true
  104178. });
  104179. /**
  104180. * get the baseId of this viewer
  104181. */
  104182. AbstractViewer.prototype.getBaseId = function () {
  104183. return this.baseId;
  104184. };
  104185. /**
  104186. * Do we have a canvas to render on, and is it a part of the scene
  104187. */
  104188. AbstractViewer.prototype.isCanvasInDOM = function () {
  104189. return !!this._canvas && !!this._canvas.parentElement;
  104190. };
  104191. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  104192. /**
  104193. * Is the engine currently set to rende even when the page is in background
  104194. */
  104195. get: function () {
  104196. return this.engine && this.engine.renderEvenInBackground;
  104197. },
  104198. /**
  104199. * Set the viewer's background rendering flag.
  104200. */
  104201. set: function (value) {
  104202. if (this.engine) {
  104203. this.engine.renderEvenInBackground = value;
  104204. }
  104205. },
  104206. enumerable: true,
  104207. configurable: true
  104208. });
  104209. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  104210. /**
  104211. * Get the configuration object. This is a reference only.
  104212. * The configuration can ONLY be updated using the updateConfiguration function.
  104213. * changing this object will have no direct effect on the scene.
  104214. */
  104215. get: function () {
  104216. return this._configurationContainer.configuration;
  104217. },
  104218. enumerable: true,
  104219. configurable: true
  104220. });
  104221. /**
  104222. * force resizing the engine.
  104223. */
  104224. AbstractViewer.prototype.forceResize = function () {
  104225. this._resize();
  104226. };
  104227. AbstractViewer.prototype.toggleHD = function () {
  104228. this._hdToggled = !this._hdToggled;
  104229. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  104230. this.engine.setHardwareScalingLevel(scale);
  104231. };
  104232. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  104233. var _this = this;
  104234. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  104235. if (this.configuration.observers) {
  104236. this._configureObservers(this.configuration.observers);
  104237. }
  104238. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  104239. if (this.configuration.loaderPlugins) {
  104240. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  104241. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  104242. _this.modelLoader.addPlugin(name);
  104243. }
  104244. }));
  104245. }
  104246. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  104247. };
  104248. /**
  104249. * Force a single render loop execution.
  104250. */
  104251. AbstractViewer.prototype.forceRender = function () {
  104252. this._render(true);
  104253. };
  104254. /**
  104255. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  104256. * @param callback optional callback that will be triggered when screenshot is done.
  104257. * @param width Optional screenshot width (default to 512).
  104258. * @param height Optional screenshot height (default to 512).
  104259. * @returns a promise with the screenshot data
  104260. */
  104261. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  104262. var _this = this;
  104263. if (width === void 0) { width = 0; }
  104264. if (height === void 0) { height = 0; }
  104265. width = width || this.canvas.clientWidth;
  104266. height = height || this.canvas.clientHeight;
  104267. // Create the screenshot
  104268. return new Promise(function (resolve, reject) {
  104269. try {
  104270. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  104271. if (callback) {
  104272. callback(data);
  104273. }
  104274. resolve(data);
  104275. });
  104276. }
  104277. catch (e) {
  104278. reject(e);
  104279. }
  104280. });
  104281. };
  104282. /**
  104283. * Update the current viewer configuration with new values.
  104284. * Only provided information will be updated, old configuration values will be kept.
  104285. * If this.configuration was manually changed, you can trigger this function with no parameters,
  104286. * and the entire configuration will be updated.
  104287. * @param newConfiguration the partial configuration to update
  104288. *
  104289. */
  104290. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  104291. var _this = this;
  104292. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  104293. // update this.configuration with the new data
  104294. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  104295. this.sceneManager.updateConfiguration(newConfiguration);
  104296. // observers in configuration
  104297. if (newConfiguration.observers) {
  104298. this._configureObservers(newConfiguration.observers);
  104299. }
  104300. if (newConfiguration.loaderPlugins) {
  104301. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  104302. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  104303. _this.modelLoader.addPlugin(name);
  104304. }
  104305. }));
  104306. }
  104307. };
  104308. /**
  104309. * this is used to register native functions using the configuration object.
  104310. * This will configure the observers.
  104311. * @param observersConfiguration observers configuration
  104312. */
  104313. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  104314. if (observersConfiguration.onEngineInit) {
  104315. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  104316. }
  104317. else {
  104318. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  104319. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  104320. }
  104321. }
  104322. if (observersConfiguration.onSceneInit) {
  104323. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  104324. }
  104325. else {
  104326. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  104327. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  104328. }
  104329. }
  104330. if (observersConfiguration.onModelLoaded) {
  104331. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  104332. }
  104333. else {
  104334. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  104335. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  104336. }
  104337. }
  104338. };
  104339. /**
  104340. * Dispoe the entire viewer including the scene and the engine
  104341. */
  104342. AbstractViewer.prototype.dispose = function () {
  104343. if (this._isDisposed) {
  104344. return;
  104345. }
  104346. window.removeEventListener('resize', this._resize);
  104347. if (this.sceneManager) {
  104348. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  104349. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  104350. }
  104351. this.sceneManager.dispose();
  104352. }
  104353. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  104354. this.observablesManager.dispose();
  104355. this.modelLoader.dispose();
  104356. if (this.engine) {
  104357. this.engine.dispose();
  104358. }
  104359. viewerManager_1.viewerManager.removeViewer(this);
  104360. this._isDisposed = true;
  104361. };
  104362. /**
  104363. * This function will execute when the HTML templates finished initializing.
  104364. * It should initialize the engine and continue execution.
  104365. *
  104366. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  104367. */
  104368. AbstractViewer.prototype._onTemplatesLoaded = function () {
  104369. return Promise.resolve(this);
  104370. };
  104371. /**
  104372. * This will force the creation of an engine and a scene.
  104373. * It will also load a model if preconfigured.
  104374. * But first - it will load the extendible onTemplateLoaded()!
  104375. */
  104376. AbstractViewer.prototype._onTemplateLoaded = function () {
  104377. var _this = this;
  104378. // check if viewer was disposed right after created
  104379. if (this._isDisposed) {
  104380. return Promise.reject("viewer was disposed");
  104381. }
  104382. return this._onTemplatesLoaded().then(function () {
  104383. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  104384. return _this._initEngine().then(function (engine) {
  104385. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  104386. }).then(function () {
  104387. _this._initTelemetryEvents();
  104388. if (autoLoad) {
  104389. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  104390. }
  104391. else {
  104392. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  104393. }
  104394. }).then(function () {
  104395. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  104396. }).catch(function (e) {
  104397. babylonjs_1.Tools.Warn(e.toString());
  104398. return _this;
  104399. });
  104400. });
  104401. };
  104402. /**
  104403. * Initialize the engine. Retruns a promise in case async calls are needed.
  104404. *
  104405. * @protected
  104406. * @returns {Promise<Engine>}
  104407. * @memberof Viewer
  104408. */
  104409. AbstractViewer.prototype._initEngine = function () {
  104410. // init custom shaders
  104411. this._injectCustomShaders();
  104412. //let canvasElement = this.templateManager.getCanvas();
  104413. if (!this.canvas) {
  104414. return Promise.reject('Canvas element not found!');
  104415. }
  104416. var config = this.configuration.engine || {};
  104417. // TDO enable further configuration
  104418. // check for webgl2 support, force-disable if needed.
  104419. if (globals_1.viewerGlobals.disableWebGL2Support) {
  104420. config.engineOptions = config.engineOptions || {};
  104421. config.engineOptions.disableWebGL2Support = true;
  104422. }
  104423. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  104424. // Disable manifest checking
  104425. babylonjs_1.Database.IDBStorageEnabled = false;
  104426. if (!config.disableResize) {
  104427. window.addEventListener('resize', this._resize);
  104428. }
  104429. if (this.configuration.engine) {
  104430. if (this.configuration.engine.adaptiveQuality) {
  104431. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  104432. this.engine.setHardwareScalingLevel(scale);
  104433. }
  104434. if (this.configuration.engine.hdEnabled) {
  104435. this.toggleHD();
  104436. }
  104437. }
  104438. // create a new template manager for this viewer
  104439. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  104440. return Promise.resolve(this.engine);
  104441. };
  104442. /**
  104443. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  104444. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  104445. *
  104446. * @param modelConfig model configuration to use when loading the model.
  104447. * @param clearScene should the scene be cleared before loading this model
  104448. * @returns a ViewerModel object that is not yet fully loaded.
  104449. */
  104450. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  104451. var _this = this;
  104452. if (clearScene === void 0) { clearScene = true; }
  104453. var configuration;
  104454. if (typeof modelConfig === 'string') {
  104455. configuration = {
  104456. url: modelConfig
  104457. };
  104458. }
  104459. else if (modelConfig instanceof File) {
  104460. configuration = {
  104461. file: modelConfig,
  104462. root: "file:"
  104463. };
  104464. }
  104465. else {
  104466. configuration = modelConfig;
  104467. }
  104468. if (!configuration.url && !configuration.file) {
  104469. throw new Error("no model provided");
  104470. }
  104471. if (clearScene) {
  104472. this.sceneManager.clearScene(true, false);
  104473. }
  104474. //merge the configuration for future models:
  104475. if (this.configuration.model && typeof this.configuration.model === 'object') {
  104476. var globalConfig = _1.deepmerge({}, this.configuration.model);
  104477. configuration = _1.deepmerge(globalConfig, configuration);
  104478. if (modelConfig instanceof File) {
  104479. configuration.file = modelConfig;
  104480. }
  104481. }
  104482. else {
  104483. this.configuration.model = configuration;
  104484. }
  104485. this._isLoading = true;
  104486. var model = this.modelLoader.load(configuration);
  104487. this.lastUsedLoader = model.loader;
  104488. model.onLoadErrorObservable.add(function (errorObject) {
  104489. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  104490. });
  104491. model.onLoadProgressObservable.add(function (progressEvent) {
  104492. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104493. });
  104494. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  104495. model.onLoadedObservable.add(function () {
  104496. _this._isLoading = false;
  104497. });
  104498. return model;
  104499. };
  104500. /**
  104501. * load a model using the provided configuration.
  104502. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  104503. * If you want to attach to the observables of the model, use initModle instead.
  104504. *
  104505. * @param modelConfig the model configuration or URL to load.
  104506. * @param clearScene Should the scene be cleared before loading the model
  104507. * @returns a Promise the fulfills when the model finished loading successfully.
  104508. */
  104509. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  104510. var _this = this;
  104511. if (clearScene === void 0) { clearScene = true; }
  104512. if (this._isLoading) {
  104513. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  104514. return Promise.reject("another model is curently being loaded.");
  104515. }
  104516. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  104517. if (!scene)
  104518. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  104519. return scene;
  104520. }).then(function () {
  104521. var model = _this.initModel(modelConfig, clearScene);
  104522. return new Promise(function (resolve, reject) {
  104523. // at this point, configuration.model is an object, not a string
  104524. model.onLoadedObservable.add(function () {
  104525. resolve(model);
  104526. });
  104527. model.onLoadErrorObservable.add(function (error) {
  104528. reject(error);
  104529. });
  104530. });
  104531. });
  104532. };
  104533. AbstractViewer.prototype._initTelemetryEvents = function () {
  104534. var _this = this;
  104535. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  104536. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  104537. userAgent: navigator.userAgent,
  104538. platform: navigator.platform
  104539. });
  104540. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  104541. var trackFPS = function () {
  104542. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  104543. };
  104544. trackFPS();
  104545. // Track the FPS again after 60 seconds
  104546. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  104547. };
  104548. /**
  104549. * Injects all the spectre shader in the babylon shader store
  104550. */
  104551. AbstractViewer.prototype._injectCustomShaders = function () {
  104552. var customShaders = this.configuration.customShaders;
  104553. // Inject all the spectre shader in the babylon shader store.
  104554. if (!customShaders) {
  104555. return;
  104556. }
  104557. if (customShaders.shaders) {
  104558. Object.keys(customShaders.shaders).forEach(function (key) {
  104559. // typescript considers a callback "unsafe", so... '!'
  104560. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  104561. });
  104562. }
  104563. if (customShaders.includes) {
  104564. Object.keys(customShaders.includes).forEach(function (key) {
  104565. // typescript considers a callback "unsafe", so... '!'
  104566. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  104567. });
  104568. }
  104569. };
  104570. return AbstractViewer;
  104571. }());
  104572. exports.AbstractViewer = AbstractViewer;
  104573. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5R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QUMsQUE3b0JELElBNm9CQztBQTdvQnFCLHdDQUFjIn0=
  104574. /***/ }),
  104575. /* 10 */
  104576. /***/ (function(module, exports, __webpack_require__) {
  104577. "use strict";
  104578. function __export(m) {
  104579. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  104580. }
  104581. Object.defineProperty(exports, "__esModule", { value: true });
  104582. __export(__webpack_require__(11));
  104583. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  104584. /***/ }),
  104585. /* 11 */
  104586. /***/ (function(module, exports, __webpack_require__) {
  104587. "use strict";
  104588. Object.defineProperty(exports, "__esModule", { value: true });
  104589. function getConfigurationKey(key, configObject) {
  104590. var splits = key.split('.');
  104591. if (splits.length === 0 || !configObject)
  104592. return;
  104593. else if (splits.length === 1) {
  104594. if (configObject[key] !== undefined) {
  104595. return configObject[key];
  104596. }
  104597. }
  104598. else {
  104599. var firstKey = splits.shift();
  104600. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  104601. }
  104602. }
  104603. exports.getConfigurationKey = getConfigurationKey;
  104604. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  104605. /***/ }),
  104606. /* 12 */
  104607. /***/ (function(module, exports, __webpack_require__) {
  104608. "use strict";
  104609. Object.defineProperty(exports, "__esModule", { value: true });
  104610. var babylonjs_1 = __webpack_require__(0);
  104611. /**
  104612. * A minimal WebGL cubemap descriptor
  104613. */
  104614. var TextureCube = /** @class */ (function () {
  104615. /**
  104616. * constructor
  104617. * @param internalFormat WebGL pixel format for the texture on the GPU
  104618. * @param type WebGL pixel type of the supplied data and texture on the GPU
  104619. * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object
  104620. */
  104621. function TextureCube(internalFormat, type, source) {
  104622. if (source === void 0) { source = []; }
  104623. this.internalFormat = internalFormat;
  104624. this.type = type;
  104625. this.source = source;
  104626. }
  104627. Object.defineProperty(TextureCube.prototype, "Width", {
  104628. /**
  104629. * Returns the width of a face of the texture or 0 if not available
  104630. */
  104631. get: function () {
  104632. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  104633. },
  104634. enumerable: true,
  104635. configurable: true
  104636. });
  104637. Object.defineProperty(TextureCube.prototype, "Height", {
  104638. /**
  104639. * Returns the height of a face of the texture or 0 if not available
  104640. */
  104641. get: function () {
  104642. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  104643. },
  104644. enumerable: true,
  104645. configurable: true
  104646. });
  104647. return TextureCube;
  104648. }());
  104649. exports.TextureCube = TextureCube;
  104650. /**
  104651. * A static class providing methods to aid working with Bablyon textures.
  104652. */
  104653. var TextureUtils = /** @class */ (function () {
  104654. function TextureUtils() {
  104655. }
  104656. /**
  104657. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  104658. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  104659. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  104660. * @param scene A Babylon Scene instance
  104661. * @param textureCube A Spectre TextureCube object
  104662. * @param parameters WebGL texture sampling parameters
  104663. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  104664. * @param environment Specifies that the texture will be used as an environment
  104665. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  104666. * @return Babylon cube texture
  104667. */
  104668. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  104669. if (environment === void 0) { environment = false; }
  104670. if (singleLod === void 0) { singleLod = false; }
  104671. if (!textureCube)
  104672. throw new Error("no texture cube provided");
  104673. var parameters;
  104674. if (environment) {
  104675. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  104676. }
  104677. else {
  104678. parameters = {
  104679. magFilter: 9728 /* NEAREST */,
  104680. minFilter: 9728 /* NEAREST */,
  104681. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104682. wrapT: 33071 /* CLAMP_TO_EDGE */
  104683. };
  104684. }
  104685. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  104686. var babylonTexture = textureCube[key];
  104687. if (!babylonTexture) {
  104688. //initialize babylon texture
  104689. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  104690. if (environment) {
  104691. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  104692. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  104693. }
  104694. babylonTexture.gammaSpace = false;
  104695. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  104696. var glTexture_1 = internalTexture_1._webGLTexture;
  104697. //babylon properties
  104698. internalTexture_1.isCube = true;
  104699. internalTexture_1.generateMipMaps = false;
  104700. babylonTexture._texture = internalTexture_1;
  104701. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  104702. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  104703. var texturesUploaded_1 = 0;
  104704. var textureComplete = function () {
  104705. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  104706. };
  104707. var uploadFace = function (i, level, face) {
  104708. if (!glTexture_1)
  104709. return;
  104710. if (i === 0 && level === 0) {
  104711. internalTexture_1.width = face.width;
  104712. internalTexture_1.height = face.height;
  104713. }
  104714. var gl = (scene.getEngine())._gl;
  104715. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  104716. scene.getEngine()._unpackFlipY(false);
  104717. if (face instanceof HTMLElement || face instanceof ImageData) {
  104718. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  104719. }
  104720. else {
  104721. var textureData = face;
  104722. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  104723. }
  104724. texturesUploaded_1++;
  104725. if (textureComplete()) {
  104726. //generate mipmaps
  104727. if (automaticMipmaps) {
  104728. var w = face.width;
  104729. var h = face.height;
  104730. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  104731. if (isPot) {
  104732. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  104733. }
  104734. }
  104735. // Upload Separate lods in case there is no support for texture lod.
  104736. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  104737. var mipSlices = 3;
  104738. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  104739. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  104740. var lod = textureCube[lodKey];
  104741. //initialize lod texture if it doesn't already exist
  104742. if (lod == null && textureCube.Width) {
  104743. //compute LOD from even spacing in smoothness (matching shader calculation)
  104744. var smoothness = i_1 / (mipSlices - 1);
  104745. var roughness = 1 - smoothness;
  104746. var kMinimumVariance = 0.0005;
  104747. var alphaG = roughness * roughness + kMinimumVariance;
  104748. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  104749. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  104750. var maxLODIndex = textureCube.source.length - 1;
  104751. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  104752. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  104753. if (i_1 === 0) {
  104754. internalTexture_1._lodTextureLow = lod;
  104755. }
  104756. else if (i_1 === 1) {
  104757. internalTexture_1._lodTextureMid = lod;
  104758. }
  104759. else {
  104760. internalTexture_1._lodTextureHigh = lod;
  104761. }
  104762. textureCube[lodKey] = lod;
  104763. }
  104764. }
  104765. }
  104766. internalTexture_1.isReady = true;
  104767. }
  104768. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  104769. scene.getEngine().resetTextureCache();
  104770. };
  104771. var _loop_1 = function (i) {
  104772. var faces = textureCube.source[i];
  104773. var _loop_2 = function (j) {
  104774. var face = faces[j];
  104775. if (face instanceof HTMLImageElement && !face.complete) {
  104776. face.addEventListener('load', function () {
  104777. uploadFace(j, i, face);
  104778. }, false);
  104779. }
  104780. else {
  104781. uploadFace(j, i, face);
  104782. }
  104783. };
  104784. for (var j = 0; j < faces.length; j++) {
  104785. _loop_2(j);
  104786. }
  104787. };
  104788. for (var i = 0; i <= maxMipLevel_1; i++) {
  104789. _loop_1(i);
  104790. }
  104791. scene.getEngine().resetTextureCache();
  104792. babylonTexture.isReady = function () {
  104793. return textureComplete();
  104794. };
  104795. textureCube[key] = babylonTexture;
  104796. }
  104797. return babylonTexture;
  104798. };
  104799. /**
  104800. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  104801. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  104802. * @param parameters Spectre SamplingParameters to apply
  104803. */
  104804. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  104805. var scene = babylonTexture.getScene();
  104806. if (!scene)
  104807. return;
  104808. var gl = (scene.getEngine())._gl;
  104809. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  104810. var internalTexture = babylonTexture._texture;
  104811. if (!internalTexture)
  104812. return;
  104813. var glTexture = internalTexture._webGLTexture;
  104814. gl.bindTexture(target, glTexture);
  104815. if (parameters.magFilter != null)
  104816. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  104817. if (parameters.minFilter != null)
  104818. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  104819. if (parameters.wrapS != null)
  104820. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  104821. if (parameters.wrapT != null)
  104822. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  104823. //set babylon wrap modes from sampling parameter
  104824. switch (parameters.wrapS) {
  104825. case 10497 /* REPEAT */:
  104826. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104827. break;
  104828. case 33071 /* CLAMP_TO_EDGE */:
  104829. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104830. break;
  104831. case 33648 /* MIRRORED_REPEAT */:
  104832. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104833. break;
  104834. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104835. }
  104836. switch (parameters.wrapT) {
  104837. case 10497 /* REPEAT */:
  104838. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104839. break;
  104840. case 33071 /* CLAMP_TO_EDGE */:
  104841. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104842. break;
  104843. case 33648 /* MIRRORED_REPEAT */:
  104844. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104845. break;
  104846. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104847. }
  104848. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  104849. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  104850. if (anisotropicExt) {
  104851. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  104852. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  104853. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  104854. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  104855. }
  104856. }
  104857. gl.bindTexture(target, null);
  104858. scene.getEngine().resetTextureCache();
  104859. };
  104860. /**
  104861. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  104862. */
  104863. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  104864. /**
  104865. * Controls anisotropic filtering for deserialized textures.
  104866. */
  104867. TextureUtils.MaxAnisotropy = 4;
  104868. TextureUtils._EnvironmentSampling = {
  104869. magFilter: 9729 /* LINEAR */,
  104870. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  104871. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104872. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104873. maxAnisotropy: 1
  104874. };
  104875. TextureUtils._EnvironmentSingleMipSampling = {
  104876. magFilter: 9729 /* LINEAR */,
  104877. minFilter: 9729 /* LINEAR */,
  104878. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104879. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104880. maxAnisotropy: 1
  104881. };
  104882. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  104883. /**
  104884. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  104885. */
  104886. TextureUtils.EnvironmentLODScale = 0.8;
  104887. /**
  104888. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  104889. */
  104890. TextureUtils.EnvironmentLODOffset = 1.0;
  104891. return TextureUtils;
  104892. }());
  104893. exports.TextureUtils = TextureUtils;
  104894. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3QjtRQUFwRixtQkFBYyxHQUFkLGNBQWMsQ0FBYTtRQUFTLFNBQUksR0FBSixJQUFJLENBQVc7UUFBUyxXQUFNLEdBQU4sTUFBTSxD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BQU0sRUFBRSxJQUFJLENBQUMsQ0FBQztRQUM3QixLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsaUJBQWlCLEVBQUUsQ0FBQztJQUMxQyxDQUFDO0lBN05EOztPQUVHO0lBQ1csb0NBQXVCLEdBQUcsbUJBQW1CLENBQUM7SUFFNUQ7O09BRUc7SUFDVywwQkFBYSxHQUFHLENBQUMsQ0FBQztJQXVOakIsaUNBQW9CLEdBQXVCO1FBQ3RELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsaUNBQXVDO1FBQ2hELEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFYSwwQ0FBNkIsR0FBdUI7UUFDL0QsU0FBUyxtQkFBeUI7UUFDbEMsU0FBUyxtQkFBeUI7UUFDbEMsS0FBSywyQkFBK0I7UUFDcEMsS0FBSywyQkFBK0I7UUFDcEMsYUFBYSxFQUFFLENBQUM7S0FDbkIsQ0FBQztJQUVGLGdGQUFnRjtJQUNoRjs7T0FFRztJQUNXLGdDQUFtQixHQUFHLEdBQUcsQ0FBQztJQUN4Qzs7T0FFRztJQUNXLGlDQUFvQixHQUFHLEdBQUcsQ0FBQztJQUM3QyxtQkFBQztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  104895. /***/ }),
  104896. /* 13 */
  104897. /***/ (function(module, exports, __webpack_require__) {
  104898. "use strict";
  104899. Object.defineProperty(exports, "__esModule", { value: true });
  104900. var babylonjs_1 = __webpack_require__(0);
  104901. var babylonjs_loaders_1 = __webpack_require__(14);
  104902. var viewerModel_1 = __webpack_require__(5);
  104903. var _1 = __webpack_require__(54);
  104904. /**
  104905. * An instance of the class is in charge of loading the model correctly.
  104906. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  104907. *
  104908. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  104909. */
  104910. var ModelLoader = /** @class */ (function () {
  104911. /**
  104912. * Create a new Model loader
  104913. * @param _viewer the viewer using this model loader
  104914. */
  104915. function ModelLoader(_observablesManager, _configurationContainer) {
  104916. this._observablesManager = _observablesManager;
  104917. this._configurationContainer = _configurationContainer;
  104918. this._disposed = false;
  104919. this._loaders = [];
  104920. this._loadId = 0;
  104921. this._plugins = [];
  104922. }
  104923. /**
  104924. * Adds a new plugin to the loader process.
  104925. *
  104926. * @param plugin the plugin name or the plugin itself
  104927. */
  104928. ModelLoader.prototype.addPlugin = function (plugin) {
  104929. var actualPlugin = {};
  104930. if (typeof plugin === 'string') {
  104931. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  104932. if (loadedPlugin) {
  104933. actualPlugin = loadedPlugin;
  104934. }
  104935. }
  104936. else {
  104937. actualPlugin = plugin;
  104938. }
  104939. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  104940. this._plugins.push(actualPlugin);
  104941. }
  104942. };
  104943. /**
  104944. * Load a model using predefined configuration
  104945. * @param modelConfiguration the modelConfiguration to use to load the model
  104946. */
  104947. ModelLoader.prototype.load = function (modelConfiguration) {
  104948. var _this = this;
  104949. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  104950. model.loadId = this._loadId++;
  104951. if (!modelConfiguration.url) {
  104952. model.state = viewerModel_1.ModelState.ERROR;
  104953. babylonjs_1.Tools.Error("No URL provided");
  104954. return model;
  104955. }
  104956. var base;
  104957. var filename;
  104958. if (modelConfiguration.file) {
  104959. base = "file:";
  104960. filename = modelConfiguration.file;
  104961. }
  104962. else {
  104963. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  104964. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  104965. }
  104966. var plugin = modelConfiguration.loader;
  104967. var scene = model.rootMesh.getScene();
  104968. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  104969. meshes.forEach(function (mesh) {
  104970. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104971. model.addMesh(mesh);
  104972. });
  104973. model.particleSystems = particleSystems;
  104974. model.skeletons = skeletons;
  104975. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  104976. var animationGroup = animationGroups_1[_i];
  104977. model.addAnimationGroup(animationGroup);
  104978. }
  104979. _this._checkAndRun("onLoaded", model);
  104980. scene.executeWhenReady(function () {
  104981. model.onLoadedObservable.notifyObservers(model);
  104982. });
  104983. }, function (progressEvent) {
  104984. _this._checkAndRun("onProgress", progressEvent);
  104985. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104986. }, function (scene, m, exception) {
  104987. model.state = viewerModel_1.ModelState.ERROR;
  104988. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  104989. _this._checkAndRun("onError", m, exception);
  104990. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104991. }, plugin);
  104992. if (model.loader.name === "gltf") {
  104993. var gltfLoader_1 = model.loader;
  104994. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  104995. gltfLoader_1.compileMaterials = true;
  104996. if (!modelConfiguration.file) {
  104997. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  104998. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  104999. };
  105000. }
  105001. // if ground is set to "mirror":
  105002. if (this._configurationContainer
  105003. && this._configurationContainer.configuration
  105004. && this._configurationContainer.configuration.ground
  105005. && typeof this._configurationContainer.configuration.ground === 'object'
  105006. && this._configurationContainer.configuration.ground.mirror) {
  105007. gltfLoader_1.useClipPlane = true;
  105008. }
  105009. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  105010. gltfLoader_1[functionName].add(function (payload) {
  105011. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  105012. });
  105013. });
  105014. gltfLoader_1.onParsedObservable.add(function (data) {
  105015. if (data && data.json && data.json['asset']) {
  105016. model.loadInfo = data.json['asset'];
  105017. }
  105018. });
  105019. gltfLoader_1.onCompleteObservable.add(function () {
  105020. model.loaderDone = true;
  105021. });
  105022. }
  105023. else {
  105024. model.loaderDone = true;
  105025. }
  105026. this._checkAndRun("onInit", model.loader, model);
  105027. this._loaders.push(model.loader);
  105028. return model;
  105029. };
  105030. ModelLoader.prototype.cancelLoad = function (model) {
  105031. var loader = model.loader || this._loaders[model.loadId];
  105032. // ATM only available in the GLTF Loader
  105033. if (loader && loader.name === "gltf") {
  105034. var gltfLoader = loader;
  105035. gltfLoader.dispose();
  105036. model.state = viewerModel_1.ModelState.CANCELED;
  105037. }
  105038. else {
  105039. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  105040. }
  105041. };
  105042. /**
  105043. * dispose the model loader.
  105044. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  105045. */
  105046. ModelLoader.prototype.dispose = function () {
  105047. this._loaders.forEach(function (loader) {
  105048. if (loader.name === "gltf") {
  105049. loader.dispose();
  105050. }
  105051. });
  105052. this._loaders.length = 0;
  105053. this._disposed = true;
  105054. };
  105055. ModelLoader.prototype._checkAndRun = function (functionName) {
  105056. var _this = this;
  105057. var payload = [];
  105058. for (var _i = 1; _i < arguments.length; _i++) {
  105059. payload[_i - 1] = arguments[_i];
  105060. }
  105061. if (this._disposed)
  105062. return;
  105063. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  105064. try {
  105065. plugin[functionName].apply(_this, payload);
  105066. }
  105067. catch (e) { }
  105068. });
  105069. };
  105070. return ModelLoader;
  105071. }());
  105072. exports.ModelLoader = ModelLoader;
  105073. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNl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LENBQUMsT0FBTyxFQUFFLENBQUM7YUFDdEM7UUFDTCxDQUFDLENBQUMsQ0FBQztRQUNILElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUN6QixJQUFJLENBQUMsU0FBUyxHQUFHLElBQUksQ0FBQztJQUMxQixDQUFDO0lBRU8sa0NBQVksR0FBcEIsVUFBcUIsWUFBb0I7UUFBekMsaUJBT0M7UUFQMEMsaUJBQXNCO2FBQXRCLFVBQXNCLEVBQXRCLHFCQUFzQixFQUF0QixJQUFzQjtZQUF0QixnQ0FBc0I7O1FBQzdELElBQUksSUFBSSxDQUFDLFNBQVM7WUFBRSxPQUFPO1FBQzNCLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFVBQUEsQ0FBQyxJQUFJLE9BQUEsQ0FBQyxDQUFDLFlBQVksQ0FBQyxFQUFmLENBQWUsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLE1BQU07WUFDckQsSUFBSTtnQkFDQSxNQUFNLENBQUMsWUFBWSxDQUFDLENBQUMsS0FBSyxDQUFDLEtBQUksRUFBRSxPQUFPLENBQUMsQ0FBQzthQUM3QztZQUFDLE9BQU8sQ0FBQyxFQUFFLEdBQUc7UUFDbkIsQ0FBQyxDQUFDLENBQUE7SUFDTixDQUFDO0lBQ0wsa0JBQUM7QUFBRCxDQUFDLEFBaExELElBZ0xDO0FBaExZLGtDQUFXIn0=
  105074. /***/ }),
  105075. /* 14 */
  105076. /***/ (function(module, exports, __webpack_require__) {
  105077. (function universalModuleDefinition(root, factory) {
  105078. var amdDependencies = [];
  105079. var BABYLON = root.BABYLON || this.BABYLON;
  105080. if(true) {
  105081. BABYLON = BABYLON || __webpack_require__(0);
  105082. module.exports = factory(BABYLON);
  105083. } else if(typeof define === 'function' && define.amd) {
  105084. amdDependencies.push("babylonjs");
  105085. define("babylonjs-loaders", amdDependencies, factory);
  105086. } else if(typeof exports === 'object') {
  105087. BABYLON = BABYLON || require("babylonjs");
  105088. exports["babylonjs-loaders"] = factory(BABYLON);
  105089. } else {
  105090. root["BABYLON"] = factory(BABYLON);
  105091. }
  105092. })(this, function(BABYLON) {
  105093. BABYLON = BABYLON || this.BABYLON;
  105094. 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};
  105095. 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)}}();
  105096. var BABYLON;
  105097. (function (BABYLON) {
  105098. var STLFileLoader = /** @class */ (function () {
  105099. function STLFileLoader() {
  105100. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105101. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105102. 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;
  105103. 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;
  105104. this.name = "stl";
  105105. // force data to come in as an ArrayBuffer
  105106. // we'll convert to string if it looks like it's an ASCII .stl
  105107. this.extensions = {
  105108. ".stl": { isBinary: true },
  105109. };
  105110. }
  105111. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105112. var matches;
  105113. if (typeof data !== "string") {
  105114. if (this.isBinary(data)) {
  105115. // binary .stl
  105116. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105117. this.parseBinary(babylonMesh, data);
  105118. if (meshes) {
  105119. meshes.push(babylonMesh);
  105120. }
  105121. return true;
  105122. }
  105123. // ASCII .stl
  105124. // convert to string
  105125. var array_buffer = new Uint8Array(data);
  105126. var str = '';
  105127. for (var i = 0; i < data.byteLength; i++) {
  105128. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105129. }
  105130. data = str;
  105131. }
  105132. //if arrived here, data is a string, containing the STLA data.
  105133. while (matches = this.solidPattern.exec(data)) {
  105134. var meshName = matches[1];
  105135. var meshNameFromEnd = matches[3];
  105136. if (meshName != meshNameFromEnd) {
  105137. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105138. return false;
  105139. }
  105140. // check meshesNames
  105141. if (meshesNames && meshName) {
  105142. if (meshesNames instanceof Array) {
  105143. if (!meshesNames.indexOf(meshName)) {
  105144. continue;
  105145. }
  105146. }
  105147. else {
  105148. if (meshName !== meshesNames) {
  105149. continue;
  105150. }
  105151. }
  105152. }
  105153. // stl mesh name can be empty as well
  105154. meshName = meshName || "stlmesh";
  105155. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105156. this.parseASCII(babylonMesh, matches[2]);
  105157. if (meshes) {
  105158. meshes.push(babylonMesh);
  105159. }
  105160. }
  105161. return true;
  105162. };
  105163. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105164. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105165. if (result) {
  105166. scene.createDefaultCameraOrLight();
  105167. }
  105168. return result;
  105169. };
  105170. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105171. var container = new BABYLON.AssetContainer(scene);
  105172. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105173. container.removeAllFromScene();
  105174. return container;
  105175. };
  105176. STLFileLoader.prototype.isBinary = function (data) {
  105177. // check if file size is correct for binary stl
  105178. var faceSize, nFaces, reader;
  105179. reader = new DataView(data);
  105180. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105181. nFaces = reader.getUint32(80, true);
  105182. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105183. return true;
  105184. }
  105185. // check characters higher than ASCII to confirm binary
  105186. var fileLength = reader.byteLength;
  105187. for (var index = 0; index < fileLength; index++) {
  105188. if (reader.getUint8(index) > 127) {
  105189. return true;
  105190. }
  105191. }
  105192. return false;
  105193. };
  105194. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105195. var reader = new DataView(data);
  105196. var faces = reader.getUint32(80, true);
  105197. var dataOffset = 84;
  105198. var faceLength = 12 * 4 + 2;
  105199. var offset = 0;
  105200. var positions = new Float32Array(faces * 3 * 3);
  105201. var normals = new Float32Array(faces * 3 * 3);
  105202. var indices = new Uint32Array(faces * 3);
  105203. var indicesCount = 0;
  105204. for (var face = 0; face < faces; face++) {
  105205. var start = dataOffset + face * faceLength;
  105206. var normalX = reader.getFloat32(start, true);
  105207. var normalY = reader.getFloat32(start + 4, true);
  105208. var normalZ = reader.getFloat32(start + 8, true);
  105209. for (var i = 1; i <= 3; i++) {
  105210. var vertexstart = start + i * 12;
  105211. // ordering is intentional to match ascii import
  105212. positions[offset] = reader.getFloat32(vertexstart, true);
  105213. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105214. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105215. normals[offset] = normalX;
  105216. normals[offset + 2] = normalY;
  105217. normals[offset + 1] = normalZ;
  105218. offset += 3;
  105219. }
  105220. indices[indicesCount] = indicesCount++;
  105221. indices[indicesCount] = indicesCount++;
  105222. indices[indicesCount] = indicesCount++;
  105223. }
  105224. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105225. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105226. mesh.setIndices(indices);
  105227. mesh.computeWorldMatrix(true);
  105228. };
  105229. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105230. var positions = [];
  105231. var normals = [];
  105232. var indices = [];
  105233. var indicesCount = 0;
  105234. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105235. var matches;
  105236. while (matches = this.facetsPattern.exec(solidData)) {
  105237. var facet = matches[1];
  105238. //one normal per face
  105239. var normalMatches = this.normalPattern.exec(facet);
  105240. this.normalPattern.lastIndex = 0;
  105241. if (!normalMatches) {
  105242. continue;
  105243. }
  105244. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105245. var vertexMatch;
  105246. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105247. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105248. normals.push(normal[0], normal[1], normal[2]);
  105249. }
  105250. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105251. this.vertexPattern.lastIndex = 0;
  105252. }
  105253. this.facetsPattern.lastIndex = 0;
  105254. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105255. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105256. mesh.setIndices(indices);
  105257. mesh.computeWorldMatrix(true);
  105258. };
  105259. return STLFileLoader;
  105260. }());
  105261. BABYLON.STLFileLoader = STLFileLoader;
  105262. if (BABYLON.SceneLoader) {
  105263. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105264. }
  105265. })(BABYLON || (BABYLON = {}));
  105266. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105267. var BABYLON;
  105268. (function (BABYLON) {
  105269. /**
  105270. * Class reading and parsing the MTL file bundled with the obj file.
  105271. */
  105272. var MTLFileLoader = /** @class */ (function () {
  105273. function MTLFileLoader() {
  105274. // All material loaded from the mtl will be set here
  105275. this.materials = [];
  105276. }
  105277. /**
  105278. * This function will read the mtl file and create each material described inside
  105279. * This function could be improve by adding :
  105280. * -some component missing (Ni, Tf...)
  105281. * -including the specific options available
  105282. *
  105283. * @param scene
  105284. * @param data
  105285. * @param rootUrl
  105286. */
  105287. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105288. if (data instanceof ArrayBuffer) {
  105289. return;
  105290. }
  105291. //Split the lines from the file
  105292. var lines = data.split('\n');
  105293. //Space char
  105294. var delimiter_pattern = /\s+/;
  105295. //Array with RGB colors
  105296. var color;
  105297. //New material
  105298. var material = null;
  105299. //Look at each line
  105300. for (var i = 0; i < lines.length; i++) {
  105301. var line = lines[i].trim();
  105302. // Blank line or comment
  105303. if (line.length === 0 || line.charAt(0) === '#') {
  105304. continue;
  105305. }
  105306. //Get the first parameter (keyword)
  105307. var pos = line.indexOf(' ');
  105308. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105309. key = key.toLowerCase();
  105310. //Get the data following the key
  105311. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105312. //This mtl keyword will create the new material
  105313. if (key === "newmtl") {
  105314. //Check if it is the first material.
  105315. // Materials specifications are described after this keyword.
  105316. if (material) {
  105317. //Add the previous material in the material array.
  105318. this.materials.push(material);
  105319. }
  105320. //Create a new material.
  105321. // value is the name of the material read in the mtl file
  105322. material = new BABYLON.StandardMaterial(value, scene);
  105323. }
  105324. else if (key === "kd" && material) {
  105325. // Diffuse color (color under white light) using RGB values
  105326. //value = "r g b"
  105327. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105328. //color = [r,g,b]
  105329. //Set tghe color into the material
  105330. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105331. }
  105332. else if (key === "ka" && material) {
  105333. // Ambient color (color under shadow) using RGB values
  105334. //value = "r g b"
  105335. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105336. //color = [r,g,b]
  105337. //Set tghe color into the material
  105338. material.ambientColor = BABYLON.Color3.FromArray(color);
  105339. }
  105340. else if (key === "ks" && material) {
  105341. // Specular color (color when light is reflected from shiny surface) using RGB values
  105342. //value = "r g b"
  105343. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105344. //color = [r,g,b]
  105345. //Set the color into the material
  105346. material.specularColor = BABYLON.Color3.FromArray(color);
  105347. }
  105348. else if (key === "ke" && material) {
  105349. // Emissive color using RGB values
  105350. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105351. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105352. }
  105353. else if (key === "ns" && material) {
  105354. //value = "Integer"
  105355. material.specularPower = parseFloat(value);
  105356. }
  105357. else if (key === "d" && material) {
  105358. //d is dissolve for current material. It mean alpha for BABYLON
  105359. material.alpha = parseFloat(value);
  105360. //Texture
  105361. //This part can be improved by adding the possible options of texture
  105362. }
  105363. else if (key === "map_ka" && material) {
  105364. // ambient texture map with a loaded image
  105365. //We must first get the folder of the image
  105366. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105367. }
  105368. else if (key === "map_kd" && material) {
  105369. // Diffuse texture map with a loaded image
  105370. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105371. }
  105372. else if (key === "map_ks" && material) {
  105373. // Specular texture map with a loaded image
  105374. //We must first get the folder of the image
  105375. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105376. }
  105377. else if (key === "map_ns") {
  105378. //Specular
  105379. //Specular highlight component
  105380. //We must first get the folder of the image
  105381. //
  105382. //Not supported by BABYLON
  105383. //
  105384. // continue;
  105385. }
  105386. else if (key === "map_bump" && material) {
  105387. //The bump texture
  105388. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105389. }
  105390. else if (key === "map_d" && material) {
  105391. // The dissolve of the material
  105392. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105393. //Options for illumination
  105394. }
  105395. else if (key === "illum") {
  105396. //Illumination
  105397. if (value === "0") {
  105398. //That mean Kd == Kd
  105399. }
  105400. else if (value === "1") {
  105401. //Color on and Ambient on
  105402. }
  105403. else if (value === "2") {
  105404. //Highlight on
  105405. }
  105406. else if (value === "3") {
  105407. //Reflection on and Ray trace on
  105408. }
  105409. else if (value === "4") {
  105410. //Transparency: Glass on, Reflection: Ray trace on
  105411. }
  105412. else if (value === "5") {
  105413. //Reflection: Fresnel on and Ray trace on
  105414. }
  105415. else if (value === "6") {
  105416. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105417. }
  105418. else if (value === "7") {
  105419. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105420. }
  105421. else if (value === "8") {
  105422. //Reflection on and Ray trace off
  105423. }
  105424. else if (value === "9") {
  105425. //Transparency: Glass on, Reflection: Ray trace off
  105426. }
  105427. else if (value === "10") {
  105428. //Casts shadows onto invisible surfaces
  105429. }
  105430. }
  105431. else {
  105432. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105433. }
  105434. }
  105435. //At the end of the file, add the last material
  105436. if (material) {
  105437. this.materials.push(material);
  105438. }
  105439. };
  105440. /**
  105441. * Gets the texture for the material.
  105442. *
  105443. * If the material is imported from input file,
  105444. * We sanitize the url to ensure it takes the textre from aside the material.
  105445. *
  105446. * @param rootUrl The root url to load from
  105447. * @param value The value stored in the mtl
  105448. * @return The Texture
  105449. */
  105450. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105451. if (!value) {
  105452. return null;
  105453. }
  105454. var url = rootUrl;
  105455. // Load from input file.
  105456. if (rootUrl === "file:") {
  105457. var lastDelimiter = value.lastIndexOf("\\");
  105458. if (lastDelimiter === -1) {
  105459. lastDelimiter = value.lastIndexOf("/");
  105460. }
  105461. if (lastDelimiter > -1) {
  105462. url += value.substr(lastDelimiter + 1);
  105463. }
  105464. else {
  105465. url += value;
  105466. }
  105467. }
  105468. // Not from input file.
  105469. else {
  105470. url += value;
  105471. }
  105472. return new BABYLON.Texture(url, scene);
  105473. };
  105474. return MTLFileLoader;
  105475. }());
  105476. BABYLON.MTLFileLoader = MTLFileLoader;
  105477. var OBJFileLoader = /** @class */ (function () {
  105478. function OBJFileLoader() {
  105479. this.name = "obj";
  105480. this.extensions = ".obj";
  105481. this.obj = /^o/;
  105482. this.group = /^g/;
  105483. this.mtllib = /^mtllib /;
  105484. this.usemtl = /^usemtl /;
  105485. this.smooth = /^s /;
  105486. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105487. // vn float float float
  105488. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105489. // vt float float
  105490. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105491. // f vertex vertex vertex ...
  105492. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105493. // f vertex/uvs vertex/uvs vertex/uvs ...
  105494. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105495. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105496. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105497. // f vertex//normal vertex//normal vertex//normal ...
  105498. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105499. }
  105500. /**
  105501. * Calls synchronously the MTL file attached to this obj.
  105502. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105503. * Without this function materials are not displayed in the first frame (but displayed after).
  105504. * In consequence it is impossible to get material information in your HTML file
  105505. *
  105506. * @param url The URL of the MTL file
  105507. * @param rootUrl
  105508. * @param onSuccess Callback function to be called when the MTL file is loaded
  105509. * @private
  105510. */
  105511. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105512. //The complete path to the mtl file
  105513. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105514. // Loads through the babylon tools to allow fileInput search.
  105515. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105516. };
  105517. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105518. //get the meshes from OBJ file
  105519. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  105520. return {
  105521. meshes: meshes,
  105522. particleSystems: [],
  105523. skeletons: [],
  105524. animationGroups: []
  105525. };
  105526. });
  105527. };
  105528. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105529. //Get the 3D model
  105530. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  105531. // return void
  105532. });
  105533. };
  105534. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105535. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  105536. var container = new BABYLON.AssetContainer(scene);
  105537. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  105538. container.removeAllFromScene();
  105539. return container;
  105540. });
  105541. };
  105542. /**
  105543. * Read the OBJ file and create an Array of meshes.
  105544. * Each mesh contains all information given by the OBJ and the MTL file.
  105545. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105546. *
  105547. * @param meshesNames
  105548. * @param scene BABYLON.Scene The scene where are displayed the data
  105549. * @param data String The content of the obj file
  105550. * @param rootUrl String The path to the folder
  105551. * @returns Array<AbstractMesh>
  105552. * @private
  105553. */
  105554. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105555. var _this = this;
  105556. var positions = []; //values for the positions of vertices
  105557. var normals = []; //Values for the normals
  105558. var uvs = []; //Values for the textures
  105559. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105560. var handledMesh; //The current mesh of meshes array
  105561. var indicesForBabylon = []; //The list of indices for VertexData
  105562. var wrappedPositionForBabylon = []; //The list of position in vectors
  105563. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105564. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105565. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105566. var curPositionInIndices = 0;
  105567. var hasMeshes = false; //Meshes are defined in the file
  105568. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105569. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105570. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105571. var triangles = []; //Indices from new triangles coming from polygons
  105572. var materialNameFromObj = ""; //The name of the current material
  105573. var fileToLoad = ""; //The name of the mtlFile to load
  105574. var materialsFromMTLFile = new MTLFileLoader();
  105575. var objMeshName = ""; //The name of the current obj mesh
  105576. var increment = 1; //Id for meshes created by the multimaterial
  105577. var isFirstMaterial = true;
  105578. /**
  105579. * Search for obj in the given array.
  105580. * This function is called to check if a couple of data already exists in an array.
  105581. *
  105582. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105583. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105584. * @param obj Array<number>
  105585. * @returns {boolean}
  105586. */
  105587. var isInArray = function (arr, obj) {
  105588. if (!arr[obj[0]])
  105589. arr[obj[0]] = { normals: [], idx: [] };
  105590. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105591. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105592. };
  105593. var isInArrayUV = function (arr, obj) {
  105594. if (!arr[obj[0]])
  105595. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105596. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105597. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105598. return arr[obj[0]].idx[idx];
  105599. }
  105600. return -1;
  105601. };
  105602. /**
  105603. * This function set the data for each triangle.
  105604. * Data are position, normals and uvs
  105605. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105606. * If the tuple already exist, add only their indice
  105607. *
  105608. * @param indicePositionFromObj Integer The index in positions array
  105609. * @param indiceUvsFromObj Integer The index in uvs array
  105610. * @param indiceNormalFromObj Integer The index in normals array
  105611. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105612. * @param textureVectorFromOBJ Vector3 The value of uvs
  105613. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105614. */
  105615. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105616. //Check if this tuple already exists in the list of tuples
  105617. var _index;
  105618. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105619. _index = isInArrayUV(tuplePosNorm, [
  105620. indicePositionFromObj,
  105621. indiceNormalFromObj,
  105622. indiceUvsFromObj
  105623. ]);
  105624. }
  105625. else {
  105626. _index = isInArray(tuplePosNorm, [
  105627. indicePositionFromObj,
  105628. indiceNormalFromObj
  105629. ]);
  105630. }
  105631. //If it not exists
  105632. if (_index == -1) {
  105633. //Add an new indice.
  105634. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105635. //We add vertices data in this order
  105636. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105637. //Push the position of vertice for Babylon
  105638. //Each element is a BABYLON.Vector3(x,y,z)
  105639. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105640. //Push the uvs for Babylon
  105641. //Each element is a BABYLON.Vector3(u,v)
  105642. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105643. //Push the normals for Babylon
  105644. //Each element is a BABYLON.Vector3(x,y,z)
  105645. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105646. //Add the tuple in the comparison list
  105647. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105648. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105649. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105650. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105651. }
  105652. else {
  105653. //The tuple already exists
  105654. //Add the index of the already existing tuple
  105655. //At this index we can get the value of position, normal and uvs of vertex
  105656. indicesForBabylon.push(_index);
  105657. }
  105658. };
  105659. /**
  105660. * Transform BABYLON.Vector() object onto 3 digits in an array
  105661. */
  105662. var unwrapData = function () {
  105663. //Every array has the same length
  105664. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105665. //Push the x, y, z values of each element in the unwrapped array
  105666. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105667. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105668. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105669. }
  105670. // Reset arrays for the next new meshes
  105671. wrappedPositionForBabylon = [];
  105672. wrappedNormalsForBabylon = [];
  105673. wrappedUvsForBabylon = [];
  105674. tuplePosNorm = [];
  105675. curPositionInIndices = 0;
  105676. };
  105677. /**
  105678. * Create triangles from polygons by recursion
  105679. * The best to understand how it works is to draw it in the same time you get the recursion.
  105680. * It is important to notice that a triangle is a polygon
  105681. * We get 4 patterns of face defined in OBJ File :
  105682. * facePattern1 = ["1","2","3","4","5","6"]
  105683. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105684. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105685. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105686. * Each pattern is divided by the same method
  105687. * @param face Array[String] The indices of elements
  105688. * @param v Integer The variable to increment
  105689. */
  105690. var getTriangles = function (face, v) {
  105691. //Work for each element of the array
  105692. if (v + 1 < face.length) {
  105693. //Add on the triangle variable the indexes to obtain triangles
  105694. triangles.push(face[0], face[v], face[v + 1]);
  105695. //Incrementation for recursion
  105696. v += 1;
  105697. //Recursion
  105698. getTriangles(face, v);
  105699. }
  105700. //Result obtained after 2 iterations:
  105701. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105702. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105703. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105704. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105705. };
  105706. /**
  105707. * Create triangles and push the data for each polygon for the pattern 1
  105708. * In this pattern we get vertice positions
  105709. * @param face
  105710. * @param v
  105711. */
  105712. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105713. //Get the indices of triangles for each polygon
  105714. getTriangles(face, v);
  105715. //For each element in the triangles array.
  105716. //This var could contains 1 to an infinity of triangles
  105717. for (var k = 0; k < triangles.length; k++) {
  105718. // Set position indice
  105719. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105720. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105721. positions[indicePositionFromObj], //Get the vectors data
  105722. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105723. );
  105724. }
  105725. //Reset variable for the next line
  105726. triangles = [];
  105727. };
  105728. /**
  105729. * Create triangles and push the data for each polygon for the pattern 2
  105730. * In this pattern we get vertice positions and uvsu
  105731. * @param face
  105732. * @param v
  105733. */
  105734. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105735. //Get the indices of triangles for each polygon
  105736. getTriangles(face, v);
  105737. for (var k = 0; k < triangles.length; k++) {
  105738. //triangle[k] = "1/1"
  105739. //Split the data for getting position and uv
  105740. var point = triangles[k].split("/"); // ["1", "1"]
  105741. //Set position indice
  105742. var indicePositionFromObj = parseInt(point[0]) - 1;
  105743. //Set uv indice
  105744. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105745. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105746. positions[indicePositionFromObj], //Get the values for each element
  105747. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105748. );
  105749. }
  105750. //Reset variable for the next line
  105751. triangles = [];
  105752. };
  105753. /**
  105754. * Create triangles and push the data for each polygon for the pattern 3
  105755. * In this pattern we get vertice positions, uvs and normals
  105756. * @param face
  105757. * @param v
  105758. */
  105759. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105760. //Get the indices of triangles for each polygon
  105761. getTriangles(face, v);
  105762. for (var k = 0; k < triangles.length; k++) {
  105763. //triangle[k] = "1/1/1"
  105764. //Split the data for getting position, uv, and normals
  105765. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105766. // Set position indice
  105767. var indicePositionFromObj = parseInt(point[0]) - 1;
  105768. // Set uv indice
  105769. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105770. // Set normal indice
  105771. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105772. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105773. );
  105774. }
  105775. //Reset variable for the next line
  105776. triangles = [];
  105777. };
  105778. /**
  105779. * Create triangles and push the data for each polygon for the pattern 4
  105780. * In this pattern we get vertice positions and normals
  105781. * @param face
  105782. * @param v
  105783. */
  105784. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105785. getTriangles(face, v);
  105786. for (var k = 0; k < triangles.length; k++) {
  105787. //triangle[k] = "1//1"
  105788. //Split the data for getting position and normals
  105789. var point = triangles[k].split("//"); // ["1", "1"]
  105790. // We check indices, and normals
  105791. var indicePositionFromObj = parseInt(point[0]) - 1;
  105792. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105793. setData(indicePositionFromObj, 1, //Default value for uv
  105794. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105795. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105796. }
  105797. //Reset variable for the next line
  105798. triangles = [];
  105799. };
  105800. var addPreviousObjMesh = function () {
  105801. //Check if it is not the first mesh. Otherwise we don't have data.
  105802. if (meshesFromObj.length > 0) {
  105803. //Get the previous mesh for applying the data about the faces
  105804. //=> in obj file, faces definition append after the name of the mesh
  105805. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105806. //Set the data into Array for the mesh
  105807. unwrapData();
  105808. // Reverse tab. Otherwise face are displayed in the wrong sens
  105809. indicesForBabylon.reverse();
  105810. //Set the information for the mesh
  105811. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105812. handledMesh.indices = indicesForBabylon.slice();
  105813. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105814. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105815. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105816. //Reset the array for the next mesh
  105817. indicesForBabylon = [];
  105818. unwrappedPositionsForBabylon = [];
  105819. unwrappedNormalsForBabylon = [];
  105820. unwrappedUVForBabylon = [];
  105821. }
  105822. };
  105823. //Main function
  105824. //Split the file into lines
  105825. var lines = data.split('\n');
  105826. //Look at each line
  105827. for (var i = 0; i < lines.length; i++) {
  105828. var line = lines[i].trim();
  105829. var result;
  105830. //Comment or newLine
  105831. if (line.length === 0 || line.charAt(0) === '#') {
  105832. continue;
  105833. //Get information about one position possible for the vertices
  105834. }
  105835. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105836. //Create a Vector3 with the position x, y, z
  105837. //Value of result:
  105838. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105839. //Add the Vector in the list of positions
  105840. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105841. }
  105842. else if ((result = this.normalPattern.exec(line)) !== null) {
  105843. //Create a Vector3 with the normals x, y, z
  105844. //Value of result
  105845. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105846. //Add the Vector in the list of normals
  105847. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105848. }
  105849. else if ((result = this.uvPattern.exec(line)) !== null) {
  105850. //Create a Vector2 with the normals u, v
  105851. //Value of result
  105852. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105853. //Add the Vector in the list of uvs
  105854. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105855. //Identify patterns of faces
  105856. //Face could be defined in different type of pattern
  105857. }
  105858. else if ((result = this.facePattern3.exec(line)) !== null) {
  105859. //Value of result:
  105860. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105861. //Set the data for this face
  105862. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105863. 1);
  105864. }
  105865. else if ((result = this.facePattern4.exec(line)) !== null) {
  105866. //Value of result:
  105867. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105868. //Set the data for this face
  105869. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105870. 1);
  105871. }
  105872. else if ((result = this.facePattern2.exec(line)) !== null) {
  105873. //Value of result:
  105874. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105875. //Set the data for this face
  105876. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105877. 1);
  105878. }
  105879. else if ((result = this.facePattern1.exec(line)) !== null) {
  105880. //Value of result
  105881. //["f 1 2 3", "1 2 3"...]
  105882. //Set the data for this face
  105883. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105884. 1);
  105885. //Define a mesh or an object
  105886. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105887. }
  105888. else if (this.group.test(line) || this.obj.test(line)) {
  105889. //Create a new mesh corresponding to the name of the group.
  105890. //Definition of the mesh
  105891. var objMesh =
  105892. //Set the name of the current obj mesh
  105893. {
  105894. name: line.substring(2).trim(),
  105895. indices: undefined,
  105896. positions: undefined,
  105897. normals: undefined,
  105898. uvs: undefined,
  105899. materialName: ""
  105900. };
  105901. addPreviousObjMesh();
  105902. //Push the last mesh created with only the name
  105903. meshesFromObj.push(objMesh);
  105904. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105905. hasMeshes = true;
  105906. isFirstMaterial = true;
  105907. increment = 1;
  105908. //Keyword for applying a material
  105909. }
  105910. else if (this.usemtl.test(line)) {
  105911. //Get the name of the material
  105912. materialNameFromObj = line.substring(7).trim();
  105913. //If this new material is in the same mesh
  105914. if (!isFirstMaterial) {
  105915. //Set the data for the previous mesh
  105916. addPreviousObjMesh();
  105917. //Create a new mesh
  105918. var objMesh =
  105919. //Set the name of the current obj mesh
  105920. {
  105921. name: objMeshName + "_mm" + increment.toString(),
  105922. indices: undefined,
  105923. positions: undefined,
  105924. normals: undefined,
  105925. uvs: undefined,
  105926. materialName: materialNameFromObj
  105927. };
  105928. increment++;
  105929. //If meshes are already defined
  105930. meshesFromObj.push(objMesh);
  105931. }
  105932. //Set the material name if the previous line define a mesh
  105933. if (hasMeshes && isFirstMaterial) {
  105934. //Set the material name to the previous mesh (1 material per mesh)
  105935. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105936. isFirstMaterial = false;
  105937. }
  105938. //Keyword for loading the mtl file
  105939. }
  105940. else if (this.mtllib.test(line)) {
  105941. //Get the name of mtl file
  105942. fileToLoad = line.substring(7).trim();
  105943. //Apply smoothing
  105944. }
  105945. else if (this.smooth.test(line)) {
  105946. // smooth shading => apply smoothing
  105947. //Toda y I don't know it work with babylon and with obj.
  105948. //With the obj file an integer is set
  105949. }
  105950. else {
  105951. //If there is another possibility
  105952. console.log("Unhandled expression at line : " + line);
  105953. }
  105954. }
  105955. //At the end of the file, add the last mesh into the meshesFromObj array
  105956. if (hasMeshes) {
  105957. //Set the data for the last mesh
  105958. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105959. //Reverse indices for displaying faces in the good sens
  105960. indicesForBabylon.reverse();
  105961. //Get the good array
  105962. unwrapData();
  105963. //Set array
  105964. handledMesh.indices = indicesForBabylon;
  105965. handledMesh.positions = unwrappedPositionsForBabylon;
  105966. handledMesh.normals = unwrappedNormalsForBabylon;
  105967. handledMesh.uvs = unwrappedUVForBabylon;
  105968. }
  105969. //If any o or g keyword found, create a mesj with a random id
  105970. if (!hasMeshes) {
  105971. // reverse tab of indices
  105972. indicesForBabylon.reverse();
  105973. //Get positions normals uvs
  105974. unwrapData();
  105975. //Set data for one mesh
  105976. meshesFromObj.push({
  105977. name: BABYLON.Geometry.RandomId(),
  105978. indices: indicesForBabylon,
  105979. positions: unwrappedPositionsForBabylon,
  105980. normals: unwrappedNormalsForBabylon,
  105981. uvs: unwrappedUVForBabylon,
  105982. materialName: materialNameFromObj
  105983. });
  105984. }
  105985. //Create a BABYLON.Mesh list
  105986. var babylonMeshesArray = []; //The mesh for babylon
  105987. var materialToUse = new Array();
  105988. //Set data for each mesh
  105989. for (var j = 0; j < meshesFromObj.length; j++) {
  105990. //check meshesNames (stlFileLoader)
  105991. if (meshesNames && meshesFromObj[j].name) {
  105992. if (meshesNames instanceof Array) {
  105993. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105994. continue;
  105995. }
  105996. }
  105997. else {
  105998. if (meshesFromObj[j].name !== meshesNames) {
  105999. continue;
  106000. }
  106001. }
  106002. }
  106003. //Get the current mesh
  106004. //Set the data with VertexBuffer for each mesh
  106005. handledMesh = meshesFromObj[j];
  106006. //Create a BABYLON.Mesh with the name of the obj mesh
  106007. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106008. //Push the name of the material to an array
  106009. //This is indispensable for the importMesh function
  106010. materialToUse.push(meshesFromObj[j].materialName);
  106011. var vertexData = new BABYLON.VertexData(); //The container for the values
  106012. //Set the data for the babylonMesh
  106013. vertexData.positions = handledMesh.positions;
  106014. vertexData.normals = handledMesh.normals;
  106015. vertexData.uvs = handledMesh.uvs;
  106016. vertexData.indices = handledMesh.indices;
  106017. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106018. vertexData.applyToMesh(babylonMesh);
  106019. if (OBJFileLoader.INVERT_Y) {
  106020. babylonMesh.scaling.y *= -1;
  106021. }
  106022. //Push the mesh into an array
  106023. babylonMeshesArray.push(babylonMesh);
  106024. }
  106025. var mtlPromises = [];
  106026. //load the materials
  106027. //Check if we have a file to load
  106028. if (fileToLoad !== "") {
  106029. //Load the file synchronously
  106030. mtlPromises.push(new Promise(function (resolve, reject) {
  106031. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106032. try {
  106033. //Create materials thanks MTLLoader function
  106034. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106035. //Look at each material loaded in the mtl file
  106036. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106037. //Three variables to get all meshes with the same material
  106038. var startIndex = 0;
  106039. var _indices = [];
  106040. var _index;
  106041. //The material from MTL file is used in the meshes loaded
  106042. //Push the indice in an array
  106043. //Check if the material is not used for another mesh
  106044. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  106045. _indices.push(_index);
  106046. startIndex = _index + 1;
  106047. }
  106048. //If the material is not used dispose it
  106049. if (_index == -1 && _indices.length == 0) {
  106050. //If the material is not needed, remove it
  106051. materialsFromMTLFile.materials[n].dispose();
  106052. }
  106053. else {
  106054. for (var o = 0; o < _indices.length; o++) {
  106055. //Apply the material to the BABYLON.Mesh for each mesh with the material
  106056. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  106057. }
  106058. }
  106059. }
  106060. resolve();
  106061. }
  106062. catch (e) {
  106063. reject(e);
  106064. }
  106065. });
  106066. }));
  106067. }
  106068. //Return an array with all BABYLON.Mesh
  106069. return Promise.all(mtlPromises).then(function () {
  106070. return babylonMeshesArray;
  106071. });
  106072. };
  106073. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  106074. OBJFileLoader.INVERT_Y = false;
  106075. return OBJFileLoader;
  106076. }());
  106077. BABYLON.OBJFileLoader = OBJFileLoader;
  106078. if (BABYLON.SceneLoader) {
  106079. //Add this loader into the register plugin
  106080. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  106081. }
  106082. })(BABYLON || (BABYLON = {}));
  106083. //# sourceMappingURL=babylon.objFileLoader.js.map
  106084. var BABYLON;
  106085. (function (BABYLON) {
  106086. /**
  106087. * Mode that determines the coordinate system to use.
  106088. */
  106089. var GLTFLoaderCoordinateSystemMode;
  106090. (function (GLTFLoaderCoordinateSystemMode) {
  106091. /**
  106092. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  106093. */
  106094. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  106095. /**
  106096. * Sets the useRightHandedSystem flag on the scene.
  106097. */
  106098. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106099. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106100. /**
  106101. * Mode that determines what animations will start.
  106102. */
  106103. var GLTFLoaderAnimationStartMode;
  106104. (function (GLTFLoaderAnimationStartMode) {
  106105. /**
  106106. * No animation will start.
  106107. */
  106108. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106109. /**
  106110. * The first animation will start.
  106111. */
  106112. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106113. /**
  106114. * All animations will start.
  106115. */
  106116. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106117. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106118. /**
  106119. * Loader state.
  106120. */
  106121. var GLTFLoaderState;
  106122. (function (GLTFLoaderState) {
  106123. /**
  106124. * The asset is loading.
  106125. */
  106126. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  106127. /**
  106128. * The asset is ready for rendering.
  106129. */
  106130. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  106131. /**
  106132. * The asset is completely loaded.
  106133. */
  106134. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  106135. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106136. /**
  106137. * File loader for loading glTF files into a scene.
  106138. */
  106139. var GLTFFileLoader = /** @class */ (function () {
  106140. function GLTFFileLoader() {
  106141. // #region Common options
  106142. /**
  106143. * Raised when the asset has been parsed
  106144. */
  106145. this.onParsedObservable = new BABYLON.Observable();
  106146. // #endregion
  106147. // #region V2 options
  106148. /**
  106149. * The coordinate system mode. Defaults to AUTO.
  106150. */
  106151. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106152. /**
  106153. * The animation start mode. Defaults to FIRST.
  106154. */
  106155. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106156. /**
  106157. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  106158. */
  106159. this.compileMaterials = false;
  106160. /**
  106161. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  106162. */
  106163. this.useClipPlane = false;
  106164. /**
  106165. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  106166. */
  106167. this.compileShadowGenerators = false;
  106168. /**
  106169. * Defines if the Alpha blended materials are only applied as coverage.
  106170. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  106171. * If true, no extra effects are applied to transparent pixels.
  106172. */
  106173. this.transparencyAsCoverage = false;
  106174. /** @hidden */
  106175. this._normalizeAnimationGroupsToBeginAtZero = true;
  106176. /**
  106177. * Function called before loading a url referenced by the asset.
  106178. */
  106179. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106180. /**
  106181. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106182. */
  106183. this.onMeshLoadedObservable = new BABYLON.Observable();
  106184. /**
  106185. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106186. */
  106187. this.onTextureLoadedObservable = new BABYLON.Observable();
  106188. /**
  106189. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  106190. */
  106191. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106192. /**
  106193. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  106194. */
  106195. this.onCameraLoadedObservable = new BABYLON.Observable();
  106196. /**
  106197. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  106198. * For assets with LODs, raised when all of the LODs are complete.
  106199. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  106200. */
  106201. this.onCompleteObservable = new BABYLON.Observable();
  106202. /**
  106203. * Observable raised after the loader is disposed.
  106204. */
  106205. this.onDisposeObservable = new BABYLON.Observable();
  106206. /**
  106207. * Observable raised after a loader extension is created.
  106208. * Set additional options for a loader extension in this event.
  106209. */
  106210. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106211. // #endregion
  106212. this._loader = null;
  106213. /**
  106214. * Name of the loader ("gltf")
  106215. */
  106216. this.name = "gltf";
  106217. /**
  106218. * Supported file extensions of the loader (.gltf, .glb)
  106219. */
  106220. this.extensions = {
  106221. ".gltf": { isBinary: false },
  106222. ".glb": { isBinary: true }
  106223. };
  106224. this._logIndentLevel = 0;
  106225. this._loggingEnabled = false;
  106226. /** @hidden */
  106227. this._log = this._logDisabled;
  106228. this._capturePerformanceCounters = false;
  106229. /** @hidden */
  106230. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  106231. /** @hidden */
  106232. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  106233. }
  106234. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106235. /**
  106236. * Raised when the asset has been parsed
  106237. */
  106238. set: function (callback) {
  106239. if (this._onParsedObserver) {
  106240. this.onParsedObservable.remove(this._onParsedObserver);
  106241. }
  106242. this._onParsedObserver = this.onParsedObservable.add(callback);
  106243. },
  106244. enumerable: true,
  106245. configurable: true
  106246. });
  106247. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106248. /**
  106249. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106250. */
  106251. set: function (callback) {
  106252. if (this._onMeshLoadedObserver) {
  106253. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106254. }
  106255. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106256. },
  106257. enumerable: true,
  106258. configurable: true
  106259. });
  106260. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106261. /**
  106262. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  106263. */
  106264. set: function (callback) {
  106265. if (this._onTextureLoadedObserver) {
  106266. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106267. }
  106268. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106269. },
  106270. enumerable: true,
  106271. configurable: true
  106272. });
  106273. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106274. /**
  106275. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  106276. */
  106277. set: function (callback) {
  106278. if (this._onMaterialLoadedObserver) {
  106279. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106280. }
  106281. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106282. },
  106283. enumerable: true,
  106284. configurable: true
  106285. });
  106286. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  106287. /**
  106288. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  106289. */
  106290. set: function (callback) {
  106291. if (this._onCameraLoadedObserver) {
  106292. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  106293. }
  106294. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  106295. },
  106296. enumerable: true,
  106297. configurable: true
  106298. });
  106299. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106300. /**
  106301. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  106302. */
  106303. set: function (callback) {
  106304. if (this._onCompleteObserver) {
  106305. this.onCompleteObservable.remove(this._onCompleteObserver);
  106306. }
  106307. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106308. },
  106309. enumerable: true,
  106310. configurable: true
  106311. });
  106312. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106313. /**
  106314. * Callback raised after the loader is disposed.
  106315. */
  106316. set: function (callback) {
  106317. if (this._onDisposeObserver) {
  106318. this.onDisposeObservable.remove(this._onDisposeObserver);
  106319. }
  106320. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106321. },
  106322. enumerable: true,
  106323. configurable: true
  106324. });
  106325. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106326. /**
  106327. * Callback raised after a loader extension is created.
  106328. */
  106329. set: function (callback) {
  106330. if (this._onExtensionLoadedObserver) {
  106331. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106332. }
  106333. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106334. },
  106335. enumerable: true,
  106336. configurable: true
  106337. });
  106338. /**
  106339. * Returns a promise that resolves when the asset is completely loaded.
  106340. * @returns a promise that resolves when the asset is completely loaded.
  106341. */
  106342. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106343. var _this = this;
  106344. return new Promise(function (resolve) {
  106345. _this.onCompleteObservable.addOnce(function () {
  106346. resolve();
  106347. });
  106348. });
  106349. };
  106350. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106351. /**
  106352. * The loader state or null if the loader is not active.
  106353. */
  106354. get: function () {
  106355. return this._loader ? this._loader.state : null;
  106356. },
  106357. enumerable: true,
  106358. configurable: true
  106359. });
  106360. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  106361. /**
  106362. * Defines if the loader logging is enabled.
  106363. */
  106364. get: function () {
  106365. return this._loggingEnabled;
  106366. },
  106367. set: function (value) {
  106368. if (this._loggingEnabled === value) {
  106369. return;
  106370. }
  106371. this._loggingEnabled = value;
  106372. if (this._loggingEnabled) {
  106373. this._log = this._logEnabled;
  106374. }
  106375. else {
  106376. this._log = this._logDisabled;
  106377. }
  106378. },
  106379. enumerable: true,
  106380. configurable: true
  106381. });
  106382. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  106383. /**
  106384. * Defines if the loader should capture performance counters.
  106385. */
  106386. get: function () {
  106387. return this._capturePerformanceCounters;
  106388. },
  106389. set: function (value) {
  106390. if (this._capturePerformanceCounters === value) {
  106391. return;
  106392. }
  106393. this._capturePerformanceCounters = value;
  106394. if (this._capturePerformanceCounters) {
  106395. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  106396. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  106397. }
  106398. else {
  106399. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  106400. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  106401. }
  106402. },
  106403. enumerable: true,
  106404. configurable: true
  106405. });
  106406. /**
  106407. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106408. */
  106409. GLTFFileLoader.prototype.dispose = function () {
  106410. if (this._loader) {
  106411. this._loader.dispose();
  106412. this._loader = null;
  106413. }
  106414. this._clear();
  106415. this.onDisposeObservable.notifyObservers(undefined);
  106416. this.onDisposeObservable.clear();
  106417. };
  106418. /** @hidden */
  106419. GLTFFileLoader.prototype._clear = function () {
  106420. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106421. this.onMeshLoadedObservable.clear();
  106422. this.onTextureLoadedObservable.clear();
  106423. this.onMaterialLoadedObservable.clear();
  106424. this.onCameraLoadedObservable.clear();
  106425. this.onCompleteObservable.clear();
  106426. this.onExtensionLoadedObservable.clear();
  106427. };
  106428. /**
  106429. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  106430. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106431. * @param scene the scene the meshes should be added to
  106432. * @param data the glTF data to load
  106433. * @param rootUrl root url to load from
  106434. * @param onProgress event that fires when loading progress has occured
  106435. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106436. */
  106437. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106438. var _this = this;
  106439. return Promise.resolve().then(function () {
  106440. var loaderData = _this._parse(data);
  106441. _this._loader = _this._getLoader(loaderData);
  106442. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106443. });
  106444. };
  106445. /**
  106446. * Imports all objects from the loaded glTF data and adds them to the scene
  106447. * @param scene the scene the objects should be added to
  106448. * @param data the glTF data to load
  106449. * @param rootUrl root url to load from
  106450. * @param onProgress event that fires when loading progress has occured
  106451. * @returns a promise which completes when objects have been loaded to the scene
  106452. */
  106453. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106454. var _this = this;
  106455. return Promise.resolve().then(function () {
  106456. var loaderData = _this._parse(data);
  106457. _this._loader = _this._getLoader(loaderData);
  106458. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106459. });
  106460. };
  106461. /**
  106462. * Load into an asset container.
  106463. * @param scene The scene to load into
  106464. * @param data The data to import
  106465. * @param rootUrl The root url for scene and resources
  106466. * @param onProgress The callback when the load progresses
  106467. * @returns The loaded asset container
  106468. */
  106469. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106470. var _this = this;
  106471. return Promise.resolve().then(function () {
  106472. var loaderData = _this._parse(data);
  106473. _this._loader = _this._getLoader(loaderData);
  106474. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106475. var container = new BABYLON.AssetContainer(scene);
  106476. Array.prototype.push.apply(container.meshes, result.meshes);
  106477. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106478. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106479. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  106480. container.removeAllFromScene();
  106481. return container;
  106482. });
  106483. });
  106484. };
  106485. /**
  106486. * If the data string can be loaded directly.
  106487. * @param data string contianing the file data
  106488. * @returns if the data can be loaded directly
  106489. */
  106490. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106491. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106492. };
  106493. /**
  106494. * Instantiates a glTF file loader plugin.
  106495. * @returns the created plugin
  106496. */
  106497. GLTFFileLoader.prototype.createPlugin = function () {
  106498. return new GLTFFileLoader();
  106499. };
  106500. GLTFFileLoader.prototype._parse = function (data) {
  106501. this._startPerformanceCounter("Parse");
  106502. var parsedData;
  106503. if (data instanceof ArrayBuffer) {
  106504. this._log("Parsing binary");
  106505. parsedData = this._parseBinary(data);
  106506. }
  106507. else {
  106508. this._log("Parsing JSON");
  106509. this._log("JSON length: " + data.length);
  106510. parsedData = {
  106511. json: JSON.parse(data),
  106512. bin: null
  106513. };
  106514. }
  106515. this.onParsedObservable.notifyObservers(parsedData);
  106516. this.onParsedObservable.clear();
  106517. this._endPerformanceCounter("Parse");
  106518. return parsedData;
  106519. };
  106520. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106521. var asset = loaderData.json.asset || {};
  106522. this._log("Asset version: " + asset.version);
  106523. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  106524. asset.generator && this._log("Asset generator: " + asset.generator);
  106525. var version = GLTFFileLoader._parseVersion(asset.version);
  106526. if (!version) {
  106527. throw new Error("Invalid version: " + asset.version);
  106528. }
  106529. if (asset.minVersion !== undefined) {
  106530. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106531. if (!minVersion) {
  106532. throw new Error("Invalid minimum version: " + asset.minVersion);
  106533. }
  106534. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  106535. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106536. }
  106537. }
  106538. var createLoaders = {
  106539. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  106540. 2: GLTFFileLoader._CreateGLTFLoaderV2
  106541. };
  106542. var createLoader = createLoaders[version.major];
  106543. if (!createLoader) {
  106544. throw new Error("Unsupported version: " + asset.version);
  106545. }
  106546. return createLoader(this);
  106547. };
  106548. GLTFFileLoader.prototype._parseBinary = function (data) {
  106549. var Binary = {
  106550. Magic: 0x46546C67
  106551. };
  106552. this._log("Binary length: " + data.byteLength);
  106553. var binaryReader = new BinaryReader(data);
  106554. var magic = binaryReader.readUint32();
  106555. if (magic !== Binary.Magic) {
  106556. throw new Error("Unexpected magic: " + magic);
  106557. }
  106558. var version = binaryReader.readUint32();
  106559. if (this.loggingEnabled) {
  106560. this._log("Binary version: " + version);
  106561. }
  106562. switch (version) {
  106563. case 1: return this._parseV1(binaryReader);
  106564. case 2: return this._parseV2(binaryReader);
  106565. }
  106566. throw new Error("Unsupported version: " + version);
  106567. };
  106568. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  106569. var ContentFormat = {
  106570. JSON: 0
  106571. };
  106572. var length = binaryReader.readUint32();
  106573. if (length != binaryReader.getLength()) {
  106574. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106575. }
  106576. var contentLength = binaryReader.readUint32();
  106577. var contentFormat = binaryReader.readUint32();
  106578. var content;
  106579. switch (contentFormat) {
  106580. case ContentFormat.JSON: {
  106581. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106582. break;
  106583. }
  106584. default: {
  106585. throw new Error("Unexpected content format: " + contentFormat);
  106586. }
  106587. }
  106588. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106589. var body = binaryReader.readUint8Array(bytesRemaining);
  106590. return {
  106591. json: content,
  106592. bin: body
  106593. };
  106594. };
  106595. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  106596. var ChunkFormat = {
  106597. JSON: 0x4E4F534A,
  106598. BIN: 0x004E4942
  106599. };
  106600. var length = binaryReader.readUint32();
  106601. if (length !== binaryReader.getLength()) {
  106602. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106603. }
  106604. // JSON chunk
  106605. var chunkLength = binaryReader.readUint32();
  106606. var chunkFormat = binaryReader.readUint32();
  106607. if (chunkFormat !== ChunkFormat.JSON) {
  106608. throw new Error("First chunk format is not JSON");
  106609. }
  106610. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106611. // Look for BIN chunk
  106612. var bin = null;
  106613. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106614. var chunkLength_1 = binaryReader.readUint32();
  106615. var chunkFormat_1 = binaryReader.readUint32();
  106616. switch (chunkFormat_1) {
  106617. case ChunkFormat.JSON: {
  106618. throw new Error("Unexpected JSON chunk");
  106619. }
  106620. case ChunkFormat.BIN: {
  106621. bin = binaryReader.readUint8Array(chunkLength_1);
  106622. break;
  106623. }
  106624. default: {
  106625. // ignore unrecognized chunkFormat
  106626. binaryReader.skipBytes(chunkLength_1);
  106627. break;
  106628. }
  106629. }
  106630. }
  106631. return {
  106632. json: json,
  106633. bin: bin
  106634. };
  106635. };
  106636. GLTFFileLoader._parseVersion = function (version) {
  106637. if (version === "1.0" || version === "1.0.1") {
  106638. return {
  106639. major: 1,
  106640. minor: 0
  106641. };
  106642. }
  106643. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106644. if (!match) {
  106645. return null;
  106646. }
  106647. return {
  106648. major: parseInt(match[1]),
  106649. minor: parseInt(match[2])
  106650. };
  106651. };
  106652. GLTFFileLoader._compareVersion = function (a, b) {
  106653. if (a.major > b.major)
  106654. return 1;
  106655. if (a.major < b.major)
  106656. return -1;
  106657. if (a.minor > b.minor)
  106658. return 1;
  106659. if (a.minor < b.minor)
  106660. return -1;
  106661. return 0;
  106662. };
  106663. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106664. var result = "";
  106665. var length = buffer.byteLength;
  106666. for (var i = 0; i < length; i++) {
  106667. result += String.fromCharCode(buffer[i]);
  106668. }
  106669. return result;
  106670. };
  106671. /** @hidden */
  106672. GLTFFileLoader.prototype._logOpen = function (message) {
  106673. this._log(message);
  106674. this._logIndentLevel++;
  106675. };
  106676. /** @hidden */
  106677. GLTFFileLoader.prototype._logClose = function () {
  106678. --this._logIndentLevel;
  106679. };
  106680. GLTFFileLoader.prototype._logEnabled = function (message) {
  106681. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  106682. BABYLON.Tools.Log("" + spaces + message);
  106683. };
  106684. GLTFFileLoader.prototype._logDisabled = function (message) {
  106685. };
  106686. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  106687. BABYLON.Tools.StartPerformanceCounter(counterName);
  106688. };
  106689. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  106690. };
  106691. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  106692. BABYLON.Tools.EndPerformanceCounter(counterName);
  106693. };
  106694. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  106695. };
  106696. // #endregion
  106697. // #region V1 options
  106698. /**
  106699. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  106700. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  106701. * Defaults to true.
  106702. * @hidden
  106703. */
  106704. GLTFFileLoader.IncrementalLoading = true;
  106705. /**
  106706. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  106707. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  106708. * @hidden
  106709. */
  106710. GLTFFileLoader.HomogeneousCoordinates = false;
  106711. GLTFFileLoader._logSpaces = " ";
  106712. return GLTFFileLoader;
  106713. }());
  106714. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106715. var BinaryReader = /** @class */ (function () {
  106716. function BinaryReader(arrayBuffer) {
  106717. this._arrayBuffer = arrayBuffer;
  106718. this._dataView = new DataView(arrayBuffer);
  106719. this._byteOffset = 0;
  106720. }
  106721. BinaryReader.prototype.getPosition = function () {
  106722. return this._byteOffset;
  106723. };
  106724. BinaryReader.prototype.getLength = function () {
  106725. return this._arrayBuffer.byteLength;
  106726. };
  106727. BinaryReader.prototype.readUint32 = function () {
  106728. var value = this._dataView.getUint32(this._byteOffset, true);
  106729. this._byteOffset += 4;
  106730. return value;
  106731. };
  106732. BinaryReader.prototype.readUint8Array = function (length) {
  106733. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106734. this._byteOffset += length;
  106735. return value;
  106736. };
  106737. BinaryReader.prototype.skipBytes = function (length) {
  106738. this._byteOffset += length;
  106739. };
  106740. return BinaryReader;
  106741. }());
  106742. if (BABYLON.SceneLoader) {
  106743. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106744. }
  106745. })(BABYLON || (BABYLON = {}));
  106746. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106747. var BABYLON;
  106748. (function (BABYLON) {
  106749. var GLTF1;
  106750. (function (GLTF1) {
  106751. /**
  106752. * Enums
  106753. */
  106754. var EComponentType;
  106755. (function (EComponentType) {
  106756. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106757. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106758. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106759. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106760. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106761. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106762. var EShaderType;
  106763. (function (EShaderType) {
  106764. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106765. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106766. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106767. var EParameterType;
  106768. (function (EParameterType) {
  106769. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106770. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106771. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106772. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106773. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106774. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106775. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106776. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106777. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106778. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106779. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106780. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106781. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106782. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106783. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106784. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106785. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106786. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106787. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106788. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106789. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106790. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106791. var ETextureWrapMode;
  106792. (function (ETextureWrapMode) {
  106793. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106794. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106795. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106796. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106797. var ETextureFilterType;
  106798. (function (ETextureFilterType) {
  106799. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106800. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106801. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106802. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106803. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106804. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106805. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106806. var ETextureFormat;
  106807. (function (ETextureFormat) {
  106808. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106809. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106810. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106811. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106812. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106813. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106814. var ECullingType;
  106815. (function (ECullingType) {
  106816. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106817. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106818. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106819. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106820. var EBlendingFunction;
  106821. (function (EBlendingFunction) {
  106822. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106823. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106824. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106825. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106826. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106827. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106828. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106829. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106830. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106831. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106832. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106833. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106834. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106835. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106836. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106837. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106838. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106839. })(BABYLON || (BABYLON = {}));
  106840. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106841. var BABYLON;
  106842. (function (BABYLON) {
  106843. var GLTF1;
  106844. (function (GLTF1) {
  106845. /**
  106846. * Tokenizer. Used for shaders compatibility
  106847. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106848. */
  106849. var ETokenType;
  106850. (function (ETokenType) {
  106851. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106852. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106853. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106854. })(ETokenType || (ETokenType = {}));
  106855. var Tokenizer = /** @class */ (function () {
  106856. function Tokenizer(toParse) {
  106857. this._pos = 0;
  106858. this.currentToken = ETokenType.UNKNOWN;
  106859. this.currentIdentifier = "";
  106860. this.currentString = "";
  106861. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106862. this._toParse = toParse;
  106863. this._maxPos = toParse.length;
  106864. }
  106865. Tokenizer.prototype.getNextToken = function () {
  106866. if (this.isEnd())
  106867. return ETokenType.END_OF_INPUT;
  106868. this.currentString = this.read();
  106869. this.currentToken = ETokenType.UNKNOWN;
  106870. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106871. this.currentToken = ETokenType.IDENTIFIER;
  106872. this.currentIdentifier = this.currentString;
  106873. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106874. this.currentIdentifier += this.currentString;
  106875. this.forward();
  106876. }
  106877. }
  106878. return this.currentToken;
  106879. };
  106880. Tokenizer.prototype.peek = function () {
  106881. return this._toParse[this._pos];
  106882. };
  106883. Tokenizer.prototype.read = function () {
  106884. return this._toParse[this._pos++];
  106885. };
  106886. Tokenizer.prototype.forward = function () {
  106887. this._pos++;
  106888. };
  106889. Tokenizer.prototype.isEnd = function () {
  106890. return this._pos >= this._maxPos;
  106891. };
  106892. return Tokenizer;
  106893. }());
  106894. /**
  106895. * Values
  106896. */
  106897. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106898. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106899. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106900. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106901. /**
  106902. * Parse
  106903. */
  106904. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106905. for (var buf in parsedBuffers) {
  106906. var parsedBuffer = parsedBuffers[buf];
  106907. gltfRuntime.buffers[buf] = parsedBuffer;
  106908. gltfRuntime.buffersCount++;
  106909. }
  106910. };
  106911. var parseShaders = function (parsedShaders, gltfRuntime) {
  106912. for (var sha in parsedShaders) {
  106913. var parsedShader = parsedShaders[sha];
  106914. gltfRuntime.shaders[sha] = parsedShader;
  106915. gltfRuntime.shaderscount++;
  106916. }
  106917. };
  106918. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106919. for (var object in parsedObjects) {
  106920. var parsedObject = parsedObjects[object];
  106921. gltfRuntime[runtimeProperty][object] = parsedObject;
  106922. }
  106923. };
  106924. /**
  106925. * Utils
  106926. */
  106927. var normalizeUVs = function (buffer) {
  106928. if (!buffer) {
  106929. return;
  106930. }
  106931. for (var i = 0; i < buffer.length / 2; i++) {
  106932. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106933. }
  106934. };
  106935. var getAttribute = function (attributeParameter) {
  106936. if (attributeParameter.semantic === "NORMAL") {
  106937. return "normal";
  106938. }
  106939. else if (attributeParameter.semantic === "POSITION") {
  106940. return "position";
  106941. }
  106942. else if (attributeParameter.semantic === "JOINT") {
  106943. return "matricesIndices";
  106944. }
  106945. else if (attributeParameter.semantic === "WEIGHT") {
  106946. return "matricesWeights";
  106947. }
  106948. else if (attributeParameter.semantic === "COLOR") {
  106949. return "color";
  106950. }
  106951. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106952. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106953. return "uv" + (channel === 0 ? "" : channel + 1);
  106954. }
  106955. return null;
  106956. };
  106957. /**
  106958. * Loads and creates animations
  106959. */
  106960. var loadAnimations = function (gltfRuntime) {
  106961. for (var anim in gltfRuntime.animations) {
  106962. var animation = gltfRuntime.animations[anim];
  106963. if (!animation.channels || !animation.samplers) {
  106964. continue;
  106965. }
  106966. var lastAnimation = null;
  106967. for (var i = 0; i < animation.channels.length; i++) {
  106968. // Get parameters and load buffers
  106969. var channel = animation.channels[i];
  106970. var sampler = animation.samplers[channel.sampler];
  106971. if (!sampler) {
  106972. continue;
  106973. }
  106974. var inputData = null;
  106975. var outputData = null;
  106976. if (animation.parameters) {
  106977. inputData = animation.parameters[sampler.input];
  106978. outputData = animation.parameters[sampler.output];
  106979. }
  106980. else {
  106981. inputData = sampler.input;
  106982. outputData = sampler.output;
  106983. }
  106984. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106985. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106986. var targetID = channel.target.id;
  106987. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106988. if (targetNode === null) {
  106989. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106990. }
  106991. if (targetNode === null) {
  106992. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106993. continue;
  106994. }
  106995. var isBone = targetNode instanceof BABYLON.Bone;
  106996. // Get target path (position, rotation or scaling)
  106997. var targetPath = channel.target.path;
  106998. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106999. if (targetPathIndex !== -1) {
  107000. targetPath = babylonAnimationPaths[targetPathIndex];
  107001. }
  107002. // Determine animation type
  107003. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107004. if (!isBone) {
  107005. if (targetPath === "rotationQuaternion") {
  107006. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107007. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107008. }
  107009. else {
  107010. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107011. }
  107012. }
  107013. // Create animation and key frames
  107014. var babylonAnimation = null;
  107015. var keys = [];
  107016. var arrayOffset = 0;
  107017. var modifyKey = false;
  107018. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107019. babylonAnimation = lastAnimation;
  107020. modifyKey = true;
  107021. }
  107022. if (!modifyKey) {
  107023. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107024. }
  107025. // For each frame
  107026. for (var j = 0; j < bufferInput.length; j++) {
  107027. var value = null;
  107028. if (targetPath === "rotationQuaternion") { // VEC4
  107029. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107030. arrayOffset += 4;
  107031. }
  107032. else { // Position and scaling are VEC3
  107033. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107034. arrayOffset += 3;
  107035. }
  107036. if (isBone) {
  107037. var bone = targetNode;
  107038. var translation = BABYLON.Vector3.Zero();
  107039. var rotationQuaternion = new BABYLON.Quaternion();
  107040. var scaling = BABYLON.Vector3.Zero();
  107041. // Warning on decompose
  107042. var mat = bone.getBaseMatrix();
  107043. if (modifyKey && lastAnimation) {
  107044. mat = lastAnimation.getKeys()[j].value;
  107045. }
  107046. mat.decompose(scaling, rotationQuaternion, translation);
  107047. if (targetPath === "position") {
  107048. translation = value;
  107049. }
  107050. else if (targetPath === "rotationQuaternion") {
  107051. rotationQuaternion = value;
  107052. }
  107053. else {
  107054. scaling = value;
  107055. }
  107056. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  107057. }
  107058. if (!modifyKey) {
  107059. keys.push({
  107060. frame: bufferInput[j],
  107061. value: value
  107062. });
  107063. }
  107064. else if (lastAnimation) {
  107065. lastAnimation.getKeys()[j].value = value;
  107066. }
  107067. }
  107068. // Finish
  107069. if (!modifyKey && babylonAnimation) {
  107070. babylonAnimation.setKeys(keys);
  107071. targetNode.animations.push(babylonAnimation);
  107072. }
  107073. lastAnimation = babylonAnimation;
  107074. gltfRuntime.scene.stopAnimation(targetNode);
  107075. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  107076. }
  107077. }
  107078. };
  107079. /**
  107080. * Returns the bones transformation matrix
  107081. */
  107082. var configureBoneTransformation = function (node) {
  107083. var mat = null;
  107084. if (node.translation || node.rotation || node.scale) {
  107085. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  107086. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  107087. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  107088. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  107089. }
  107090. else {
  107091. mat = BABYLON.Matrix.FromArray(node.matrix);
  107092. }
  107093. return mat;
  107094. };
  107095. /**
  107096. * Returns the parent bone
  107097. */
  107098. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  107099. // Try to find
  107100. for (var i = 0; i < newSkeleton.bones.length; i++) {
  107101. if (newSkeleton.bones[i].name === jointName) {
  107102. return newSkeleton.bones[i];
  107103. }
  107104. }
  107105. // Not found, search in gltf nodes
  107106. var nodes = gltfRuntime.nodes;
  107107. for (var nde in nodes) {
  107108. var node = nodes[nde];
  107109. if (!node.jointName) {
  107110. continue;
  107111. }
  107112. var children = node.children;
  107113. for (var i = 0; i < children.length; i++) {
  107114. var child = gltfRuntime.nodes[children[i]];
  107115. if (!child.jointName) {
  107116. continue;
  107117. }
  107118. if (child.jointName === jointName) {
  107119. var mat = configureBoneTransformation(node);
  107120. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  107121. bone.id = nde;
  107122. return bone;
  107123. }
  107124. }
  107125. }
  107126. return null;
  107127. };
  107128. /**
  107129. * Returns the appropriate root node
  107130. */
  107131. var getNodeToRoot = function (nodesToRoot, id) {
  107132. for (var i = 0; i < nodesToRoot.length; i++) {
  107133. var nodeToRoot = nodesToRoot[i];
  107134. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  107135. var child = nodeToRoot.node.children[j];
  107136. if (child === id) {
  107137. return nodeToRoot.bone;
  107138. }
  107139. }
  107140. }
  107141. return null;
  107142. };
  107143. /**
  107144. * Returns the node with the joint name
  107145. */
  107146. var getJointNode = function (gltfRuntime, jointName) {
  107147. var nodes = gltfRuntime.nodes;
  107148. var node = nodes[jointName];
  107149. if (node) {
  107150. return {
  107151. node: node,
  107152. id: jointName
  107153. };
  107154. }
  107155. for (var nde in nodes) {
  107156. node = nodes[nde];
  107157. if (node.jointName === jointName) {
  107158. return {
  107159. node: node,
  107160. id: nde
  107161. };
  107162. }
  107163. }
  107164. return null;
  107165. };
  107166. /**
  107167. * Checks if a nodes is in joints
  107168. */
  107169. var nodeIsInJoints = function (skins, id) {
  107170. for (var i = 0; i < skins.jointNames.length; i++) {
  107171. if (skins.jointNames[i] === id) {
  107172. return true;
  107173. }
  107174. }
  107175. return false;
  107176. };
  107177. /**
  107178. * Fills the nodes to root for bones and builds hierarchy
  107179. */
  107180. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  107181. // Creates nodes for root
  107182. for (var nde in gltfRuntime.nodes) {
  107183. var node = gltfRuntime.nodes[nde];
  107184. var id = nde;
  107185. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  107186. continue;
  107187. }
  107188. // Create node to root bone
  107189. var mat = configureBoneTransformation(node);
  107190. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  107191. bone.id = id;
  107192. nodesToRoot.push({ bone: bone, node: node, id: id });
  107193. }
  107194. // Parenting
  107195. for (var i = 0; i < nodesToRoot.length; i++) {
  107196. var nodeToRoot = nodesToRoot[i];
  107197. var children = nodeToRoot.node.children;
  107198. for (var j = 0; j < children.length; j++) {
  107199. var child = null;
  107200. for (var k = 0; k < nodesToRoot.length; k++) {
  107201. if (nodesToRoot[k].id === children[j]) {
  107202. child = nodesToRoot[k];
  107203. break;
  107204. }
  107205. }
  107206. if (child) {
  107207. child.bone._parent = nodeToRoot.bone;
  107208. nodeToRoot.bone.children.push(child.bone);
  107209. }
  107210. }
  107211. }
  107212. };
  107213. /**
  107214. * Imports a skeleton
  107215. */
  107216. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  107217. if (!newSkeleton) {
  107218. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  107219. }
  107220. if (!skins.babylonSkeleton) {
  107221. return newSkeleton;
  107222. }
  107223. // Find the root bones
  107224. var nodesToRoot = [];
  107225. var nodesToRootToAdd = [];
  107226. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  107227. newSkeleton.bones = [];
  107228. // Joints
  107229. for (var i = 0; i < skins.jointNames.length; i++) {
  107230. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107231. if (!jointNode) {
  107232. continue;
  107233. }
  107234. var node = jointNode.node;
  107235. if (!node) {
  107236. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  107237. continue;
  107238. }
  107239. var id = jointNode.id;
  107240. // Optimize, if the bone already exists...
  107241. var existingBone = gltfRuntime.scene.getBoneByID(id);
  107242. if (existingBone) {
  107243. newSkeleton.bones.push(existingBone);
  107244. continue;
  107245. }
  107246. // Search for parent bone
  107247. var foundBone = false;
  107248. var parentBone = null;
  107249. for (var j = 0; j < i; j++) {
  107250. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  107251. if (!jointNode_1) {
  107252. continue;
  107253. }
  107254. var joint = jointNode_1.node;
  107255. if (!joint) {
  107256. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  107257. continue;
  107258. }
  107259. var children = joint.children;
  107260. if (!children) {
  107261. continue;
  107262. }
  107263. foundBone = false;
  107264. for (var k = 0; k < children.length; k++) {
  107265. if (children[k] === id) {
  107266. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  107267. foundBone = true;
  107268. break;
  107269. }
  107270. }
  107271. if (foundBone) {
  107272. break;
  107273. }
  107274. }
  107275. // Create bone
  107276. var mat = configureBoneTransformation(node);
  107277. if (!parentBone && nodesToRoot.length > 0) {
  107278. parentBone = getNodeToRoot(nodesToRoot, id);
  107279. if (parentBone) {
  107280. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  107281. nodesToRootToAdd.push(parentBone);
  107282. }
  107283. }
  107284. }
  107285. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  107286. bone.id = id;
  107287. }
  107288. // Polish
  107289. var bones = newSkeleton.bones;
  107290. newSkeleton.bones = [];
  107291. for (var i = 0; i < skins.jointNames.length; i++) {
  107292. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107293. if (!jointNode) {
  107294. continue;
  107295. }
  107296. for (var j = 0; j < bones.length; j++) {
  107297. if (bones[j].id === jointNode.id) {
  107298. newSkeleton.bones.push(bones[j]);
  107299. break;
  107300. }
  107301. }
  107302. }
  107303. newSkeleton.prepare();
  107304. // Finish
  107305. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107306. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107307. }
  107308. return newSkeleton;
  107309. };
  107310. /**
  107311. * Imports a mesh and its geometries
  107312. */
  107313. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107314. if (!newMesh) {
  107315. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107316. newMesh.id = id;
  107317. }
  107318. if (!node.babylonNode) {
  107319. return newMesh;
  107320. }
  107321. var subMaterials = [];
  107322. var vertexData = null;
  107323. var verticesStarts = new Array();
  107324. var verticesCounts = new Array();
  107325. var indexStarts = new Array();
  107326. var indexCounts = new Array();
  107327. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107328. var meshID = meshes[meshIndex];
  107329. var mesh = gltfRuntime.meshes[meshID];
  107330. if (!mesh) {
  107331. continue;
  107332. }
  107333. // Positions, normals and UVs
  107334. for (var i = 0; i < mesh.primitives.length; i++) {
  107335. // Temporary vertex data
  107336. var tempVertexData = new BABYLON.VertexData();
  107337. var primitive = mesh.primitives[i];
  107338. if (primitive.mode !== 4) {
  107339. // continue;
  107340. }
  107341. var attributes = primitive.attributes;
  107342. var accessor = null;
  107343. var buffer = null;
  107344. // Set positions, normal and uvs
  107345. for (var semantic in attributes) {
  107346. // Link accessor and buffer view
  107347. accessor = gltfRuntime.accessors[attributes[semantic]];
  107348. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107349. if (semantic === "NORMAL") {
  107350. tempVertexData.normals = new Float32Array(buffer.length);
  107351. tempVertexData.normals.set(buffer);
  107352. }
  107353. else if (semantic === "POSITION") {
  107354. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107355. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107356. for (var j = 0; j < buffer.length; j += 4) {
  107357. tempVertexData.positions[j] = buffer[j];
  107358. tempVertexData.positions[j + 1] = buffer[j + 1];
  107359. tempVertexData.positions[j + 2] = buffer[j + 2];
  107360. }
  107361. }
  107362. else {
  107363. tempVertexData.positions = new Float32Array(buffer.length);
  107364. tempVertexData.positions.set(buffer);
  107365. }
  107366. verticesCounts.push(tempVertexData.positions.length);
  107367. }
  107368. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107369. var channel = Number(semantic.split("_")[1]);
  107370. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107371. var uvs = new Float32Array(buffer.length);
  107372. uvs.set(buffer);
  107373. normalizeUVs(uvs);
  107374. tempVertexData.set(uvs, uvKind);
  107375. }
  107376. else if (semantic === "JOINT") {
  107377. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107378. tempVertexData.matricesIndices.set(buffer);
  107379. }
  107380. else if (semantic === "WEIGHT") {
  107381. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107382. tempVertexData.matricesWeights.set(buffer);
  107383. }
  107384. else if (semantic === "COLOR") {
  107385. tempVertexData.colors = new Float32Array(buffer.length);
  107386. tempVertexData.colors.set(buffer);
  107387. }
  107388. }
  107389. // Indices
  107390. accessor = gltfRuntime.accessors[primitive.indices];
  107391. if (accessor) {
  107392. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107393. tempVertexData.indices = new Int32Array(buffer.length);
  107394. tempVertexData.indices.set(buffer);
  107395. indexCounts.push(tempVertexData.indices.length);
  107396. }
  107397. else {
  107398. // Set indices on the fly
  107399. var indices = [];
  107400. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107401. indices.push(j);
  107402. }
  107403. tempVertexData.indices = new Int32Array(indices);
  107404. indexCounts.push(tempVertexData.indices.length);
  107405. }
  107406. if (!vertexData) {
  107407. vertexData = tempVertexData;
  107408. }
  107409. else {
  107410. vertexData.merge(tempVertexData);
  107411. }
  107412. // Sub material
  107413. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107414. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107415. // Update vertices start and index start
  107416. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107417. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107418. }
  107419. }
  107420. var material;
  107421. if (subMaterials.length > 1) {
  107422. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107423. material.subMaterials = subMaterials;
  107424. }
  107425. else {
  107426. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107427. }
  107428. if (subMaterials.length === 1) {
  107429. material = subMaterials[0];
  107430. }
  107431. if (!newMesh.material) {
  107432. newMesh.material = material;
  107433. }
  107434. // Apply geometry
  107435. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107436. newMesh.computeWorldMatrix(true);
  107437. // Apply submeshes
  107438. newMesh.subMeshes = [];
  107439. var index = 0;
  107440. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107441. var meshID = meshes[meshIndex];
  107442. var mesh = gltfRuntime.meshes[meshID];
  107443. if (!mesh) {
  107444. continue;
  107445. }
  107446. for (var i = 0; i < mesh.primitives.length; i++) {
  107447. if (mesh.primitives[i].mode !== 4) {
  107448. //continue;
  107449. }
  107450. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107451. index++;
  107452. }
  107453. }
  107454. // Finish
  107455. return newMesh;
  107456. };
  107457. /**
  107458. * Configure node transformation from position, rotation and scaling
  107459. */
  107460. var configureNode = function (newNode, position, rotation, scaling) {
  107461. if (newNode.position) {
  107462. newNode.position = position;
  107463. }
  107464. if (newNode.rotationQuaternion || newNode.rotation) {
  107465. newNode.rotationQuaternion = rotation;
  107466. }
  107467. if (newNode.scaling) {
  107468. newNode.scaling = scaling;
  107469. }
  107470. };
  107471. /**
  107472. * Configures node from transformation matrix
  107473. */
  107474. var configureNodeFromMatrix = function (newNode, node, parent) {
  107475. if (node.matrix) {
  107476. var position = new BABYLON.Vector3(0, 0, 0);
  107477. var rotation = new BABYLON.Quaternion();
  107478. var scaling = new BABYLON.Vector3(0, 0, 0);
  107479. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107480. mat.decompose(scaling, rotation, position);
  107481. configureNode(newNode, position, rotation, scaling);
  107482. }
  107483. else if (node.translation && node.rotation && node.scale) {
  107484. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107485. }
  107486. newNode.computeWorldMatrix(true);
  107487. };
  107488. /**
  107489. * Imports a node
  107490. */
  107491. var importNode = function (gltfRuntime, node, id, parent) {
  107492. var lastNode = null;
  107493. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107494. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107495. return null;
  107496. }
  107497. }
  107498. // Meshes
  107499. if (node.skin) {
  107500. if (node.meshes) {
  107501. var skin = gltfRuntime.skins[node.skin];
  107502. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107503. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107504. if (newMesh.skeleton === null) {
  107505. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107506. if (!skin.babylonSkeleton) {
  107507. skin.babylonSkeleton = newMesh.skeleton;
  107508. }
  107509. }
  107510. lastNode = newMesh;
  107511. }
  107512. }
  107513. else if (node.meshes) {
  107514. /**
  107515. * Improve meshes property
  107516. */
  107517. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107518. lastNode = newMesh;
  107519. }
  107520. // Lights
  107521. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107522. var light = gltfRuntime.lights[node.light];
  107523. if (light) {
  107524. if (light.type === "ambient") {
  107525. var ambienLight = light[light.type];
  107526. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107527. hemiLight.name = node.name || "";
  107528. if (ambienLight.color) {
  107529. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107530. }
  107531. lastNode = hemiLight;
  107532. }
  107533. else if (light.type === "directional") {
  107534. var directionalLight = light[light.type];
  107535. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107536. dirLight.name = node.name || "";
  107537. if (directionalLight.color) {
  107538. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107539. }
  107540. lastNode = dirLight;
  107541. }
  107542. else if (light.type === "point") {
  107543. var pointLight = light[light.type];
  107544. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107545. ptLight.name = node.name || "";
  107546. if (pointLight.color) {
  107547. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107548. }
  107549. lastNode = ptLight;
  107550. }
  107551. else if (light.type === "spot") {
  107552. var spotLight = light[light.type];
  107553. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107554. spLight.name = node.name || "";
  107555. if (spotLight.color) {
  107556. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107557. }
  107558. if (spotLight.fallOfAngle) {
  107559. spLight.angle = spotLight.fallOfAngle;
  107560. }
  107561. if (spotLight.fallOffExponent) {
  107562. spLight.exponent = spotLight.fallOffExponent;
  107563. }
  107564. lastNode = spLight;
  107565. }
  107566. }
  107567. }
  107568. // Cameras
  107569. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107570. var camera = gltfRuntime.cameras[node.camera];
  107571. if (camera) {
  107572. if (camera.type === "orthographic") {
  107573. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107574. orthoCamera.name = node.name || "";
  107575. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107576. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107577. lastNode = orthoCamera;
  107578. }
  107579. else if (camera.type === "perspective") {
  107580. var perspectiveCamera = camera[camera.type];
  107581. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107582. persCamera.name = node.name || "";
  107583. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107584. if (!perspectiveCamera.aspectRatio) {
  107585. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107586. }
  107587. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107588. persCamera.maxZ = perspectiveCamera.zfar;
  107589. persCamera.minZ = perspectiveCamera.znear;
  107590. }
  107591. lastNode = persCamera;
  107592. }
  107593. }
  107594. }
  107595. // Empty node
  107596. if (!node.jointName) {
  107597. if (node.babylonNode) {
  107598. return node.babylonNode;
  107599. }
  107600. else if (lastNode === null) {
  107601. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107602. node.babylonNode = dummy;
  107603. lastNode = dummy;
  107604. }
  107605. }
  107606. if (lastNode !== null) {
  107607. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107608. configureNodeFromMatrix(lastNode, node, parent);
  107609. }
  107610. else {
  107611. var translation = node.translation || [0, 0, 0];
  107612. var rotation = node.rotation || [0, 0, 0, 1];
  107613. var scale = node.scale || [1, 1, 1];
  107614. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107615. }
  107616. lastNode.updateCache(true);
  107617. node.babylonNode = lastNode;
  107618. }
  107619. return lastNode;
  107620. };
  107621. /**
  107622. * Traverses nodes and creates them
  107623. */
  107624. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107625. if (meshIncluded === void 0) { meshIncluded = false; }
  107626. var node = gltfRuntime.nodes[id];
  107627. var newNode = null;
  107628. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107629. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107630. meshIncluded = true;
  107631. }
  107632. else {
  107633. meshIncluded = false;
  107634. }
  107635. }
  107636. else {
  107637. meshIncluded = true;
  107638. }
  107639. if (!node.jointName && meshIncluded) {
  107640. newNode = importNode(gltfRuntime, node, id, parent);
  107641. if (newNode !== null) {
  107642. newNode.id = id;
  107643. newNode.parent = parent;
  107644. }
  107645. }
  107646. if (node.children) {
  107647. for (var i = 0; i < node.children.length; i++) {
  107648. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107649. }
  107650. }
  107651. };
  107652. /**
  107653. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107654. */
  107655. var postLoad = function (gltfRuntime) {
  107656. // Nodes
  107657. var currentScene = gltfRuntime.currentScene;
  107658. if (currentScene) {
  107659. for (var i = 0; i < currentScene.nodes.length; i++) {
  107660. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107661. }
  107662. }
  107663. else {
  107664. for (var thing in gltfRuntime.scenes) {
  107665. currentScene = gltfRuntime.scenes[thing];
  107666. for (var i = 0; i < currentScene.nodes.length; i++) {
  107667. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107668. }
  107669. }
  107670. }
  107671. // Set animations
  107672. loadAnimations(gltfRuntime);
  107673. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107674. var skeleton = gltfRuntime.scene.skeletons[i];
  107675. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107676. }
  107677. };
  107678. /**
  107679. * onBind shaderrs callback to set uniforms and matrices
  107680. */
  107681. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107682. var materialValues = material.values || technique.parameters;
  107683. for (var unif in unTreatedUniforms) {
  107684. var uniform = unTreatedUniforms[unif];
  107685. var type = uniform.type;
  107686. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107687. if (uniform.semantic && !uniform.source && !uniform.node) {
  107688. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107689. }
  107690. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107691. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107692. if (source === null) {
  107693. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107694. }
  107695. if (source === null) {
  107696. continue;
  107697. }
  107698. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107699. }
  107700. }
  107701. else {
  107702. var value = materialValues[technique.uniforms[unif]];
  107703. if (!value) {
  107704. continue;
  107705. }
  107706. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107707. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107708. if (texture === null || texture === undefined) {
  107709. continue;
  107710. }
  107711. shaderMaterial.getEffect().setTexture(unif, texture);
  107712. }
  107713. else {
  107714. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107715. }
  107716. }
  107717. }
  107718. onSuccess(shaderMaterial);
  107719. };
  107720. /**
  107721. * Prepare uniforms to send the only one time
  107722. * Loads the appropriate textures
  107723. */
  107724. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107725. var materialValues = material.values || technique.parameters;
  107726. var techniqueUniforms = technique.uniforms;
  107727. /**
  107728. * Prepare values here (not matrices)
  107729. */
  107730. for (var unif in unTreatedUniforms) {
  107731. var uniform = unTreatedUniforms[unif];
  107732. var type = uniform.type;
  107733. var value = materialValues[techniqueUniforms[unif]];
  107734. if (value === undefined) {
  107735. // In case the value is the same for all materials
  107736. value = uniform.value;
  107737. }
  107738. if (!value) {
  107739. continue;
  107740. }
  107741. var onLoadTexture = function (uniformName) {
  107742. return function (texture) {
  107743. if (uniform.value && uniformName) {
  107744. // Static uniform
  107745. shaderMaterial.setTexture(uniformName, texture);
  107746. delete unTreatedUniforms[uniformName];
  107747. }
  107748. };
  107749. };
  107750. // Texture (sampler2D)
  107751. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107752. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107753. }
  107754. // Others
  107755. else {
  107756. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107757. // Static uniform
  107758. delete unTreatedUniforms[unif];
  107759. }
  107760. }
  107761. }
  107762. };
  107763. /**
  107764. * Shader compilation failed
  107765. */
  107766. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107767. return function (effect, error) {
  107768. shaderMaterial.dispose(true);
  107769. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107770. };
  107771. };
  107772. /**
  107773. * Shader compilation success
  107774. */
  107775. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107776. return function (_) {
  107777. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107778. shaderMaterial.onBind = function (mesh) {
  107779. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107780. };
  107781. };
  107782. };
  107783. /**
  107784. * Returns the appropriate uniform if already handled by babylon
  107785. */
  107786. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107787. for (var unif in technique.uniforms) {
  107788. var uniform = technique.uniforms[unif];
  107789. var uniformParameter = technique.parameters[uniform];
  107790. if (tokenizer.currentIdentifier === unif) {
  107791. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107792. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107793. if (transformIndex !== -1) {
  107794. delete unTreatedUniforms[unif];
  107795. return babylonTransforms[transformIndex];
  107796. }
  107797. }
  107798. }
  107799. }
  107800. return tokenizer.currentIdentifier;
  107801. };
  107802. /**
  107803. * All shaders loaded. Create materials one by one
  107804. */
  107805. var importMaterials = function (gltfRuntime) {
  107806. // Create materials
  107807. for (var mat in gltfRuntime.materials) {
  107808. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107809. }
  107810. };
  107811. /**
  107812. * Implementation of the base glTF spec
  107813. */
  107814. var GLTFLoaderBase = /** @class */ (function () {
  107815. function GLTFLoaderBase() {
  107816. }
  107817. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107818. var gltfRuntime = {
  107819. extensions: {},
  107820. accessors: {},
  107821. buffers: {},
  107822. bufferViews: {},
  107823. meshes: {},
  107824. lights: {},
  107825. cameras: {},
  107826. nodes: {},
  107827. images: {},
  107828. textures: {},
  107829. shaders: {},
  107830. programs: {},
  107831. samplers: {},
  107832. techniques: {},
  107833. materials: {},
  107834. animations: {},
  107835. skins: {},
  107836. extensionsUsed: [],
  107837. scenes: {},
  107838. buffersCount: 0,
  107839. shaderscount: 0,
  107840. scene: scene,
  107841. rootUrl: rootUrl,
  107842. loadedBufferCount: 0,
  107843. loadedBufferViews: {},
  107844. loadedShaderCount: 0,
  107845. importOnlyMeshes: false,
  107846. dummyNodes: []
  107847. };
  107848. // Parse
  107849. if (parsedData.extensions) {
  107850. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107851. }
  107852. if (parsedData.extensionsUsed) {
  107853. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107854. }
  107855. if (parsedData.buffers) {
  107856. parseBuffers(parsedData.buffers, gltfRuntime);
  107857. }
  107858. if (parsedData.bufferViews) {
  107859. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107860. }
  107861. if (parsedData.accessors) {
  107862. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107863. }
  107864. if (parsedData.meshes) {
  107865. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107866. }
  107867. if (parsedData.lights) {
  107868. parseObject(parsedData.lights, "lights", gltfRuntime);
  107869. }
  107870. if (parsedData.cameras) {
  107871. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107872. }
  107873. if (parsedData.nodes) {
  107874. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107875. }
  107876. if (parsedData.images) {
  107877. parseObject(parsedData.images, "images", gltfRuntime);
  107878. }
  107879. if (parsedData.textures) {
  107880. parseObject(parsedData.textures, "textures", gltfRuntime);
  107881. }
  107882. if (parsedData.shaders) {
  107883. parseShaders(parsedData.shaders, gltfRuntime);
  107884. }
  107885. if (parsedData.programs) {
  107886. parseObject(parsedData.programs, "programs", gltfRuntime);
  107887. }
  107888. if (parsedData.samplers) {
  107889. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107890. }
  107891. if (parsedData.techniques) {
  107892. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107893. }
  107894. if (parsedData.materials) {
  107895. parseObject(parsedData.materials, "materials", gltfRuntime);
  107896. }
  107897. if (parsedData.animations) {
  107898. parseObject(parsedData.animations, "animations", gltfRuntime);
  107899. }
  107900. if (parsedData.skins) {
  107901. parseObject(parsedData.skins, "skins", gltfRuntime);
  107902. }
  107903. if (parsedData.scenes) {
  107904. gltfRuntime.scenes = parsedData.scenes;
  107905. }
  107906. if (parsedData.scene && parsedData.scenes) {
  107907. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107908. }
  107909. return gltfRuntime;
  107910. };
  107911. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107912. var buffer = gltfRuntime.buffers[id];
  107913. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107914. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107915. }
  107916. else {
  107917. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107918. if (request) {
  107919. onError(request.status + " " + request.statusText);
  107920. }
  107921. });
  107922. }
  107923. };
  107924. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107925. var texture = gltfRuntime.textures[id];
  107926. if (!texture || !texture.source) {
  107927. onError("");
  107928. return;
  107929. }
  107930. if (texture.babylonTexture) {
  107931. onSuccess(null);
  107932. return;
  107933. }
  107934. var source = gltfRuntime.images[texture.source];
  107935. if (BABYLON.Tools.IsBase64(source.uri)) {
  107936. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107937. }
  107938. else {
  107939. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107940. if (request) {
  107941. onError(request.status + " " + request.statusText);
  107942. }
  107943. });
  107944. }
  107945. };
  107946. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107947. var texture = gltfRuntime.textures[id];
  107948. if (texture.babylonTexture) {
  107949. onSuccess(texture.babylonTexture);
  107950. return;
  107951. }
  107952. var sampler = gltfRuntime.samplers[texture.sampler];
  107953. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107954. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107955. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107956. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107957. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107958. var blob = new Blob([buffer]);
  107959. var blobURL = URL.createObjectURL(blob);
  107960. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107961. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107962. if (sampler.wrapS !== undefined) {
  107963. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107964. }
  107965. if (sampler.wrapT !== undefined) {
  107966. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107967. }
  107968. newTexture.name = id;
  107969. texture.babylonTexture = newTexture;
  107970. onSuccess(newTexture);
  107971. };
  107972. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107973. var shader = gltfRuntime.shaders[id];
  107974. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107975. var shaderString = atob(shader.uri.split(",")[1]);
  107976. if (onSuccess) {
  107977. onSuccess(shaderString);
  107978. }
  107979. }
  107980. else {
  107981. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107982. if (request && onError) {
  107983. onError(request.status + " " + request.statusText);
  107984. }
  107985. });
  107986. }
  107987. };
  107988. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107989. var material = gltfRuntime.materials[id];
  107990. if (!material.technique) {
  107991. if (onError) {
  107992. onError("No technique found.");
  107993. }
  107994. return;
  107995. }
  107996. var technique = gltfRuntime.techniques[material.technique];
  107997. if (!technique) {
  107998. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107999. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108000. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108001. onSuccess(defaultMaterial);
  108002. return;
  108003. }
  108004. var program = gltfRuntime.programs[technique.program];
  108005. var states = technique.states;
  108006. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108007. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108008. var newVertexShader = "";
  108009. var newPixelShader = "";
  108010. var vertexTokenizer = new Tokenizer(vertexShader);
  108011. var pixelTokenizer = new Tokenizer(pixelShader);
  108012. var unTreatedUniforms = {};
  108013. var uniforms = [];
  108014. var attributes = [];
  108015. var samplers = [];
  108016. // Fill uniform, sampler2D and attributes
  108017. for (var unif in technique.uniforms) {
  108018. var uniform = technique.uniforms[unif];
  108019. var uniformParameter = technique.parameters[uniform];
  108020. unTreatedUniforms[unif] = uniformParameter;
  108021. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108022. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108023. if (transformIndex !== -1) {
  108024. uniforms.push(babylonTransforms[transformIndex]);
  108025. delete unTreatedUniforms[unif];
  108026. }
  108027. else {
  108028. uniforms.push(unif);
  108029. }
  108030. }
  108031. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108032. samplers.push(unif);
  108033. }
  108034. else {
  108035. uniforms.push(unif);
  108036. }
  108037. }
  108038. for (var attr in technique.attributes) {
  108039. var attribute = technique.attributes[attr];
  108040. var attributeParameter = technique.parameters[attribute];
  108041. if (attributeParameter.semantic) {
  108042. attributes.push(getAttribute(attributeParameter));
  108043. }
  108044. }
  108045. // Configure vertex shader
  108046. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  108047. var tokenType = vertexTokenizer.currentToken;
  108048. if (tokenType !== ETokenType.IDENTIFIER) {
  108049. newVertexShader += vertexTokenizer.currentString;
  108050. continue;
  108051. }
  108052. var foundAttribute = false;
  108053. for (var attr in technique.attributes) {
  108054. var attribute = technique.attributes[attr];
  108055. var attributeParameter = technique.parameters[attribute];
  108056. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  108057. newVertexShader += getAttribute(attributeParameter);
  108058. foundAttribute = true;
  108059. break;
  108060. }
  108061. }
  108062. if (foundAttribute) {
  108063. continue;
  108064. }
  108065. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  108066. }
  108067. // Configure pixel shader
  108068. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  108069. var tokenType = pixelTokenizer.currentToken;
  108070. if (tokenType !== ETokenType.IDENTIFIER) {
  108071. newPixelShader += pixelTokenizer.currentString;
  108072. continue;
  108073. }
  108074. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  108075. }
  108076. // Create shader material
  108077. var shaderPath = {
  108078. vertex: program.vertexShader + id,
  108079. fragment: program.fragmentShader + id
  108080. };
  108081. var options = {
  108082. attributes: attributes,
  108083. uniforms: uniforms,
  108084. samplers: samplers,
  108085. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  108086. };
  108087. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  108088. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  108089. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  108090. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  108091. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  108092. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108093. if (states && states.functions) {
  108094. var functions = states.functions;
  108095. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  108096. shaderMaterial.backFaceCulling = false;
  108097. }
  108098. var blendFunc = functions.blendFuncSeparate;
  108099. if (blendFunc) {
  108100. 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) {
  108101. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  108102. }
  108103. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108104. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  108105. }
  108106. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108107. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  108108. }
  108109. 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) {
  108110. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  108111. }
  108112. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108113. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  108114. }
  108115. 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) {
  108116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  108117. }
  108118. }
  108119. }
  108120. };
  108121. return GLTFLoaderBase;
  108122. }());
  108123. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  108124. /**
  108125. * glTF V1 Loader
  108126. */
  108127. var GLTFLoader = /** @class */ (function () {
  108128. function GLTFLoader() {
  108129. this.state = null;
  108130. }
  108131. GLTFLoader.RegisterExtension = function (extension) {
  108132. if (GLTFLoader.Extensions[extension.name]) {
  108133. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  108134. return;
  108135. }
  108136. GLTFLoader.Extensions[extension.name] = extension;
  108137. };
  108138. GLTFLoader.prototype.dispose = function () {
  108139. // do nothing
  108140. };
  108141. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  108142. var _this = this;
  108143. scene.useRightHandedSystem = true;
  108144. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108145. gltfRuntime.importOnlyMeshes = true;
  108146. if (meshesNames === "") {
  108147. gltfRuntime.importMeshesNames = [];
  108148. }
  108149. else if (typeof meshesNames === "string") {
  108150. gltfRuntime.importMeshesNames = [meshesNames];
  108151. }
  108152. else if (meshesNames && !(meshesNames instanceof Array)) {
  108153. gltfRuntime.importMeshesNames = [meshesNames];
  108154. }
  108155. else {
  108156. gltfRuntime.importMeshesNames = [];
  108157. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  108158. }
  108159. // Create nodes
  108160. _this._createNodes(gltfRuntime);
  108161. var meshes = new Array();
  108162. var skeletons = new Array();
  108163. // Fill arrays of meshes and skeletons
  108164. for (var nde in gltfRuntime.nodes) {
  108165. var node = gltfRuntime.nodes[nde];
  108166. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  108167. meshes.push(node.babylonNode);
  108168. }
  108169. }
  108170. for (var skl in gltfRuntime.skins) {
  108171. var skin = gltfRuntime.skins[skl];
  108172. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  108173. skeletons.push(skin.babylonSkeleton);
  108174. }
  108175. }
  108176. // Load buffers, shaders, materials, etc.
  108177. _this._loadBuffersAsync(gltfRuntime, function () {
  108178. _this._loadShadersAsync(gltfRuntime, function () {
  108179. importMaterials(gltfRuntime);
  108180. postLoad(gltfRuntime);
  108181. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108182. onSuccess(meshes, skeletons);
  108183. }
  108184. });
  108185. }, onProgress);
  108186. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108187. onSuccess(meshes, skeletons);
  108188. }
  108189. }, onError);
  108190. return true;
  108191. };
  108192. /**
  108193. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  108194. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  108195. * @param scene the scene the meshes should be added to
  108196. * @param data gltf data containing information of the meshes in a loaded file
  108197. * @param rootUrl root url to load from
  108198. * @param onProgress event that fires when loading progress has occured
  108199. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  108200. */
  108201. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108202. var _this = this;
  108203. return new Promise(function (resolve, reject) {
  108204. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  108205. resolve({
  108206. meshes: meshes,
  108207. particleSystems: [],
  108208. skeletons: skeletons,
  108209. animationGroups: []
  108210. });
  108211. }, onProgress, function (message) {
  108212. reject(new Error(message));
  108213. });
  108214. });
  108215. };
  108216. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  108217. var _this = this;
  108218. scene.useRightHandedSystem = true;
  108219. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108220. // Load runtime extensios
  108221. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  108222. // Create nodes
  108223. _this._createNodes(gltfRuntime);
  108224. // Load buffers, shaders, materials, etc.
  108225. _this._loadBuffersAsync(gltfRuntime, function () {
  108226. _this._loadShadersAsync(gltfRuntime, function () {
  108227. importMaterials(gltfRuntime);
  108228. postLoad(gltfRuntime);
  108229. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  108230. onSuccess();
  108231. }
  108232. });
  108233. });
  108234. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  108235. onSuccess();
  108236. }
  108237. }, onError);
  108238. }, onError);
  108239. };
  108240. /**
  108241. * Imports all objects from a loaded gltf file and adds them to the scene
  108242. * @param scene the scene the objects should be added to
  108243. * @param data gltf data containing information of the meshes in a loaded file
  108244. * @param rootUrl root url to load from
  108245. * @param onProgress event that fires when loading progress has occured
  108246. * @returns a promise which completes when objects have been loaded to the scene
  108247. */
  108248. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108249. var _this = this;
  108250. return new Promise(function (resolve, reject) {
  108251. _this._loadAsync(scene, data, rootUrl, function () {
  108252. resolve();
  108253. }, onProgress, function (message) {
  108254. reject(new Error(message));
  108255. });
  108256. });
  108257. };
  108258. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  108259. var hasShaders = false;
  108260. var processShader = function (sha, shader) {
  108261. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  108262. if (shaderString instanceof ArrayBuffer) {
  108263. return;
  108264. }
  108265. gltfRuntime.loadedShaderCount++;
  108266. if (shaderString) {
  108267. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  108268. }
  108269. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  108270. onload();
  108271. }
  108272. }, function () {
  108273. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  108274. });
  108275. };
  108276. for (var sha in gltfRuntime.shaders) {
  108277. hasShaders = true;
  108278. var shader = gltfRuntime.shaders[sha];
  108279. if (shader) {
  108280. processShader.bind(this, sha, shader)();
  108281. }
  108282. else {
  108283. BABYLON.Tools.Error("No shader named: " + sha);
  108284. }
  108285. }
  108286. if (!hasShaders) {
  108287. onload();
  108288. }
  108289. };
  108290. ;
  108291. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  108292. var hasBuffers = false;
  108293. var processBuffer = function (buf, buffer) {
  108294. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  108295. gltfRuntime.loadedBufferCount++;
  108296. if (bufferView) {
  108297. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  108298. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  108299. }
  108300. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108301. }
  108302. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108303. onLoad();
  108304. }
  108305. }, function () {
  108306. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108307. });
  108308. };
  108309. for (var buf in gltfRuntime.buffers) {
  108310. hasBuffers = true;
  108311. var buffer = gltfRuntime.buffers[buf];
  108312. if (buffer) {
  108313. processBuffer.bind(this, buf, buffer)();
  108314. }
  108315. else {
  108316. BABYLON.Tools.Error("No buffer named: " + buf);
  108317. }
  108318. }
  108319. if (!hasBuffers) {
  108320. onLoad();
  108321. }
  108322. };
  108323. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108324. var currentScene = gltfRuntime.currentScene;
  108325. if (currentScene) {
  108326. // Only one scene even if multiple scenes are defined
  108327. for (var i = 0; i < currentScene.nodes.length; i++) {
  108328. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108329. }
  108330. }
  108331. else {
  108332. // Load all scenes
  108333. for (var thing in gltfRuntime.scenes) {
  108334. currentScene = gltfRuntime.scenes[thing];
  108335. for (var i = 0; i < currentScene.nodes.length; i++) {
  108336. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108337. }
  108338. }
  108339. }
  108340. };
  108341. GLTFLoader.Extensions = {};
  108342. return GLTFLoader;
  108343. }());
  108344. GLTF1.GLTFLoader = GLTFLoader;
  108345. ;
  108346. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108347. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108348. })(BABYLON || (BABYLON = {}));
  108349. //# sourceMappingURL=babylon.glTFLoader.js.map
  108350. var BABYLON;
  108351. (function (BABYLON) {
  108352. var GLTF1;
  108353. (function (GLTF1) {
  108354. /**
  108355. * Utils functions for GLTF
  108356. */
  108357. var GLTFUtils = /** @class */ (function () {
  108358. function GLTFUtils() {
  108359. }
  108360. /**
  108361. * Sets the given "parameter" matrix
  108362. * @param scene: the {BABYLON.Scene} object
  108363. * @param source: the source node where to pick the matrix
  108364. * @param parameter: the GLTF technique parameter
  108365. * @param uniformName: the name of the shader's uniform
  108366. * @param shaderMaterial: the shader material
  108367. */
  108368. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108369. var mat = null;
  108370. if (parameter.semantic === "MODEL") {
  108371. mat = source.getWorldMatrix();
  108372. }
  108373. else if (parameter.semantic === "PROJECTION") {
  108374. mat = scene.getProjectionMatrix();
  108375. }
  108376. else if (parameter.semantic === "VIEW") {
  108377. mat = scene.getViewMatrix();
  108378. }
  108379. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108380. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108381. }
  108382. else if (parameter.semantic === "MODELVIEW") {
  108383. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108384. }
  108385. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108386. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108387. }
  108388. else if (parameter.semantic === "MODELINVERSE") {
  108389. mat = source.getWorldMatrix().invert();
  108390. }
  108391. else if (parameter.semantic === "VIEWINVERSE") {
  108392. mat = scene.getViewMatrix().invert();
  108393. }
  108394. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108395. mat = scene.getProjectionMatrix().invert();
  108396. }
  108397. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108398. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108399. }
  108400. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108401. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108402. }
  108403. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108404. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108405. }
  108406. else {
  108407. debugger;
  108408. }
  108409. if (mat) {
  108410. switch (parameter.type) {
  108411. case GLTF1.EParameterType.FLOAT_MAT2:
  108412. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108413. break;
  108414. case GLTF1.EParameterType.FLOAT_MAT3:
  108415. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108416. break;
  108417. case GLTF1.EParameterType.FLOAT_MAT4:
  108418. shaderMaterial.setMatrix(uniformName, mat);
  108419. break;
  108420. default: break;
  108421. }
  108422. }
  108423. };
  108424. /**
  108425. * Sets the given "parameter" matrix
  108426. * @param shaderMaterial: the shader material
  108427. * @param uniform: the name of the shader's uniform
  108428. * @param value: the value of the uniform
  108429. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108430. */
  108431. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108432. switch (type) {
  108433. case GLTF1.EParameterType.FLOAT:
  108434. shaderMaterial.setFloat(uniform, value);
  108435. return true;
  108436. case GLTF1.EParameterType.FLOAT_VEC2:
  108437. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108438. return true;
  108439. case GLTF1.EParameterType.FLOAT_VEC3:
  108440. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108441. return true;
  108442. case GLTF1.EParameterType.FLOAT_VEC4:
  108443. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108444. return true;
  108445. default: return false;
  108446. }
  108447. };
  108448. /**
  108449. * Returns the wrap mode of the texture
  108450. * @param mode: the mode value
  108451. */
  108452. GLTFUtils.GetWrapMode = function (mode) {
  108453. switch (mode) {
  108454. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108455. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108456. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108457. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108458. }
  108459. };
  108460. /**
  108461. * Returns the byte stride giving an accessor
  108462. * @param accessor: the GLTF accessor objet
  108463. */
  108464. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108465. // Needs this function since "byteStride" isn't requiered in glTF format
  108466. var type = accessor.type;
  108467. switch (type) {
  108468. case "VEC2": return 2;
  108469. case "VEC3": return 3;
  108470. case "VEC4": return 4;
  108471. case "MAT2": return 4;
  108472. case "MAT3": return 9;
  108473. case "MAT4": return 16;
  108474. default: return 1;
  108475. }
  108476. };
  108477. /**
  108478. * Returns the texture filter mode giving a mode value
  108479. * @param mode: the filter mode value
  108480. */
  108481. GLTFUtils.GetTextureFilterMode = function (mode) {
  108482. switch (mode) {
  108483. case GLTF1.ETextureFilterType.LINEAR:
  108484. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108485. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108486. case GLTF1.ETextureFilterType.NEAREST:
  108487. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108488. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108489. }
  108490. };
  108491. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108492. var byteOffset = bufferView.byteOffset + byteOffset;
  108493. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108494. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108495. throw new Error("Buffer access is out of range");
  108496. }
  108497. var buffer = loadedBufferView.buffer;
  108498. byteOffset += loadedBufferView.byteOffset;
  108499. switch (componentType) {
  108500. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108501. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108502. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108503. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108504. default: return new Float32Array(buffer, byteOffset, byteLength);
  108505. }
  108506. };
  108507. /**
  108508. * Returns a buffer from its accessor
  108509. * @param gltfRuntime: the GLTF runtime
  108510. * @param accessor: the GLTF accessor
  108511. */
  108512. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108513. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108514. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108515. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108516. };
  108517. /**
  108518. * Decodes a buffer view into a string
  108519. * @param view: the buffer view
  108520. */
  108521. GLTFUtils.DecodeBufferToText = function (view) {
  108522. var result = "";
  108523. var length = view.byteLength;
  108524. for (var i = 0; i < length; ++i) {
  108525. result += String.fromCharCode(view[i]);
  108526. }
  108527. return result;
  108528. };
  108529. /**
  108530. * Returns the default material of gltf. Related to
  108531. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108532. * @param scene: the Babylon.js scene
  108533. */
  108534. GLTFUtils.GetDefaultMaterial = function (scene) {
  108535. if (!GLTFUtils._DefaultMaterial) {
  108536. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108537. "precision highp float;",
  108538. "",
  108539. "uniform mat4 worldView;",
  108540. "uniform mat4 projection;",
  108541. "",
  108542. "attribute vec3 position;",
  108543. "",
  108544. "void main(void)",
  108545. "{",
  108546. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108547. "}"
  108548. ].join("\n");
  108549. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108550. "precision highp float;",
  108551. "",
  108552. "uniform vec4 u_emission;",
  108553. "",
  108554. "void main(void)",
  108555. "{",
  108556. " gl_FragColor = u_emission;",
  108557. "}"
  108558. ].join("\n");
  108559. var shaderPath = {
  108560. vertex: "GLTFDefaultMaterial",
  108561. fragment: "GLTFDefaultMaterial"
  108562. };
  108563. var options = {
  108564. attributes: ["position"],
  108565. uniforms: ["worldView", "projection", "u_emission"],
  108566. samplers: new Array(),
  108567. needAlphaBlending: false
  108568. };
  108569. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108570. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108571. }
  108572. return GLTFUtils._DefaultMaterial;
  108573. };
  108574. // The GLTF default material
  108575. GLTFUtils._DefaultMaterial = null;
  108576. return GLTFUtils;
  108577. }());
  108578. GLTF1.GLTFUtils = GLTFUtils;
  108579. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108580. })(BABYLON || (BABYLON = {}));
  108581. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108582. var BABYLON;
  108583. (function (BABYLON) {
  108584. var GLTF1;
  108585. (function (GLTF1) {
  108586. var GLTFLoaderExtension = /** @class */ (function () {
  108587. function GLTFLoaderExtension(name) {
  108588. this._name = name;
  108589. }
  108590. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108591. get: function () {
  108592. return this._name;
  108593. },
  108594. enumerable: true,
  108595. configurable: true
  108596. });
  108597. /**
  108598. * Defines an override for loading the runtime
  108599. * Return true to stop further extensions from loading the runtime
  108600. */
  108601. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108602. return false;
  108603. };
  108604. /**
  108605. * Defines an onverride for creating gltf runtime
  108606. * Return true to stop further extensions from creating the runtime
  108607. */
  108608. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108609. return false;
  108610. };
  108611. /**
  108612. * Defines an override for loading buffers
  108613. * Return true to stop further extensions from loading this buffer
  108614. */
  108615. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108616. return false;
  108617. };
  108618. /**
  108619. * Defines an override for loading texture buffers
  108620. * Return true to stop further extensions from loading this texture data
  108621. */
  108622. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108623. return false;
  108624. };
  108625. /**
  108626. * Defines an override for creating textures
  108627. * Return true to stop further extensions from loading this texture
  108628. */
  108629. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108630. return false;
  108631. };
  108632. /**
  108633. * Defines an override for loading shader strings
  108634. * Return true to stop further extensions from loading this shader data
  108635. */
  108636. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108637. return false;
  108638. };
  108639. /**
  108640. * Defines an override for loading materials
  108641. * Return true to stop further extensions from loading this material
  108642. */
  108643. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108644. return false;
  108645. };
  108646. // ---------
  108647. // Utilities
  108648. // ---------
  108649. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108650. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108651. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108652. }, function () {
  108653. setTimeout(function () {
  108654. if (!onSuccess) {
  108655. return;
  108656. }
  108657. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108658. });
  108659. });
  108660. };
  108661. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108662. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108663. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108664. }, function () {
  108665. setTimeout(function () {
  108666. onSuccess();
  108667. });
  108668. });
  108669. };
  108670. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108671. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108672. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108673. }, function () {
  108674. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108675. });
  108676. };
  108677. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108678. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108679. if (buffer) {
  108680. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108681. }
  108682. }, onError);
  108683. };
  108684. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108685. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108686. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108687. }, function () {
  108688. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108689. });
  108690. };
  108691. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108692. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108693. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108694. }, function () {
  108695. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108696. });
  108697. };
  108698. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108699. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108700. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108701. }, function () {
  108702. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108703. });
  108704. };
  108705. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108706. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108707. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108708. }, function () {
  108709. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108710. });
  108711. };
  108712. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108713. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108714. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108715. if (func(loaderExtension)) {
  108716. return;
  108717. }
  108718. }
  108719. defaultFunc();
  108720. };
  108721. return GLTFLoaderExtension;
  108722. }());
  108723. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108724. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108725. })(BABYLON || (BABYLON = {}));
  108726. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108727. var BABYLON;
  108728. (function (BABYLON) {
  108729. var GLTF1;
  108730. (function (GLTF1) {
  108731. var BinaryExtensionBufferName = "binary_glTF";
  108732. ;
  108733. ;
  108734. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108735. __extends(GLTFBinaryExtension, _super);
  108736. function GLTFBinaryExtension() {
  108737. return _super.call(this, "KHR_binary_glTF") || this;
  108738. }
  108739. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108740. var extensionsUsed = data.json.extensionsUsed;
  108741. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108742. return false;
  108743. }
  108744. this._bin = data.bin;
  108745. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108746. return true;
  108747. };
  108748. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108749. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108750. return false;
  108751. }
  108752. if (id !== BinaryExtensionBufferName) {
  108753. return false;
  108754. }
  108755. onSuccess(this._bin);
  108756. return true;
  108757. };
  108758. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108759. var texture = gltfRuntime.textures[id];
  108760. var source = gltfRuntime.images[texture.source];
  108761. if (!source.extensions || !(this.name in source.extensions)) {
  108762. return false;
  108763. }
  108764. var sourceExt = source.extensions[this.name];
  108765. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108766. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108767. onSuccess(buffer);
  108768. return true;
  108769. };
  108770. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108771. var shader = gltfRuntime.shaders[id];
  108772. if (!shader.extensions || !(this.name in shader.extensions)) {
  108773. return false;
  108774. }
  108775. var binaryExtensionShader = shader.extensions[this.name];
  108776. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108777. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108778. setTimeout(function () {
  108779. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108780. onSuccess(shaderString);
  108781. });
  108782. return true;
  108783. };
  108784. return GLTFBinaryExtension;
  108785. }(GLTF1.GLTFLoaderExtension));
  108786. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108787. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108788. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108789. })(BABYLON || (BABYLON = {}));
  108790. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108791. var BABYLON;
  108792. (function (BABYLON) {
  108793. var GLTF1;
  108794. (function (GLTF1) {
  108795. ;
  108796. ;
  108797. ;
  108798. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108799. __extends(GLTFMaterialsCommonExtension, _super);
  108800. function GLTFMaterialsCommonExtension() {
  108801. return _super.call(this, "KHR_materials_common") || this;
  108802. }
  108803. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108804. if (!gltfRuntime.extensions)
  108805. return false;
  108806. var extension = gltfRuntime.extensions[this.name];
  108807. if (!extension)
  108808. return false;
  108809. // Create lights
  108810. var lights = extension.lights;
  108811. if (lights) {
  108812. for (var thing in lights) {
  108813. var light = lights[thing];
  108814. switch (light.type) {
  108815. case "ambient":
  108816. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108817. var ambient = light.ambient;
  108818. if (ambient) {
  108819. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108820. }
  108821. break;
  108822. case "point":
  108823. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108824. var point = light.point;
  108825. if (point) {
  108826. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108827. }
  108828. break;
  108829. case "directional":
  108830. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108831. var directional = light.directional;
  108832. if (directional) {
  108833. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108834. }
  108835. break;
  108836. case "spot":
  108837. var spot = light.spot;
  108838. if (spot) {
  108839. 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);
  108840. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108841. }
  108842. break;
  108843. default:
  108844. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108845. break;
  108846. }
  108847. }
  108848. }
  108849. return false;
  108850. };
  108851. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108852. var material = gltfRuntime.materials[id];
  108853. if (!material || !material.extensions)
  108854. return false;
  108855. var extension = material.extensions[this.name];
  108856. if (!extension)
  108857. return false;
  108858. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108859. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108860. if (extension.technique === "CONSTANT") {
  108861. standardMaterial.disableLighting = true;
  108862. }
  108863. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108864. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108865. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108866. // Ambient
  108867. if (typeof extension.values.ambient === "string") {
  108868. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108869. }
  108870. else {
  108871. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108872. }
  108873. // Diffuse
  108874. if (typeof extension.values.diffuse === "string") {
  108875. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108876. }
  108877. else {
  108878. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108879. }
  108880. // Emission
  108881. if (typeof extension.values.emission === "string") {
  108882. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108883. }
  108884. else {
  108885. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108886. }
  108887. // Specular
  108888. if (typeof extension.values.specular === "string") {
  108889. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108890. }
  108891. else {
  108892. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108893. }
  108894. return true;
  108895. };
  108896. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108897. // Create buffer from texture url
  108898. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108899. // Create texture from buffer
  108900. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108901. }, onError);
  108902. };
  108903. return GLTFMaterialsCommonExtension;
  108904. }(GLTF1.GLTFLoaderExtension));
  108905. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108906. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108907. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108908. })(BABYLON || (BABYLON = {}));
  108909. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108910. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108911. /**
  108912. * Defines the module used to import/export glTF 2.0 assets
  108913. */
  108914. var BABYLON;
  108915. (function (BABYLON) {
  108916. var GLTF2;
  108917. (function (GLTF2) {
  108918. var _ArrayItem = /** @class */ (function () {
  108919. function _ArrayItem() {
  108920. }
  108921. _ArrayItem.Assign = function (values) {
  108922. if (values) {
  108923. for (var index = 0; index < values.length; index++) {
  108924. values[index]._index = index;
  108925. }
  108926. }
  108927. };
  108928. return _ArrayItem;
  108929. }());
  108930. /** @hidden */
  108931. var GLTFLoader = /** @class */ (function () {
  108932. function GLTFLoader(parent) {
  108933. this._completePromises = new Array();
  108934. this._disposed = false;
  108935. this._state = null;
  108936. this._extensions = {};
  108937. this._defaultSampler = {};
  108938. this._defaultBabylonMaterials = {};
  108939. this._requests = new Array();
  108940. this._parent = parent;
  108941. }
  108942. GLTFLoader._Register = function (name, factory) {
  108943. if (GLTFLoader._ExtensionFactories[name]) {
  108944. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108945. return;
  108946. }
  108947. GLTFLoader._ExtensionFactories[name] = factory;
  108948. // Keep the order of registration so that extensions registered first are called first.
  108949. GLTFLoader._ExtensionNames.push(name);
  108950. };
  108951. Object.defineProperty(GLTFLoader.prototype, "state", {
  108952. /**
  108953. * Loader state or null if the loader is not active.
  108954. */
  108955. get: function () {
  108956. return this._state;
  108957. },
  108958. enumerable: true,
  108959. configurable: true
  108960. });
  108961. GLTFLoader.prototype.dispose = function () {
  108962. if (this._disposed) {
  108963. return;
  108964. }
  108965. this._disposed = true;
  108966. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108967. var request = _a[_i];
  108968. request.abort();
  108969. }
  108970. this._requests.length = 0;
  108971. delete this._gltf;
  108972. delete this._babylonScene;
  108973. delete this._readyPromise;
  108974. this._completePromises.length = 0;
  108975. for (var name_1 in this._extensions) {
  108976. this._extensions[name_1].dispose();
  108977. }
  108978. this._extensions = {};
  108979. delete this._rootBabylonMesh;
  108980. delete this._progressCallback;
  108981. this._parent._clear();
  108982. };
  108983. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108984. var _this = this;
  108985. return Promise.resolve().then(function () {
  108986. _this._babylonScene = scene;
  108987. _this._rootUrl = rootUrl;
  108988. _this._progressCallback = onProgress;
  108989. _this._loadData(data);
  108990. var nodes = null;
  108991. if (meshesNames) {
  108992. var nodeMap_1 = {};
  108993. if (_this._gltf.nodes) {
  108994. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108995. var node = _a[_i];
  108996. if (node.name) {
  108997. nodeMap_1[node.name] = node._index;
  108998. }
  108999. }
  109000. }
  109001. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109002. nodes = names.map(function (name) {
  109003. var node = nodeMap_1[name];
  109004. if (node === undefined) {
  109005. throw new Error("Failed to find node '" + name + "'");
  109006. }
  109007. return node;
  109008. });
  109009. }
  109010. return _this._loadAsync(nodes).then(function () {
  109011. return {
  109012. meshes: _this._getMeshes(),
  109013. particleSystems: [],
  109014. skeletons: _this._getSkeletons(),
  109015. animationGroups: _this._getAnimationGroups()
  109016. };
  109017. });
  109018. });
  109019. };
  109020. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109021. var _this = this;
  109022. return Promise.resolve().then(function () {
  109023. _this._babylonScene = scene;
  109024. _this._rootUrl = rootUrl;
  109025. _this._progressCallback = onProgress;
  109026. _this._loadData(data);
  109027. return _this._loadAsync(null);
  109028. });
  109029. };
  109030. GLTFLoader.prototype._loadAsync = function (nodes) {
  109031. var _this = this;
  109032. return Promise.resolve().then(function () {
  109033. _this._parent._startPerformanceCounter("Loading => Ready");
  109034. _this._parent._startPerformanceCounter("Loading => Complete");
  109035. _this._state = BABYLON.GLTFLoaderState.LOADING;
  109036. _this._parent._log("Loading");
  109037. var readyDeferred = new BABYLON.Deferred();
  109038. _this._readyPromise = readyDeferred.promise;
  109039. _this._loadExtensions();
  109040. _this._checkExtensions();
  109041. var promises = new Array();
  109042. if (nodes) {
  109043. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  109044. }
  109045. else {
  109046. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  109047. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  109048. }
  109049. if (_this._parent.compileMaterials) {
  109050. promises.push(_this._compileMaterialsAsync());
  109051. }
  109052. if (_this._parent.compileShadowGenerators) {
  109053. promises.push(_this._compileShadowGeneratorsAsync());
  109054. }
  109055. var resultPromise = Promise.all(promises).then(function () {
  109056. _this._state = BABYLON.GLTFLoaderState.READY;
  109057. _this._parent._log("Ready");
  109058. readyDeferred.resolve();
  109059. _this._startAnimations();
  109060. });
  109061. resultPromise.then(function () {
  109062. _this._parent._endPerformanceCounter("Loading => Ready");
  109063. BABYLON.Tools.SetImmediate(function () {
  109064. if (!_this._disposed) {
  109065. Promise.all(_this._completePromises).then(function () {
  109066. _this._parent._endPerformanceCounter("Loading => Complete");
  109067. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  109068. _this._parent._log("Complete");
  109069. _this._parent.onCompleteObservable.notifyObservers(undefined);
  109070. _this._parent.onCompleteObservable.clear();
  109071. _this.dispose();
  109072. }).catch(function (error) {
  109073. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109074. _this.dispose();
  109075. });
  109076. }
  109077. });
  109078. });
  109079. return resultPromise;
  109080. }).catch(function (error) {
  109081. if (!_this._disposed) {
  109082. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109083. _this.dispose();
  109084. throw error;
  109085. }
  109086. });
  109087. };
  109088. GLTFLoader.prototype._loadData = function (data) {
  109089. this._gltf = data.json;
  109090. this._setupData();
  109091. if (data.bin) {
  109092. var buffers = this._gltf.buffers;
  109093. if (buffers && buffers[0] && !buffers[0].uri) {
  109094. var binaryBuffer = buffers[0];
  109095. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  109096. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  109097. }
  109098. binaryBuffer._data = Promise.resolve(data.bin);
  109099. }
  109100. else {
  109101. BABYLON.Tools.Warn("Unexpected BIN chunk");
  109102. }
  109103. }
  109104. };
  109105. GLTFLoader.prototype._setupData = function () {
  109106. _ArrayItem.Assign(this._gltf.accessors);
  109107. _ArrayItem.Assign(this._gltf.animations);
  109108. _ArrayItem.Assign(this._gltf.buffers);
  109109. _ArrayItem.Assign(this._gltf.bufferViews);
  109110. _ArrayItem.Assign(this._gltf.cameras);
  109111. _ArrayItem.Assign(this._gltf.images);
  109112. _ArrayItem.Assign(this._gltf.materials);
  109113. _ArrayItem.Assign(this._gltf.meshes);
  109114. _ArrayItem.Assign(this._gltf.nodes);
  109115. _ArrayItem.Assign(this._gltf.samplers);
  109116. _ArrayItem.Assign(this._gltf.scenes);
  109117. _ArrayItem.Assign(this._gltf.skins);
  109118. _ArrayItem.Assign(this._gltf.textures);
  109119. if (this._gltf.nodes) {
  109120. var nodeParents = {};
  109121. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  109122. var node = _a[_i];
  109123. if (node.children) {
  109124. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  109125. var index = _c[_b];
  109126. nodeParents[index] = node._index;
  109127. }
  109128. }
  109129. }
  109130. var rootNode = this._createRootNode();
  109131. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  109132. var node = _e[_d];
  109133. var parentIndex = nodeParents[node._index];
  109134. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  109135. }
  109136. }
  109137. };
  109138. GLTFLoader.prototype._loadExtensions = function () {
  109139. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  109140. var name_2 = _a[_i];
  109141. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  109142. this._extensions[name_2] = extension;
  109143. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  109144. }
  109145. this._parent.onExtensionLoadedObservable.clear();
  109146. };
  109147. GLTFLoader.prototype._checkExtensions = function () {
  109148. if (this._gltf.extensionsRequired) {
  109149. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  109150. var name_3 = _a[_i];
  109151. var extension = this._extensions[name_3];
  109152. if (!extension || !extension.enabled) {
  109153. throw new Error("Require extension " + name_3 + " is not available");
  109154. }
  109155. }
  109156. }
  109157. };
  109158. GLTFLoader.prototype._createRootNode = function () {
  109159. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  109160. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  109161. switch (this._parent.coordinateSystemMode) {
  109162. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  109163. if (!this._babylonScene.useRightHandedSystem) {
  109164. rootNode.rotation = [0, 1, 0, 0];
  109165. rootNode.scale = [1, 1, -1];
  109166. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  109167. }
  109168. break;
  109169. }
  109170. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  109171. this._babylonScene.useRightHandedSystem = true;
  109172. break;
  109173. }
  109174. default: {
  109175. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  109176. }
  109177. }
  109178. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  109179. return rootNode;
  109180. };
  109181. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  109182. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  109183. if (promise) {
  109184. return promise;
  109185. }
  109186. var promises = new Array();
  109187. this._parent._logOpen(context + " " + (scene.name || ""));
  109188. if (scene.nodes) {
  109189. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  109190. var index = _a[_i];
  109191. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  109192. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109193. }
  109194. }
  109195. promises.push(this._loadAnimationsAsync());
  109196. this._parent._logClose();
  109197. return Promise.all(promises).then(function () { });
  109198. };
  109199. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  109200. if (node._primitiveBabylonMeshes) {
  109201. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  109202. var babylonMesh = _a[_i];
  109203. callback(babylonMesh);
  109204. }
  109205. }
  109206. else {
  109207. callback(node._babylonMesh);
  109208. }
  109209. };
  109210. GLTFLoader.prototype._getMeshes = function () {
  109211. var meshes = new Array();
  109212. // Root mesh is always first.
  109213. meshes.push(this._rootBabylonMesh);
  109214. var nodes = this._gltf.nodes;
  109215. if (nodes) {
  109216. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  109217. var node = nodes_1[_i];
  109218. if (node._babylonMesh) {
  109219. meshes.push(node._babylonMesh);
  109220. }
  109221. if (node._primitiveBabylonMeshes) {
  109222. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  109223. var babylonMesh = _b[_a];
  109224. meshes.push(babylonMesh);
  109225. }
  109226. }
  109227. }
  109228. }
  109229. return meshes;
  109230. };
  109231. GLTFLoader.prototype._getSkeletons = function () {
  109232. var skeletons = new Array();
  109233. var skins = this._gltf.skins;
  109234. if (skins) {
  109235. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  109236. var skin = skins_1[_i];
  109237. if (skin._babylonSkeleton) {
  109238. skeletons.push(skin._babylonSkeleton);
  109239. }
  109240. }
  109241. }
  109242. return skeletons;
  109243. };
  109244. GLTFLoader.prototype._getAnimationGroups = function () {
  109245. var animationGroups = new Array();
  109246. var animations = this._gltf.animations;
  109247. if (animations) {
  109248. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  109249. var animation = animations_1[_i];
  109250. if (animation._babylonAnimationGroup) {
  109251. animationGroups.push(animation._babylonAnimationGroup);
  109252. }
  109253. }
  109254. }
  109255. return animationGroups;
  109256. };
  109257. GLTFLoader.prototype._startAnimations = function () {
  109258. switch (this._parent.animationStartMode) {
  109259. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  109260. // do nothing
  109261. break;
  109262. }
  109263. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  109264. var babylonAnimationGroups = this._getAnimationGroups();
  109265. if (babylonAnimationGroups.length !== 0) {
  109266. babylonAnimationGroups[0].start(true);
  109267. }
  109268. break;
  109269. }
  109270. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  109271. var babylonAnimationGroups = this._getAnimationGroups();
  109272. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  109273. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  109274. babylonAnimationGroup.start(true);
  109275. }
  109276. break;
  109277. }
  109278. default: {
  109279. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  109280. return;
  109281. }
  109282. }
  109283. };
  109284. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  109285. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  109286. if (promise) {
  109287. return promise;
  109288. }
  109289. if (node._babylonMesh) {
  109290. throw new Error(context + ": Invalid recursive node hierarchy");
  109291. }
  109292. var promises = new Array();
  109293. this._parent._logOpen(context + " " + (node.name || ""));
  109294. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  109295. node._babylonMesh = babylonMesh;
  109296. babylonMesh.setEnabled(false);
  109297. GLTFLoader._LoadTransform(node, babylonMesh);
  109298. if (node.mesh != undefined) {
  109299. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  109300. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  109301. }
  109302. if (node.camera != undefined) {
  109303. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  109304. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  109305. }
  109306. if (node.children) {
  109307. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  109308. var index = _a[_i];
  109309. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  109310. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  109311. }
  109312. }
  109313. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109314. this._parent._logClose();
  109315. return Promise.all(promises).then(function () {
  109316. babylonMesh.setEnabled(true);
  109317. });
  109318. };
  109319. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  109320. var _this = this;
  109321. var promises = new Array();
  109322. this._parent._logOpen(context + " " + (mesh.name || ""));
  109323. var primitives = mesh.primitives;
  109324. if (!primitives || primitives.length === 0) {
  109325. throw new Error(context + ": Primitives are missing");
  109326. }
  109327. _ArrayItem.Assign(primitives);
  109328. if (primitives.length === 1) {
  109329. var primitive = primitives[0];
  109330. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  109331. }
  109332. else {
  109333. node._primitiveBabylonMeshes = [];
  109334. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  109335. var primitive = primitives_1[_i];
  109336. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  109337. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  109338. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  109339. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109340. }
  109341. }
  109342. if (node.skin != undefined) {
  109343. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109344. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109345. }
  109346. this._parent._logClose();
  109347. return Promise.all(promises).then(function () {
  109348. _this._forEachPrimitive(node, function (babylonMesh) {
  109349. babylonMesh._refreshBoundingInfo(true);
  109350. });
  109351. });
  109352. };
  109353. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109354. var _this = this;
  109355. var promises = new Array();
  109356. this._parent._logOpen("" + context);
  109357. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109358. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  109359. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  109360. babylonGeometry.applyToMesh(babylonMesh);
  109361. });
  109362. }));
  109363. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  109364. if (primitive.material == undefined) {
  109365. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  109366. }
  109367. else {
  109368. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109369. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109370. babylonMesh.material = babylonMaterial;
  109371. }));
  109372. }
  109373. this._parent._logClose();
  109374. return Promise.all(promises).then(function () { });
  109375. };
  109376. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109377. var _this = this;
  109378. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109379. if (promise) {
  109380. return promise;
  109381. }
  109382. var attributes = primitive.attributes;
  109383. if (!attributes) {
  109384. throw new Error(context + ": Attributes are missing");
  109385. }
  109386. var promises = new Array();
  109387. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  109388. if (primitive.indices == undefined) {
  109389. babylonMesh.isUnIndexed = true;
  109390. }
  109391. else {
  109392. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109393. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109394. babylonGeometry.setIndices(data);
  109395. }));
  109396. }
  109397. var loadAttribute = function (attribute, kind, callback) {
  109398. if (attributes[attribute] == undefined) {
  109399. return;
  109400. }
  109401. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109402. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109403. babylonMesh._delayInfo.push(kind);
  109404. }
  109405. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109406. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  109407. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  109408. }));
  109409. if (callback) {
  109410. callback(accessor);
  109411. }
  109412. };
  109413. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109414. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109415. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109416. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109417. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109418. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109419. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109420. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  109421. if (accessor.type === "VEC4" /* VEC4 */) {
  109422. babylonMesh.hasVertexAlpha = true;
  109423. }
  109424. });
  109425. return Promise.all(promises).then(function () {
  109426. return babylonGeometry;
  109427. });
  109428. };
  109429. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109430. if (!primitive.targets) {
  109431. return;
  109432. }
  109433. if (node._numMorphTargets == undefined) {
  109434. node._numMorphTargets = primitive.targets.length;
  109435. }
  109436. else if (primitive.targets.length !== node._numMorphTargets) {
  109437. throw new Error(context + ": Primitives do not have the same number of targets");
  109438. }
  109439. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109440. for (var index = 0; index < primitive.targets.length; index++) {
  109441. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109442. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109443. // TODO: tell the target whether it has positions, normals, tangents
  109444. }
  109445. };
  109446. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  109447. if (!primitive.targets) {
  109448. return Promise.resolve();
  109449. }
  109450. var promises = new Array();
  109451. var morphTargetManager = babylonMesh.morphTargetManager;
  109452. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109453. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109454. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  109455. }
  109456. return Promise.all(promises).then(function () { });
  109457. };
  109458. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  109459. var _this = this;
  109460. var promises = new Array();
  109461. var loadAttribute = function (attribute, kind, setData) {
  109462. if (attributes[attribute] == undefined) {
  109463. return;
  109464. }
  109465. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  109466. if (!babylonVertexBuffer) {
  109467. return;
  109468. }
  109469. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109470. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109471. setData(babylonVertexBuffer, data);
  109472. }));
  109473. };
  109474. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  109475. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109476. data[index] += value;
  109477. });
  109478. babylonMorphTarget.setPositions(data);
  109479. });
  109480. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  109481. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109482. data[index] += value;
  109483. });
  109484. babylonMorphTarget.setNormals(data);
  109485. });
  109486. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  109487. var dataIndex = 0;
  109488. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  109489. // Tangent data for morph targets is stored as xyz delta.
  109490. // The vertexData.tangent is stored as xyzw.
  109491. // So we need to skip every fourth vertexData.tangent.
  109492. if (((index + 1) % 4) !== 0) {
  109493. data[dataIndex++] += value;
  109494. }
  109495. });
  109496. babylonMorphTarget.setTangents(data);
  109497. });
  109498. return Promise.all(promises).then(function () { });
  109499. };
  109500. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109501. var position = BABYLON.Vector3.Zero();
  109502. var rotation = BABYLON.Quaternion.Identity();
  109503. var scaling = BABYLON.Vector3.One();
  109504. if (node.matrix) {
  109505. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109506. matrix.decompose(scaling, rotation, position);
  109507. }
  109508. else {
  109509. if (node.translation)
  109510. position = BABYLON.Vector3.FromArray(node.translation);
  109511. if (node.rotation)
  109512. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109513. if (node.scale)
  109514. scaling = BABYLON.Vector3.FromArray(node.scale);
  109515. }
  109516. babylonNode.position = position;
  109517. babylonNode.rotationQuaternion = rotation;
  109518. babylonNode.scaling = scaling;
  109519. };
  109520. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109521. var _this = this;
  109522. var assignSkeleton = function (skeleton) {
  109523. _this._forEachPrimitive(node, function (babylonMesh) {
  109524. babylonMesh.skeleton = skeleton;
  109525. });
  109526. // Ignore the TRS of skinned nodes.
  109527. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  109528. node._babylonMesh.parent = _this._rootBabylonMesh;
  109529. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109530. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109531. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109532. };
  109533. if (skin._loaded) {
  109534. return skin._loaded.then(function () {
  109535. assignSkeleton(skin._babylonSkeleton);
  109536. });
  109537. }
  109538. var skeletonId = "skeleton" + skin._index;
  109539. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  109540. skin._babylonSkeleton = babylonSkeleton;
  109541. this._loadBones(context, skin);
  109542. assignSkeleton(babylonSkeleton);
  109543. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109544. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  109545. }));
  109546. };
  109547. GLTFLoader.prototype._loadBones = function (context, skin) {
  109548. var babylonBones = {};
  109549. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109550. var index = _a[_i];
  109551. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109552. this._loadBone(node, skin, babylonBones);
  109553. }
  109554. };
  109555. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  109556. var babylonBone = babylonBones[node._index];
  109557. if (babylonBone) {
  109558. return babylonBone;
  109559. }
  109560. var babylonParentBone = null;
  109561. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  109562. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  109563. }
  109564. var boneIndex = skin.joints.indexOf(node._index);
  109565. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  109566. babylonBones[node._index] = babylonBone;
  109567. node._babylonBones = node._babylonBones || [];
  109568. node._babylonBones.push(babylonBone);
  109569. return babylonBone;
  109570. };
  109571. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109572. if (skin.inverseBindMatrices == undefined) {
  109573. return Promise.resolve(null);
  109574. }
  109575. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109576. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  109577. };
  109578. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  109579. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  109580. var babylonBone = _a[_i];
  109581. var baseMatrix = BABYLON.Matrix.Identity();
  109582. var boneIndex = babylonBone._index;
  109583. if (inverseBindMatricesData && boneIndex !== -1) {
  109584. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  109585. baseMatrix.invertToRef(baseMatrix);
  109586. }
  109587. var babylonParentBone = babylonBone.getParent();
  109588. if (babylonParentBone) {
  109589. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  109590. }
  109591. babylonBone.updateMatrix(baseMatrix, false, false);
  109592. babylonBone._updateDifferenceMatrix(undefined, false);
  109593. }
  109594. };
  109595. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109596. return node.matrix ?
  109597. BABYLON.Matrix.FromArray(node.matrix) :
  109598. 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());
  109599. };
  109600. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  109601. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  109602. babylonCamera.parent = babylonMesh;
  109603. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  109604. switch (camera.type) {
  109605. case "perspective" /* PERSPECTIVE */: {
  109606. var perspective = camera.perspective;
  109607. if (!perspective) {
  109608. throw new Error(context + ": Camera perspective properties are missing");
  109609. }
  109610. babylonCamera.fov = perspective.yfov;
  109611. babylonCamera.minZ = perspective.znear;
  109612. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  109613. break;
  109614. }
  109615. case "orthographic" /* ORTHOGRAPHIC */: {
  109616. if (!camera.orthographic) {
  109617. throw new Error(context + ": Camera orthographic properties are missing");
  109618. }
  109619. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  109620. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  109621. babylonCamera.orthoRight = camera.orthographic.xmag;
  109622. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  109623. babylonCamera.orthoTop = camera.orthographic.ymag;
  109624. babylonCamera.minZ = camera.orthographic.znear;
  109625. babylonCamera.maxZ = camera.orthographic.zfar;
  109626. break;
  109627. }
  109628. default: {
  109629. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  109630. }
  109631. }
  109632. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  109633. };
  109634. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109635. var animations = this._gltf.animations;
  109636. if (!animations) {
  109637. return Promise.resolve();
  109638. }
  109639. var promises = new Array();
  109640. for (var index = 0; index < animations.length; index++) {
  109641. var animation = animations[index];
  109642. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109643. }
  109644. return Promise.all(promises).then(function () { });
  109645. };
  109646. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109647. var _this = this;
  109648. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109649. animation._babylonAnimationGroup = babylonAnimationGroup;
  109650. var promises = new Array();
  109651. _ArrayItem.Assign(animation.channels);
  109652. _ArrayItem.Assign(animation.samplers);
  109653. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109654. var channel = _a[_i];
  109655. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109656. }
  109657. return Promise.all(promises).then(function () {
  109658. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  109659. });
  109660. };
  109661. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109662. var _this = this;
  109663. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109664. // Ignore animations that have no animation targets.
  109665. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  109666. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  109667. return Promise.resolve();
  109668. }
  109669. // Ignore animations targeting TRS of skinned nodes.
  109670. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  109671. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  109672. return Promise.resolve();
  109673. }
  109674. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109675. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109676. var targetPath;
  109677. var animationType;
  109678. switch (channel.target.path) {
  109679. case "translation" /* TRANSLATION */: {
  109680. targetPath = "position";
  109681. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109682. break;
  109683. }
  109684. case "rotation" /* ROTATION */: {
  109685. targetPath = "rotationQuaternion";
  109686. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109687. break;
  109688. }
  109689. case "scale" /* SCALE */: {
  109690. targetPath = "scaling";
  109691. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109692. break;
  109693. }
  109694. case "weights" /* WEIGHTS */: {
  109695. targetPath = "influence";
  109696. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109697. break;
  109698. }
  109699. default: {
  109700. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109701. }
  109702. }
  109703. var outputBufferOffset = 0;
  109704. var getNextOutputValue;
  109705. switch (targetPath) {
  109706. case "position": {
  109707. getNextOutputValue = function () {
  109708. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109709. outputBufferOffset += 3;
  109710. return value;
  109711. };
  109712. break;
  109713. }
  109714. case "rotationQuaternion": {
  109715. getNextOutputValue = function () {
  109716. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109717. outputBufferOffset += 4;
  109718. return value;
  109719. };
  109720. break;
  109721. }
  109722. case "scaling": {
  109723. getNextOutputValue = function () {
  109724. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109725. outputBufferOffset += 3;
  109726. return value;
  109727. };
  109728. break;
  109729. }
  109730. case "influence": {
  109731. getNextOutputValue = function () {
  109732. var value = new Array(targetNode._numMorphTargets);
  109733. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109734. value[i] = data.output[outputBufferOffset++];
  109735. }
  109736. return value;
  109737. };
  109738. break;
  109739. }
  109740. }
  109741. var getNextKey;
  109742. switch (data.interpolation) {
  109743. case "STEP" /* STEP */: {
  109744. getNextKey = function (frameIndex) { return ({
  109745. frame: data.input[frameIndex],
  109746. value: getNextOutputValue(),
  109747. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109748. }); };
  109749. break;
  109750. }
  109751. case "LINEAR" /* LINEAR */: {
  109752. getNextKey = function (frameIndex) { return ({
  109753. frame: data.input[frameIndex],
  109754. value: getNextOutputValue()
  109755. }); };
  109756. break;
  109757. }
  109758. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109759. getNextKey = function (frameIndex) { return ({
  109760. frame: data.input[frameIndex],
  109761. inTangent: getNextOutputValue(),
  109762. value: getNextOutputValue(),
  109763. outTangent: getNextOutputValue()
  109764. }); };
  109765. break;
  109766. }
  109767. }
  109768. var keys = new Array(data.input.length);
  109769. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109770. keys[frameIndex] = getNextKey(frameIndex);
  109771. }
  109772. if (targetPath === "influence") {
  109773. var _loop_1 = function (targetIndex) {
  109774. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109775. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109776. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109777. frame: key.frame,
  109778. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109779. value: key.value[targetIndex],
  109780. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109781. }); }));
  109782. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  109783. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109784. var babylonAnimationClone = babylonAnimation.clone();
  109785. morphTarget.animations.push(babylonAnimationClone);
  109786. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  109787. });
  109788. };
  109789. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109790. _loop_1(targetIndex);
  109791. }
  109792. }
  109793. else {
  109794. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109795. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109796. babylonAnimation.setKeys(keys);
  109797. if (targetNode._babylonBones) {
  109798. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  109799. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  109800. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  109801. babylonAnimationTarget.animations.push(babylonAnimation);
  109802. }
  109803. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  109804. }
  109805. else {
  109806. targetNode._babylonMesh.animations.push(babylonAnimation);
  109807. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  109808. }
  109809. }
  109810. });
  109811. };
  109812. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109813. if (sampler._data) {
  109814. return sampler._data;
  109815. }
  109816. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109817. switch (interpolation) {
  109818. case "STEP" /* STEP */:
  109819. case "LINEAR" /* LINEAR */:
  109820. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109821. break;
  109822. }
  109823. default: {
  109824. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109825. }
  109826. }
  109827. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109828. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109829. sampler._data = Promise.all([
  109830. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  109831. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  109832. ]).then(function (_a) {
  109833. var inputData = _a[0], outputData = _a[1];
  109834. return {
  109835. input: inputData,
  109836. interpolation: interpolation,
  109837. output: outputData,
  109838. };
  109839. });
  109840. return sampler._data;
  109841. };
  109842. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109843. if (buffer._data) {
  109844. return buffer._data;
  109845. }
  109846. if (!buffer.uri) {
  109847. throw new Error(context + ": Uri is missing");
  109848. }
  109849. buffer._data = this._loadUriAsync(context, buffer.uri);
  109850. return buffer._data;
  109851. };
  109852. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109853. if (bufferView._data) {
  109854. return bufferView._data;
  109855. }
  109856. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109857. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  109858. try {
  109859. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109860. }
  109861. catch (e) {
  109862. throw new Error(context + ": " + e.message);
  109863. }
  109864. });
  109865. return bufferView._data;
  109866. };
  109867. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  109868. if (accessor.type !== "SCALAR" /* SCALAR */) {
  109869. throw new Error(context + ": Invalid type " + accessor.type);
  109870. }
  109871. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  109872. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  109873. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  109874. throw new Error(context + ": Invalid component type " + accessor.componentType);
  109875. }
  109876. if (accessor._data) {
  109877. return accessor._data;
  109878. }
  109879. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109880. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109881. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  109882. });
  109883. return accessor._data;
  109884. };
  109885. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  109886. // TODO: support normalized and stride
  109887. var _this = this;
  109888. if (accessor.componentType !== 5126 /* FLOAT */) {
  109889. throw new Error("Invalid component type " + accessor.componentType);
  109890. }
  109891. if (accessor._data) {
  109892. return accessor._data;
  109893. }
  109894. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109895. var length = numComponents * accessor.count;
  109896. if (accessor.bufferView == undefined) {
  109897. accessor._data = Promise.resolve(new Float32Array(length));
  109898. }
  109899. else {
  109900. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109901. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109902. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  109903. });
  109904. }
  109905. if (accessor.sparse) {
  109906. var sparse_1 = accessor.sparse;
  109907. accessor._data = accessor._data.then(function (data) {
  109908. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  109909. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  109910. return Promise.all([
  109911. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  109912. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  109913. ]).then(function (_a) {
  109914. var indicesData = _a[0], valuesData = _a[1];
  109915. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  109916. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  109917. var valuesIndex = 0;
  109918. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  109919. var dataIndex = indices[indicesIndex] * numComponents;
  109920. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109921. data[dataIndex++] = values[valuesIndex++];
  109922. }
  109923. }
  109924. return data;
  109925. });
  109926. });
  109927. }
  109928. return accessor._data;
  109929. };
  109930. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  109931. var _this = this;
  109932. if (bufferView._babylonBuffer) {
  109933. return bufferView._babylonBuffer;
  109934. }
  109935. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  109936. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  109937. });
  109938. return bufferView._babylonBuffer;
  109939. };
  109940. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  109941. var _this = this;
  109942. if (accessor._babylonVertexBuffer) {
  109943. return accessor._babylonVertexBuffer;
  109944. }
  109945. if (accessor.sparse) {
  109946. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  109947. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  109948. });
  109949. }
  109950. else {
  109951. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109952. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  109953. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  109954. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  109955. });
  109956. }
  109957. return accessor._babylonVertexBuffer;
  109958. };
  109959. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  109960. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  109961. if (!babylonMaterial) {
  109962. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  109963. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109964. babylonMaterial.metallic = 1;
  109965. babylonMaterial.roughness = 1;
  109966. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109967. }
  109968. return babylonMaterial;
  109969. };
  109970. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  109971. var promises = new Array();
  109972. // Ensure metallic workflow
  109973. babylonMaterial.metallic = 1;
  109974. babylonMaterial.roughness = 1;
  109975. var properties = material.pbrMetallicRoughness;
  109976. if (properties) {
  109977. if (properties.baseColorFactor) {
  109978. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109979. babylonMaterial.alpha = properties.baseColorFactor[3];
  109980. }
  109981. else {
  109982. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109983. }
  109984. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109985. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109986. if (properties.baseColorTexture) {
  109987. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109988. babylonMaterial.albedoTexture = texture;
  109989. }));
  109990. }
  109991. if (properties.metallicRoughnessTexture) {
  109992. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109993. babylonMaterial.metallicTexture = texture;
  109994. }));
  109995. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109996. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109997. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109998. }
  109999. }
  110000. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110001. return Promise.all(promises).then(function () { });
  110002. };
  110003. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110004. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  110005. if (promise) {
  110006. return promise;
  110007. }
  110008. material._babylonData = material._babylonData || {};
  110009. var babylonData = material._babylonData[babylonDrawMode];
  110010. if (!babylonData) {
  110011. this._parent._logOpen(context + " " + (material.name || ""));
  110012. var name_4 = material.name || "material" + material._index;
  110013. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  110014. babylonData = {
  110015. material: babylonMaterial,
  110016. meshes: [],
  110017. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  110018. };
  110019. material._babylonData[babylonDrawMode] = babylonData;
  110020. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110021. this._parent._logClose();
  110022. }
  110023. babylonData.meshes.push(babylonMesh);
  110024. babylonMesh.onDisposeObservable.addOnce(function () {
  110025. var index = babylonData.meshes.indexOf(babylonMesh);
  110026. if (index !== -1) {
  110027. babylonData.meshes.splice(index, 1);
  110028. }
  110029. });
  110030. assign(babylonData.material);
  110031. return babylonData.loaded;
  110032. };
  110033. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110034. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  110035. if (promise) {
  110036. return promise;
  110037. }
  110038. var promises = new Array();
  110039. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110040. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  110041. return Promise.all(promises).then(function () { });
  110042. };
  110043. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  110044. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  110045. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  110046. babylonMaterial.fillMode = drawMode;
  110047. babylonMaterial.enableSpecularAntiAliasing = true;
  110048. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  110049. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  110050. return babylonMaterial;
  110051. };
  110052. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  110053. var promises = new Array();
  110054. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  110055. if (material.doubleSided) {
  110056. babylonMaterial.backFaceCulling = false;
  110057. babylonMaterial.twoSidedLighting = true;
  110058. }
  110059. if (material.normalTexture) {
  110060. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  110061. babylonMaterial.bumpTexture = texture;
  110062. }));
  110063. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  110064. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  110065. if (material.normalTexture.scale != undefined) {
  110066. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  110067. }
  110068. }
  110069. if (material.occlusionTexture) {
  110070. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  110071. babylonMaterial.ambientTexture = texture;
  110072. }));
  110073. babylonMaterial.useAmbientInGrayScale = true;
  110074. if (material.occlusionTexture.strength != undefined) {
  110075. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  110076. }
  110077. }
  110078. if (material.emissiveTexture) {
  110079. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  110080. babylonMaterial.emissiveTexture = texture;
  110081. }));
  110082. }
  110083. return Promise.all(promises).then(function () { });
  110084. };
  110085. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  110086. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  110087. switch (alphaMode) {
  110088. case "OPAQUE" /* OPAQUE */: {
  110089. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110090. break;
  110091. }
  110092. case "MASK" /* MASK */: {
  110093. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  110094. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  110095. if (babylonMaterial.albedoTexture) {
  110096. babylonMaterial.albedoTexture.hasAlpha = true;
  110097. }
  110098. break;
  110099. }
  110100. case "BLEND" /* BLEND */: {
  110101. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  110102. if (babylonMaterial.albedoTexture) {
  110103. babylonMaterial.albedoTexture.hasAlpha = true;
  110104. babylonMaterial.useAlphaFromAlbedoTexture = true;
  110105. }
  110106. break;
  110107. }
  110108. default: {
  110109. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  110110. }
  110111. }
  110112. };
  110113. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110114. var _this = this;
  110115. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  110116. if (promise) {
  110117. return promise;
  110118. }
  110119. this._parent._logOpen("" + context);
  110120. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  110121. context = "#/textures/" + textureInfo.index;
  110122. var promises = new Array();
  110123. this._parent._logOpen(context + " " + (texture.name || ""));
  110124. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  110125. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  110126. var deferred = new BABYLON.Deferred();
  110127. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  110128. if (!_this._disposed) {
  110129. deferred.resolve();
  110130. }
  110131. }, function (message, exception) {
  110132. if (!_this._disposed) {
  110133. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  110134. }
  110135. });
  110136. promises.push(deferred.promise);
  110137. babylonTexture.name = texture.name || "texture" + texture._index;
  110138. babylonTexture.wrapU = samplerData.wrapU;
  110139. babylonTexture.wrapV = samplerData.wrapV;
  110140. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  110141. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  110142. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  110143. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  110144. babylonTexture.updateURL(dataUrl, blob);
  110145. }));
  110146. assign(babylonTexture);
  110147. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  110148. this._parent._logClose();
  110149. this._parent._logClose();
  110150. return Promise.all(promises).then(function () { });
  110151. };
  110152. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  110153. if (!sampler._data) {
  110154. sampler._data = {
  110155. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  110156. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  110157. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  110158. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  110159. };
  110160. }
  110161. ;
  110162. return sampler._data;
  110163. };
  110164. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  110165. if (!image._blob) {
  110166. this._parent._logOpen(context + " " + (image.name || ""));
  110167. var promise = void 0;
  110168. if (image.uri) {
  110169. promise = this._loadUriAsync(context, image.uri);
  110170. }
  110171. else {
  110172. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  110173. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  110174. }
  110175. image._blob = promise.then(function (data) {
  110176. return new Blob([data], { type: image.mimeType });
  110177. });
  110178. this._parent._logClose();
  110179. }
  110180. return image._blob;
  110181. };
  110182. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  110183. var _this = this;
  110184. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  110185. if (promise) {
  110186. return promise;
  110187. }
  110188. if (!GLTFLoader._ValidateUri(uri)) {
  110189. throw new Error(context + ": Uri '" + uri + "' is invalid");
  110190. }
  110191. if (BABYLON.Tools.IsBase64(uri)) {
  110192. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  110193. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  110194. return Promise.resolve(data);
  110195. }
  110196. this._parent._log("Loading " + uri);
  110197. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  110198. return new Promise(function (resolve, reject) {
  110199. if (!_this._disposed) {
  110200. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  110201. if (!_this._disposed) {
  110202. var data = new Uint8Array(fileData);
  110203. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  110204. resolve(data);
  110205. }
  110206. }, function (event) {
  110207. if (!_this._disposed) {
  110208. if (request_1) {
  110209. request_1._lengthComputable = event.lengthComputable;
  110210. request_1._loaded = event.loaded;
  110211. request_1._total = event.total;
  110212. }
  110213. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  110214. try {
  110215. _this._onProgress();
  110216. }
  110217. catch (e) {
  110218. reject(e);
  110219. }
  110220. }
  110221. }
  110222. }, _this._babylonScene.database, true, function (request, exception) {
  110223. if (!_this._disposed) {
  110224. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  110225. }
  110226. });
  110227. _this._requests.push(request_1);
  110228. }
  110229. });
  110230. });
  110231. };
  110232. GLTFLoader.prototype._onProgress = function () {
  110233. if (!this._progressCallback) {
  110234. return;
  110235. }
  110236. var lengthComputable = true;
  110237. var loaded = 0;
  110238. var total = 0;
  110239. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110240. var request = _a[_i];
  110241. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  110242. return;
  110243. }
  110244. lengthComputable = lengthComputable && request._lengthComputable;
  110245. loaded += request._loaded;
  110246. total += request._total;
  110247. }
  110248. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  110249. };
  110250. GLTFLoader._GetProperty = function (context, array, index) {
  110251. if (!array || index == undefined || !array[index]) {
  110252. throw new Error(context + ": Failed to find index (" + index + ")");
  110253. }
  110254. return array[index];
  110255. };
  110256. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  110257. // Set defaults if undefined
  110258. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  110259. switch (mode) {
  110260. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110261. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110262. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110263. default:
  110264. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  110265. return BABYLON.Texture.WRAP_ADDRESSMODE;
  110266. }
  110267. };
  110268. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  110269. // Set defaults if undefined
  110270. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  110271. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  110272. if (magFilter === 9729 /* LINEAR */) {
  110273. switch (minFilter) {
  110274. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  110275. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  110276. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  110277. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  110278. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  110279. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110280. default:
  110281. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110282. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110283. }
  110284. }
  110285. else {
  110286. if (magFilter !== 9728 /* NEAREST */) {
  110287. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  110288. }
  110289. switch (minFilter) {
  110290. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  110291. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  110292. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110293. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  110294. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  110295. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  110296. default:
  110297. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110298. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110299. }
  110300. }
  110301. };
  110302. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  110303. var buffer = bufferView.buffer;
  110304. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  110305. try {
  110306. switch (componentType) {
  110307. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  110308. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  110309. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  110310. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  110311. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  110312. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  110313. default: throw new Error("Invalid component type " + componentType);
  110314. }
  110315. }
  110316. catch (e) {
  110317. throw new Error(context + ": " + e);
  110318. }
  110319. };
  110320. GLTFLoader._GetNumComponents = function (context, type) {
  110321. switch (type) {
  110322. case "SCALAR": return 1;
  110323. case "VEC2": return 2;
  110324. case "VEC3": return 3;
  110325. case "VEC4": return 4;
  110326. case "MAT2": return 4;
  110327. case "MAT3": return 9;
  110328. case "MAT4": return 16;
  110329. }
  110330. throw new Error(context + ": Invalid type (" + type + ")");
  110331. };
  110332. GLTFLoader._ValidateUri = function (uri) {
  110333. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  110334. };
  110335. GLTFLoader._GetDrawMode = function (context, mode) {
  110336. if (mode == undefined) {
  110337. mode = 4 /* TRIANGLES */;
  110338. }
  110339. switch (mode) {
  110340. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  110341. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  110342. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  110343. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  110344. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  110345. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  110346. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  110347. }
  110348. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  110349. };
  110350. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110351. var _this = this;
  110352. this._parent._startPerformanceCounter("Compile materials");
  110353. var promises = new Array();
  110354. if (this._gltf.materials) {
  110355. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110356. var material = _a[_i];
  110357. if (material._babylonData) {
  110358. for (var babylonDrawMode in material._babylonData) {
  110359. var babylonData = material._babylonData[babylonDrawMode];
  110360. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  110361. var babylonMesh = _c[_b];
  110362. // Ensure nonUniformScaling is set if necessary.
  110363. babylonMesh.computeWorldMatrix(true);
  110364. var babylonMaterial = babylonData.material;
  110365. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110366. if (this._parent.useClipPlane) {
  110367. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110368. }
  110369. }
  110370. }
  110371. }
  110372. }
  110373. }
  110374. return Promise.all(promises).then(function () {
  110375. _this._parent._endPerformanceCounter("Compile materials");
  110376. });
  110377. };
  110378. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110379. var _this = this;
  110380. this._parent._startPerformanceCounter("Compile shadow generators");
  110381. var promises = new Array();
  110382. var lights = this._babylonScene.lights;
  110383. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110384. var light = lights_1[_i];
  110385. var generator = light.getShadowGenerator();
  110386. if (generator) {
  110387. promises.push(generator.forceCompilationAsync());
  110388. }
  110389. }
  110390. return Promise.all(promises).then(function () {
  110391. _this._parent._endPerformanceCounter("Compile shadow generators");
  110392. });
  110393. };
  110394. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110395. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110396. var name_5 = _a[_i];
  110397. var extension = this._extensions[name_5];
  110398. if (extension.enabled) {
  110399. var promise = actionAsync(extension);
  110400. if (promise) {
  110401. return promise;
  110402. }
  110403. }
  110404. }
  110405. return null;
  110406. };
  110407. GLTFLoader._ExtensionNames = new Array();
  110408. GLTFLoader._ExtensionFactories = {};
  110409. return GLTFLoader;
  110410. }());
  110411. GLTF2.GLTFLoader = GLTFLoader;
  110412. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  110413. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110414. })(BABYLON || (BABYLON = {}));
  110415. //# sourceMappingURL=babylon.glTFLoader.js.map
  110416. var BABYLON;
  110417. (function (BABYLON) {
  110418. var GLTF2;
  110419. (function (GLTF2) {
  110420. /**
  110421. * Abstract class that can be implemented to extend existing glTF loader behavior.
  110422. */
  110423. var GLTFLoaderExtension = /** @class */ (function () {
  110424. /**
  110425. * Creates new GLTFLoaderExtension
  110426. * @param loader defines the GLTFLoader to use
  110427. */
  110428. function GLTFLoaderExtension(loader) {
  110429. /**
  110430. * Gets or sets a boolean indicating if the extension is enabled
  110431. */
  110432. this.enabled = true;
  110433. this._loader = loader;
  110434. }
  110435. /**
  110436. * Release all resources
  110437. */
  110438. GLTFLoaderExtension.prototype.dispose = function () {
  110439. delete this._loader;
  110440. };
  110441. // #region Overridable Methods
  110442. /**
  110443. * Override this method to modify the default behavior for loading scenes.
  110444. * @hidden
  110445. */
  110446. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110447. /**
  110448. * Override this method to modify the default behavior for loading nodes.
  110449. * @hidden
  110450. */
  110451. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110452. /**
  110453. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  110454. * @hidden
  110455. */
  110456. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110457. /**
  110458. * Override this method to modify the default behavior for loading materials.
  110459. * @hidden
  110460. */
  110461. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  110462. /**
  110463. * Override this method to modify the default behavior for loading material properties.
  110464. * @hidden
  110465. */
  110466. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  110467. /**
  110468. * Override this method to modify the default behavior for loading textures.
  110469. * @hidden
  110470. */
  110471. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  110472. /**
  110473. * Override this method to modify the default behavior for loading uris.
  110474. * @hidden
  110475. */
  110476. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110477. // #endregion
  110478. /**
  110479. * Helper method called by a loader extension to load an glTF extension.
  110480. * @hidden
  110481. */
  110482. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110483. if (!property.extensions) {
  110484. return null;
  110485. }
  110486. var extensions = property.extensions;
  110487. var extension = extensions[this.name];
  110488. if (!extension) {
  110489. return null;
  110490. }
  110491. // Clear out the extension before executing the action to avoid infinite recursion.
  110492. delete extensions[this.name];
  110493. try {
  110494. return actionAsync(context + "/extensions/" + this.name, extension);
  110495. }
  110496. finally {
  110497. // Restore the extension after executing the action.
  110498. extensions[this.name] = extension;
  110499. }
  110500. };
  110501. /**
  110502. * Helper method called by the loader to allow extensions to override loading scenes.
  110503. * @hidden
  110504. */
  110505. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  110506. if (!property.extras) {
  110507. return null;
  110508. }
  110509. var extras = property.extras;
  110510. var value = extras[this.name];
  110511. if (value === undefined) {
  110512. return null;
  110513. }
  110514. // Clear out the extras value before executing the action to avoid infinite recursion.
  110515. delete extras[this.name];
  110516. try {
  110517. return actionAsync(context + "/extras/" + this.name, value);
  110518. }
  110519. finally {
  110520. // Restore the extras value after executing the action.
  110521. extras[this.name] = value;
  110522. }
  110523. };
  110524. /**
  110525. * Helper method called by the loader to allow extensions to override loading scenes.
  110526. * @hidden
  110527. */
  110528. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110529. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110530. };
  110531. /**
  110532. * Helper method called by the loader to allow extensions to override loading nodes.
  110533. * @hidden
  110534. */
  110535. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110536. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110537. };
  110538. /**
  110539. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  110540. * @hidden
  110541. */
  110542. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110543. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110544. };
  110545. /**
  110546. * Helper method called by the loader to allow extensions to override loading materials.
  110547. * @hidden
  110548. */
  110549. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110550. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  110551. };
  110552. /**
  110553. * Helper method called by the loader to allow extensions to override loading material properties.
  110554. * @hidden
  110555. */
  110556. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  110557. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  110558. };
  110559. /**
  110560. * Helper method called by the loader to allow extensions to override loading textures.
  110561. * @hidden
  110562. */
  110563. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  110564. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  110565. };
  110566. /**
  110567. * Helper method called by the loader to allow extensions to override loading uris.
  110568. * @hidden
  110569. */
  110570. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110571. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110572. };
  110573. return GLTFLoaderExtension;
  110574. }());
  110575. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110576. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110577. })(BABYLON || (BABYLON = {}));
  110578. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110579. var BABYLON;
  110580. (function (BABYLON) {
  110581. var GLTF2;
  110582. (function (GLTF2) {
  110583. var Extensions;
  110584. (function (Extensions) {
  110585. var NAME = "MSFT_lod";
  110586. /**
  110587. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  110588. */
  110589. var MSFT_lod = /** @class */ (function (_super) {
  110590. __extends(MSFT_lod, _super);
  110591. function MSFT_lod(loader) {
  110592. var _this = _super.call(this, loader) || this;
  110593. _this.name = NAME;
  110594. /**
  110595. * Maximum number of LODs to load, starting from the lowest LOD.
  110596. */
  110597. _this.maxLODsToLoad = Number.MAX_VALUE;
  110598. /**
  110599. * Observable raised when all node LODs of one level are loaded.
  110600. * The event data is the index of the loaded LOD starting from zero.
  110601. * Dispose the loader to cancel the loading of the next level of LODs.
  110602. */
  110603. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  110604. /**
  110605. * Observable raised when all material LODs of one level are loaded.
  110606. * The event data is the index of the loaded LOD starting from zero.
  110607. * Dispose the loader to cancel the loading of the next level of LODs.
  110608. */
  110609. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  110610. _this._nodeIndexLOD = null;
  110611. _this._nodeSignalLODs = new Array();
  110612. _this._nodePromiseLODs = new Array();
  110613. _this._materialIndexLOD = null;
  110614. _this._materialSignalLODs = new Array();
  110615. _this._materialPromiseLODs = new Array();
  110616. _this._loader._readyPromise.then(function () {
  110617. var _loop_1 = function (indexLOD) {
  110618. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  110619. if (indexLOD !== 0) {
  110620. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  110621. }
  110622. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  110623. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  110624. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  110625. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  110626. _this._nodeSignalLODs[indexLOD].resolve();
  110627. }
  110628. });
  110629. _this._loader._completePromises.push(promise);
  110630. };
  110631. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  110632. _loop_1(indexLOD);
  110633. }
  110634. var _loop_2 = function (indexLOD) {
  110635. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  110636. if (indexLOD !== 0) {
  110637. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  110638. }
  110639. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  110640. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  110641. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  110642. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  110643. _this._materialSignalLODs[indexLOD].resolve();
  110644. }
  110645. });
  110646. _this._loader._completePromises.push(promise);
  110647. };
  110648. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  110649. _loop_2(indexLOD);
  110650. }
  110651. });
  110652. return _this;
  110653. }
  110654. MSFT_lod.prototype.dispose = function () {
  110655. _super.prototype.dispose.call(this);
  110656. this._nodeIndexLOD = null;
  110657. this._nodeSignalLODs.length = 0;
  110658. this._nodePromiseLODs.length = 0;
  110659. this._materialIndexLOD = null;
  110660. this._materialSignalLODs.length = 0;
  110661. this._materialPromiseLODs.length = 0;
  110662. this.onMaterialLODsLoadedObservable.clear();
  110663. this.onNodeLODsLoadedObservable.clear();
  110664. };
  110665. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110666. var _this = this;
  110667. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  110668. var firstPromise;
  110669. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  110670. _this._loader._parent._logOpen("" + extensionContext);
  110671. var _loop_3 = function (indexLOD) {
  110672. var nodeLOD = nodeLODs[indexLOD];
  110673. if (indexLOD !== 0) {
  110674. _this._nodeIndexLOD = indexLOD;
  110675. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  110676. }
  110677. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110678. if (indexLOD !== 0) {
  110679. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110680. if (previousNodeLOD._babylonMesh) {
  110681. previousNodeLOD._babylonMesh.dispose();
  110682. delete previousNodeLOD._babylonMesh;
  110683. _this._disposeUnusedMaterials();
  110684. }
  110685. }
  110686. });
  110687. if (indexLOD === 0) {
  110688. firstPromise = promise;
  110689. }
  110690. else {
  110691. _this._nodeIndexLOD = null;
  110692. }
  110693. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  110694. _this._nodePromiseLODs[indexLOD].push(promise);
  110695. };
  110696. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110697. _loop_3(indexLOD);
  110698. }
  110699. _this._loader._parent._logClose();
  110700. return firstPromise;
  110701. });
  110702. };
  110703. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110704. var _this = this;
  110705. // Don't load material LODs if already loading a node LOD.
  110706. if (this._nodeIndexLOD) {
  110707. return null;
  110708. }
  110709. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  110710. var firstPromise;
  110711. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  110712. _this._loader._parent._logOpen("" + extensionContext);
  110713. var _loop_4 = function (indexLOD) {
  110714. var materialLOD = materialLODs[indexLOD];
  110715. if (indexLOD !== 0) {
  110716. _this._materialIndexLOD = indexLOD;
  110717. }
  110718. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  110719. if (indexLOD !== 0) {
  110720. var babylonDataLOD = materialLOD._babylonData;
  110721. assign(babylonDataLOD[babylonDrawMode].material);
  110722. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  110723. if (previousBabylonDataLOD[babylonDrawMode]) {
  110724. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  110725. delete previousBabylonDataLOD[babylonDrawMode];
  110726. }
  110727. }
  110728. });
  110729. if (indexLOD === 0) {
  110730. firstPromise = promise;
  110731. }
  110732. else {
  110733. _this._materialIndexLOD = null;
  110734. }
  110735. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  110736. _this._materialPromiseLODs[indexLOD].push(promise);
  110737. };
  110738. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110739. _loop_4(indexLOD);
  110740. }
  110741. _this._loader._parent._logClose();
  110742. return firstPromise;
  110743. });
  110744. };
  110745. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110746. var _this = this;
  110747. // Defer the loading of uris if loading a material or node LOD.
  110748. if (this._materialIndexLOD !== null) {
  110749. this._loader._parent._log("deferred");
  110750. var previousIndexLOD = this._materialIndexLOD - 1;
  110751. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110752. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  110753. return _this._loader._loadUriAsync(context, uri);
  110754. });
  110755. }
  110756. else if (this._nodeIndexLOD !== null) {
  110757. this._loader._parent._log("deferred");
  110758. var previousIndexLOD = this._nodeIndexLOD - 1;
  110759. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110760. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  110761. return _this._loader._loadUriAsync(context, uri);
  110762. });
  110763. }
  110764. return null;
  110765. };
  110766. /**
  110767. * Gets an array of LOD properties from lowest to highest.
  110768. */
  110769. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110770. if (this.maxLODsToLoad <= 0) {
  110771. throw new Error("maxLODsToLoad must be greater than zero");
  110772. }
  110773. var properties = new Array();
  110774. for (var i = ids.length - 1; i >= 0; i--) {
  110775. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110776. if (properties.length === this.maxLODsToLoad) {
  110777. return properties;
  110778. }
  110779. }
  110780. properties.push(property);
  110781. return properties;
  110782. };
  110783. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  110784. var materials = this._loader._gltf.materials;
  110785. if (materials) {
  110786. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  110787. var material = materials_1[_i];
  110788. if (material._babylonData) {
  110789. for (var drawMode in material._babylonData) {
  110790. var babylonData = material._babylonData[drawMode];
  110791. if (babylonData.meshes.length === 0) {
  110792. babylonData.material.dispose(false, true);
  110793. delete material._babylonData[drawMode];
  110794. }
  110795. }
  110796. }
  110797. }
  110798. }
  110799. };
  110800. return MSFT_lod;
  110801. }(GLTF2.GLTFLoaderExtension));
  110802. Extensions.MSFT_lod = MSFT_lod;
  110803. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110804. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110805. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110806. })(BABYLON || (BABYLON = {}));
  110807. //# sourceMappingURL=MSFT_lod.js.map
  110808. var BABYLON;
  110809. (function (BABYLON) {
  110810. var GLTF2;
  110811. (function (GLTF2) {
  110812. var Extensions;
  110813. (function (Extensions) {
  110814. var NAME = "MSFT_minecraftMesh";
  110815. /** @hidden */
  110816. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  110817. __extends(MSFT_minecraftMesh, _super);
  110818. function MSFT_minecraftMesh() {
  110819. var _this = _super !== null && _super.apply(this, arguments) || this;
  110820. _this.name = NAME;
  110821. return _this;
  110822. }
  110823. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110824. var _this = this;
  110825. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  110826. if (value) {
  110827. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110828. if (babylonMaterial.needAlphaBlending()) {
  110829. babylonMaterial.forceDepthWrite = true;
  110830. babylonMaterial.separateCullingPass = true;
  110831. }
  110832. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  110833. babylonMaterial.twoSidedLighting = true;
  110834. assign(babylonMaterial);
  110835. });
  110836. }
  110837. return null;
  110838. });
  110839. };
  110840. return MSFT_minecraftMesh;
  110841. }(GLTF2.GLTFLoaderExtension));
  110842. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  110843. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  110844. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110845. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110846. })(BABYLON || (BABYLON = {}));
  110847. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  110848. var BABYLON;
  110849. (function (BABYLON) {
  110850. var GLTF2;
  110851. (function (GLTF2) {
  110852. var Extensions;
  110853. (function (Extensions) {
  110854. var NAME = "MSFT_sRGBFactors";
  110855. /** @hidden */
  110856. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  110857. __extends(MSFT_sRGBFactors, _super);
  110858. function MSFT_sRGBFactors() {
  110859. var _this = _super !== null && _super.apply(this, arguments) || this;
  110860. _this.name = NAME;
  110861. return _this;
  110862. }
  110863. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110864. var _this = this;
  110865. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  110866. if (value) {
  110867. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110868. if (!babylonMaterial.albedoTexture) {
  110869. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  110870. }
  110871. if (!babylonMaterial.reflectivityTexture) {
  110872. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  110873. }
  110874. assign(babylonMaterial);
  110875. });
  110876. }
  110877. return null;
  110878. });
  110879. };
  110880. return MSFT_sRGBFactors;
  110881. }(GLTF2.GLTFLoaderExtension));
  110882. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  110883. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  110884. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110885. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110886. })(BABYLON || (BABYLON = {}));
  110887. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  110888. var BABYLON;
  110889. (function (BABYLON) {
  110890. var GLTF2;
  110891. (function (GLTF2) {
  110892. var Extensions;
  110893. (function (Extensions) {
  110894. var NAME = "KHR_draco_mesh_compression";
  110895. /**
  110896. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  110897. */
  110898. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110899. __extends(KHR_draco_mesh_compression, _super);
  110900. function KHR_draco_mesh_compression(loader) {
  110901. var _this = _super.call(this, loader) || this;
  110902. _this.name = NAME;
  110903. _this._dracoCompression = null;
  110904. // Disable extension if decoder is not available.
  110905. if (!BABYLON.DracoCompression.DecoderAvailable) {
  110906. _this.enabled = false;
  110907. }
  110908. return _this;
  110909. }
  110910. KHR_draco_mesh_compression.prototype.dispose = function () {
  110911. if (this._dracoCompression) {
  110912. this._dracoCompression.dispose();
  110913. }
  110914. _super.prototype.dispose.call(this);
  110915. };
  110916. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110917. var _this = this;
  110918. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110919. if (primitive.mode != undefined) {
  110920. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110921. primitive.mode !== 4 /* TRIANGLES */) {
  110922. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110923. }
  110924. // TODO: handle triangle strips
  110925. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110926. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110927. }
  110928. }
  110929. var attributes = {};
  110930. var loadAttribute = function (name, kind) {
  110931. var uniqueId = extension.attributes[name];
  110932. if (uniqueId == undefined) {
  110933. return;
  110934. }
  110935. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110936. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110937. babylonMesh._delayInfo.push(kind);
  110938. }
  110939. attributes[kind] = uniqueId;
  110940. };
  110941. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110942. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110943. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110944. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110945. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110946. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110947. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110948. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110949. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110950. if (!bufferView._dracoBabylonGeometry) {
  110951. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110952. if (!_this._dracoCompression) {
  110953. _this._dracoCompression = new BABYLON.DracoCompression();
  110954. }
  110955. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  110956. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  110957. babylonVertexData.applyToGeometry(babylonGeometry);
  110958. return babylonGeometry;
  110959. }).catch(function (error) {
  110960. throw new Error(context + ": " + error.message);
  110961. });
  110962. });
  110963. }
  110964. return bufferView._dracoBabylonGeometry;
  110965. });
  110966. };
  110967. return KHR_draco_mesh_compression;
  110968. }(GLTF2.GLTFLoaderExtension));
  110969. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110970. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110971. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110972. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110973. })(BABYLON || (BABYLON = {}));
  110974. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110975. var BABYLON;
  110976. (function (BABYLON) {
  110977. var GLTF2;
  110978. (function (GLTF2) {
  110979. var Extensions;
  110980. (function (Extensions) {
  110981. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110982. /**
  110983. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  110984. */
  110985. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110986. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110987. function KHR_materials_pbrSpecularGlossiness() {
  110988. var _this = _super !== null && _super.apply(this, arguments) || this;
  110989. _this.name = NAME;
  110990. return _this;
  110991. }
  110992. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110993. var _this = this;
  110994. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  110995. var promises = new Array();
  110996. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110997. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  110998. return Promise.all(promises).then(function () { });
  110999. });
  111000. };
  111001. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  111002. var promises = new Array();
  111003. if (properties.diffuseFactor) {
  111004. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  111005. babylonMaterial.alpha = properties.diffuseFactor[3];
  111006. }
  111007. else {
  111008. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111009. }
  111010. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  111011. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  111012. if (properties.diffuseTexture) {
  111013. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  111014. babylonMaterial.albedoTexture = texture;
  111015. }));
  111016. }
  111017. if (properties.specularGlossinessTexture) {
  111018. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  111019. babylonMaterial.reflectivityTexture = texture;
  111020. }));
  111021. babylonMaterial.reflectivityTexture.hasAlpha = true;
  111022. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  111023. }
  111024. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111025. return Promise.all(promises).then(function () { });
  111026. };
  111027. return KHR_materials_pbrSpecularGlossiness;
  111028. }(GLTF2.GLTFLoaderExtension));
  111029. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  111030. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  111031. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111032. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111033. })(BABYLON || (BABYLON = {}));
  111034. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  111035. var BABYLON;
  111036. (function (BABYLON) {
  111037. var GLTF2;
  111038. (function (GLTF2) {
  111039. var Extensions;
  111040. (function (Extensions) {
  111041. var NAME = "KHR_materials_unlit";
  111042. /**
  111043. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  111044. */
  111045. var KHR_materials_unlit = /** @class */ (function (_super) {
  111046. __extends(KHR_materials_unlit, _super);
  111047. function KHR_materials_unlit() {
  111048. var _this = _super !== null && _super.apply(this, arguments) || this;
  111049. _this.name = NAME;
  111050. return _this;
  111051. }
  111052. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111053. var _this = this;
  111054. return this._loadExtensionAsync(context, material, function () {
  111055. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  111056. });
  111057. };
  111058. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  111059. var promises = new Array();
  111060. babylonMaterial.unlit = true;
  111061. // Ensure metallic workflow
  111062. babylonMaterial.metallic = 1;
  111063. babylonMaterial.roughness = 1;
  111064. var properties = material.pbrMetallicRoughness;
  111065. if (properties) {
  111066. if (properties.baseColorFactor) {
  111067. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  111068. babylonMaterial.alpha = properties.baseColorFactor[3];
  111069. }
  111070. else {
  111071. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111072. }
  111073. if (properties.baseColorTexture) {
  111074. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  111075. babylonMaterial.albedoTexture = texture;
  111076. }));
  111077. }
  111078. }
  111079. if (material.doubleSided) {
  111080. babylonMaterial.backFaceCulling = false;
  111081. babylonMaterial.twoSidedLighting = true;
  111082. }
  111083. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111084. return Promise.all(promises).then(function () { });
  111085. };
  111086. return KHR_materials_unlit;
  111087. }(GLTF2.GLTFLoaderExtension));
  111088. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  111089. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  111090. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111091. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111092. })(BABYLON || (BABYLON = {}));
  111093. //# sourceMappingURL=KHR_materials_unlit.js.map
  111094. var BABYLON;
  111095. (function (BABYLON) {
  111096. var GLTF2;
  111097. (function (GLTF2) {
  111098. var Extensions;
  111099. (function (Extensions) {
  111100. var NAME = "KHR_lights";
  111101. var LightType;
  111102. (function (LightType) {
  111103. LightType["AMBIENT"] = "ambient";
  111104. LightType["DIRECTIONAL"] = "directional";
  111105. LightType["POINT"] = "point";
  111106. LightType["SPOT"] = "spot";
  111107. })(LightType || (LightType = {}));
  111108. /**
  111109. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  111110. */
  111111. var KHR_lights = /** @class */ (function (_super) {
  111112. __extends(KHR_lights, _super);
  111113. function KHR_lights() {
  111114. var _this = _super !== null && _super.apply(this, arguments) || this;
  111115. _this.name = NAME;
  111116. return _this;
  111117. }
  111118. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  111119. var _this = this;
  111120. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  111121. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  111122. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  111123. if (light.type !== LightType.AMBIENT) {
  111124. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  111125. }
  111126. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  111127. return promise;
  111128. });
  111129. };
  111130. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  111131. var _this = this;
  111132. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  111133. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  111134. var babylonLight;
  111135. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  111136. var name = node._babylonMesh.name;
  111137. switch (light.type) {
  111138. case LightType.AMBIENT: {
  111139. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  111140. }
  111141. case LightType.DIRECTIONAL: {
  111142. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  111143. break;
  111144. }
  111145. case LightType.POINT: {
  111146. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  111147. break;
  111148. }
  111149. case LightType.SPOT: {
  111150. var spotLight = light;
  111151. // TODO: support inner and outer cone angles
  111152. //const innerConeAngle = spotLight.innerConeAngle || 0;
  111153. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  111154. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  111155. break;
  111156. }
  111157. default: {
  111158. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  111159. }
  111160. }
  111161. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  111162. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  111163. babylonLight.parent = node._babylonMesh;
  111164. return promise;
  111165. });
  111166. };
  111167. Object.defineProperty(KHR_lights.prototype, "_lights", {
  111168. get: function () {
  111169. var extensions = this._loader._gltf.extensions;
  111170. if (!extensions || !extensions[this.name]) {
  111171. throw new Error("#/extensions: '" + this.name + "' not found");
  111172. }
  111173. var extension = extensions[this.name];
  111174. return extension.lights;
  111175. },
  111176. enumerable: true,
  111177. configurable: true
  111178. });
  111179. return KHR_lights;
  111180. }(GLTF2.GLTFLoaderExtension));
  111181. Extensions.KHR_lights = KHR_lights;
  111182. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  111183. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111184. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111185. })(BABYLON || (BABYLON = {}));
  111186. var BABYLON;
  111187. (function (BABYLON) {
  111188. var GLTF2;
  111189. (function (GLTF2) {
  111190. var Extensions;
  111191. (function (Extensions) {
  111192. var NAME = "KHR_texture_transform";
  111193. /**
  111194. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  111195. */
  111196. var KHR_texture_transform = /** @class */ (function (_super) {
  111197. __extends(KHR_texture_transform, _super);
  111198. function KHR_texture_transform() {
  111199. var _this = _super !== null && _super.apply(this, arguments) || this;
  111200. _this.name = NAME;
  111201. return _this;
  111202. }
  111203. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  111204. var _this = this;
  111205. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  111206. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  111207. if (extension.offset) {
  111208. babylonTexture.uOffset = extension.offset[0];
  111209. babylonTexture.vOffset = extension.offset[1];
  111210. }
  111211. // Always rotate around the origin.
  111212. babylonTexture.uRotationCenter = 0;
  111213. babylonTexture.vRotationCenter = 0;
  111214. if (extension.rotation) {
  111215. babylonTexture.wAng = -extension.rotation;
  111216. }
  111217. if (extension.scale) {
  111218. babylonTexture.uScale = extension.scale[0];
  111219. babylonTexture.vScale = extension.scale[1];
  111220. }
  111221. if (extension.texCoord != undefined) {
  111222. babylonTexture.coordinatesIndex = extension.texCoord;
  111223. }
  111224. assign(babylonTexture);
  111225. });
  111226. });
  111227. };
  111228. return KHR_texture_transform;
  111229. }(GLTF2.GLTFLoaderExtension));
  111230. Extensions.KHR_texture_transform = KHR_texture_transform;
  111231. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  111232. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111233. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111234. })(BABYLON || (BABYLON = {}));
  111235. return BABYLON;
  111236. });
  111237. /***/ }),
  111238. /* 15 */
  111239. /***/ (function(module, exports, __webpack_require__) {
  111240. module.exports = __webpack_require__(16);
  111241. /***/ }),
  111242. /* 16 */
  111243. /***/ (function(module, exports, __webpack_require__) {
  111244. "use strict";
  111245. function __export(m) {
  111246. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  111247. }
  111248. Object.defineProperty(exports, "__esModule", { value: true });
  111249. var mappers_1 = __webpack_require__(3);
  111250. exports.mapperManager = mappers_1.mapperManager;
  111251. var globals_1 = __webpack_require__(4);
  111252. exports.viewerGlobals = globals_1.viewerGlobals;
  111253. var viewerManager_1 = __webpack_require__(7);
  111254. exports.viewerManager = viewerManager_1.viewerManager;
  111255. var defaultViewer_1 = __webpack_require__(8);
  111256. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  111257. var viewer_1 = __webpack_require__(9);
  111258. exports.AbstractViewer = viewer_1.AbstractViewer;
  111259. var telemetryManager_1 = __webpack_require__(6);
  111260. exports.telemetryManager = telemetryManager_1.telemetryManager;
  111261. var modelLoader_1 = __webpack_require__(13);
  111262. exports.ModelLoader = modelLoader_1.ModelLoader;
  111263. var viewerModel_1 = __webpack_require__(5);
  111264. exports.ViewerModel = viewerModel_1.ViewerModel;
  111265. exports.ModelState = viewerModel_1.ModelState;
  111266. /**
  111267. * BabylonJS Viewer
  111268. *
  111269. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  111270. */
  111271. var BABYLON = __webpack_require__(0);
  111272. exports.BABYLON = BABYLON;
  111273. // load needed modules.
  111274. __webpack_require__(14);
  111275. __webpack_require__(64);
  111276. var initializer_1 = __webpack_require__(65);
  111277. exports.InitTags = initializer_1.InitTags;
  111278. // promise polyfill, if needed!
  111279. BABYLON.PromisePolyfill.Apply();
  111280. initializer_1.initListeners();
  111281. //deprectaed, here for backwards compatibility
  111282. var disableInit = globals_1.viewerGlobals.disableInit;
  111283. exports.disableInit = disableInit;
  111284. /**
  111285. * Dispose all viewers currently registered
  111286. */
  111287. function disposeAll() {
  111288. viewerManager_1.viewerManager.dispose();
  111289. mappers_1.mapperManager.dispose();
  111290. telemetryManager_1.telemetryManager.dispose();
  111291. }
  111292. exports.disposeAll = disposeAll;
  111293. var Version = globals_1.viewerGlobals.version;
  111294. exports.Version = Version;
  111295. console.log("Babylon.js viewer (v" + Version + ")");
  111296. // export publicliy all configuration interfaces
  111297. __export(__webpack_require__(10));
  111298. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlI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ENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  111299. /***/ }),
  111300. /* 17 */
  111301. /***/ (function(module, exports) {
  111302. var g;
  111303. // This works in non-strict mode
  111304. g = (function() {
  111305. return this;
  111306. })();
  111307. try {
  111308. // This works if eval is allowed (see CSP)
  111309. g = g || Function("return this")() || (1,eval)("this");
  111310. } catch(e) {
  111311. // This works if the window reference is available
  111312. if(typeof window === "object")
  111313. g = window;
  111314. }
  111315. // g can still be undefined, but nothing to do about it...
  111316. // We return undefined, instead of nothing here, so it's
  111317. // easier to handle this case. if(!global) { ...}
  111318. module.exports = g;
  111319. /***/ }),
  111320. /* 18 */
  111321. /***/ (function(module, exports) {
  111322. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  111323. module.exports = CANNON;
  111324. /***/ }),
  111325. /* 19 */
  111326. /***/ (function(module, exports) {
  111327. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  111328. module.exports = OIMO;
  111329. /***/ }),
  111330. /* 20 */
  111331. /***/ (function(module, exports) {
  111332. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  111333. module.exports = earcut;
  111334. /***/ }),
  111335. /* 21 */
  111336. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  111337. "use strict";
  111338. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  111339. var isMergeableObject = function isMergeableObject(value) {
  111340. return isNonNullObject(value)
  111341. && !isSpecial(value)
  111342. };
  111343. function isNonNullObject(value) {
  111344. return !!value && typeof value === 'object'
  111345. }
  111346. function isSpecial(value) {
  111347. var stringValue = Object.prototype.toString.call(value);
  111348. return stringValue === '[object RegExp]'
  111349. || stringValue === '[object Date]'
  111350. || isReactElement(value)
  111351. }
  111352. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  111353. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  111354. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  111355. function isReactElement(value) {
  111356. return value.$$typeof === REACT_ELEMENT_TYPE
  111357. }
  111358. function emptyTarget(val) {
  111359. return Array.isArray(val) ? [] : {}
  111360. }
  111361. function cloneUnlessOtherwiseSpecified(value, options) {
  111362. return (options.clone !== false && options.isMergeableObject(value))
  111363. ? deepmerge(emptyTarget(value), value, options)
  111364. : value
  111365. }
  111366. function defaultArrayMerge(target, source, options) {
  111367. return target.concat(source).map(function(element) {
  111368. return cloneUnlessOtherwiseSpecified(element, options)
  111369. })
  111370. }
  111371. function mergeObject(target, source, options) {
  111372. var destination = {};
  111373. if (options.isMergeableObject(target)) {
  111374. Object.keys(target).forEach(function(key) {
  111375. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  111376. });
  111377. }
  111378. Object.keys(source).forEach(function(key) {
  111379. if (!options.isMergeableObject(source[key]) || !target[key]) {
  111380. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  111381. } else {
  111382. destination[key] = deepmerge(target[key], source[key], options);
  111383. }
  111384. });
  111385. return destination
  111386. }
  111387. function deepmerge(target, source, options) {
  111388. options = options || {};
  111389. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  111390. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  111391. var sourceIsArray = Array.isArray(source);
  111392. var targetIsArray = Array.isArray(target);
  111393. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  111394. if (!sourceAndTargetTypesMatch) {
  111395. return cloneUnlessOtherwiseSpecified(source, options)
  111396. } else if (sourceIsArray) {
  111397. return options.arrayMerge(target, source, options)
  111398. } else {
  111399. return mergeObject(target, source, options)
  111400. }
  111401. }
  111402. deepmerge.all = function deepmergeAll(array, options) {
  111403. if (!Array.isArray(array)) {
  111404. throw new Error('first argument should be an array')
  111405. }
  111406. return array.reduce(function(prev, next) {
  111407. return deepmerge(prev, next, options)
  111408. }, {})
  111409. };
  111410. var deepmerge_1 = deepmerge;
  111411. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  111412. /***/ }),
  111413. /* 22 */
  111414. /***/ (function(module, exports, __webpack_require__) {
  111415. "use strict";
  111416. Object.defineProperty(exports, "__esModule", { value: true });
  111417. var babylonjs_1 = __webpack_require__(0);
  111418. var configuration_1 = __webpack_require__(10);
  111419. var viewerModel_1 = __webpack_require__(5);
  111420. var helper_1 = __webpack_require__(1);
  111421. var viewerLabs_1 = __webpack_require__(24);
  111422. var _1 = __webpack_require__(26);
  111423. var SceneManager = /** @class */ (function () {
  111424. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  111425. var _this = this;
  111426. this._engine = _engine;
  111427. this._configurationContainer = _configurationContainer;
  111428. this._observablesManager = _observablesManager;
  111429. this._animationBlendingEnabled = true;
  111430. this._white = babylonjs_1.Color3.White();
  111431. this._forceShadowUpdate = false;
  111432. this._processShadows = true;
  111433. this._groundEnabled = true;
  111434. this._groundMirrorEnabled = true;
  111435. this._defaultRenderingPipelineEnabled = false;
  111436. this._globalConfiguration = {};
  111437. this._defaultRenderingPipelineShouldBuild = true;
  111438. // default from rendering pipeline
  111439. this._bloomEnabled = false;
  111440. // default from rendering pipeline
  111441. this._fxaaEnabled = false;
  111442. this._focusOnModel = function (model) {
  111443. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  111444. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  111445. var halfSizeVec = sizeVec.scale(0.5);
  111446. var center = boundingInfo.min.add(halfSizeVec);
  111447. _this.camera.setTarget(center);
  111448. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  111449. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  111450. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  111451. var sceneDiagonalLenght = sizeVec.length();
  111452. if (isFinite(sceneDiagonalLenght))
  111453. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  111454. if (_this._configurationContainer.configuration)
  111455. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  111456. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  111457. // casting ais safe, due to the constraints tested before
  111458. (<ShadowLight>light).setDirectionToTarget(center);
  111459. });*/
  111460. };
  111461. this._cameraBehaviorMapping = {};
  111462. this.models = [];
  111463. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  111464. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  111465. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  111466. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  111467. this.onSceneInitObservable = new babylonjs_1.Observable();
  111468. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  111469. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  111470. //this._viewer.onEngineInitObservable.add(() => {
  111471. this._handleHardwareLimitations();
  111472. //});
  111473. this.onSceneInitObservable.add(function (scene) {
  111474. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  111475. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  111476. var updateShadows = function () {
  111477. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  111478. var light = _a[_i];
  111479. var generator = light.getShadowGenerator();
  111480. if (generator) {
  111481. // Processing shadows if animates
  111482. var shadowMap = generator.getShadowMap();
  111483. if (shadowMap) {
  111484. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111485. }
  111486. }
  111487. }
  111488. };
  111489. scene.registerBeforeRender(function () {
  111490. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  111491. // make sure all models are loaded
  111492. updateShadows();
  111493. _this._forceShadowUpdate = false;
  111494. }
  111495. else if (!(_this.models.every(function (model) {
  111496. if (!model.shadowsRenderedAfterLoad) {
  111497. model.shadowsRenderedAfterLoad = true;
  111498. return false;
  111499. }
  111500. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  111501. }))) {
  111502. updateShadows();
  111503. }
  111504. });
  111505. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  111506. });
  111507. if (this._observablesManager) {
  111508. this._observablesManager.onModelLoadedObservable.add(function (model) {
  111509. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  111510. var light = _a[_i];
  111511. var generator = light.getShadowGenerator();
  111512. if (generator) {
  111513. // Processing shadows if animates
  111514. var shadowMap = generator.getShadowMap();
  111515. if (shadowMap) {
  111516. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111517. }
  111518. }
  111519. }
  111520. _this._focusOnModel(model);
  111521. });
  111522. this._observablesManager.onModelAddedObservable.add(function (model) {
  111523. _this.models.push(model);
  111524. });
  111525. this._observablesManager.onModelRemovedObservable.add(function (model) {
  111526. _this.models.splice(_this.models.indexOf(model), 1);
  111527. });
  111528. }
  111529. }
  111530. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  111531. get: function () {
  111532. return this._defaultRenderingPipeline;
  111533. },
  111534. enumerable: true,
  111535. configurable: true
  111536. });
  111537. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  111538. /**
  111539. * Returns a boolean representing HDR support
  111540. */
  111541. get: function () {
  111542. return this._hdrSupport;
  111543. },
  111544. enumerable: true,
  111545. configurable: true
  111546. });
  111547. Object.defineProperty(SceneManager.prototype, "mainColor", {
  111548. /**
  111549. * Return the main color defined in the configuration.
  111550. */
  111551. get: function () {
  111552. return this._configurationContainer.mainColor;
  111553. },
  111554. enumerable: true,
  111555. configurable: true
  111556. });
  111557. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  111558. get: function () {
  111559. return this._configurationContainer.reflectionColor;
  111560. },
  111561. enumerable: true,
  111562. configurable: true
  111563. });
  111564. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  111565. get: function () {
  111566. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  111567. },
  111568. set: function (value) {
  111569. this.scene.animationPropertiesOverride.enableBlending = value;
  111570. },
  111571. enumerable: true,
  111572. configurable: true
  111573. });
  111574. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  111575. get: function () {
  111576. return this._observablesManager;
  111577. },
  111578. enumerable: true,
  111579. configurable: true
  111580. });
  111581. Object.defineProperty(SceneManager.prototype, "processShadows", {
  111582. /**
  111583. * The flag defining whether shadows are rendered constantly or once.
  111584. */
  111585. get: function () {
  111586. return this._processShadows;
  111587. },
  111588. /**
  111589. * Should shadows be rendered every frame, or only once and stop.
  111590. * This can be used to optimize a scene.
  111591. *
  111592. * Not that the shadows will NOT disapear but will remain in place.
  111593. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  111594. */
  111595. set: function (process) {
  111596. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  111597. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  111598. var light = _a[_i];
  111599. var generator = light.getShadowGenerator();
  111600. if (generator) {
  111601. var shadowMap = generator.getShadowMap();
  111602. if (shadowMap) {
  111603. shadowMap.refreshRate = refreshType;
  111604. }
  111605. }
  111606. }
  111607. this._processShadows = process;
  111608. },
  111609. enumerable: true,
  111610. configurable: true
  111611. });
  111612. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  111613. get: function () {
  111614. return this._groundEnabled;
  111615. },
  111616. set: function (newValue) {
  111617. if (newValue === this._groundEnabled)
  111618. return;
  111619. this._groundEnabled = newValue;
  111620. if (this.environmentHelper && this.environmentHelper.ground) {
  111621. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  111622. }
  111623. },
  111624. enumerable: true,
  111625. configurable: true
  111626. });
  111627. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  111628. /**
  111629. * gets wether the reflection is disabled.
  111630. */
  111631. get: function () {
  111632. return this._groundMirrorEnabled;
  111633. },
  111634. /**
  111635. * sets wether the reflection is disabled.
  111636. */
  111637. set: function (value) {
  111638. if (this._groundMirrorEnabled === value) {
  111639. return;
  111640. }
  111641. this._groundMirrorEnabled = value;
  111642. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  111643. if (!value) {
  111644. this.environmentHelper.groundMaterial.reflectionTexture = null;
  111645. }
  111646. else {
  111647. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  111648. }
  111649. }
  111650. },
  111651. enumerable: true,
  111652. configurable: true
  111653. });
  111654. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  111655. get: function () {
  111656. return this._defaultRenderingPipelineEnabled;
  111657. },
  111658. set: function (value) {
  111659. if (value === this._defaultRenderingPipelineEnabled) {
  111660. return;
  111661. }
  111662. this._defaultRenderingPipelineEnabled = value;
  111663. this._rebuildPostprocesses();
  111664. if (this._defaultRenderingPipeline) {
  111665. this._defaultRenderingPipelineShouldBuild = false;
  111666. this._defaultRenderingPipeline.prepare();
  111667. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111668. }
  111669. },
  111670. enumerable: true,
  111671. configurable: true
  111672. });
  111673. /**
  111674. * Sets the engine flags to unlock all babylon features.
  111675. * Can also be configured using the scene.flags configuration object
  111676. */
  111677. SceneManager.prototype.unlockBabylonFeatures = function () {
  111678. this.scene.shadowsEnabled = true;
  111679. this.scene.particlesEnabled = true;
  111680. this.scene.postProcessesEnabled = true;
  111681. this.scene.collisionsEnabled = true;
  111682. this.scene.lightsEnabled = true;
  111683. this.scene.texturesEnabled = true;
  111684. this.scene.lensFlaresEnabled = true;
  111685. this.scene.proceduralTexturesEnabled = true;
  111686. this.scene.renderTargetsEnabled = true;
  111687. this.scene.spritesEnabled = true;
  111688. this.scene.skeletonsEnabled = true;
  111689. this.scene.audioEnabled = true;
  111690. };
  111691. /**
  111692. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  111693. */
  111694. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  111695. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  111696. // if the scen exists, dispose it.
  111697. if (this.scene) {
  111698. this.scene.dispose();
  111699. }
  111700. // create a new scene
  111701. this.scene = new babylonjs_1.Scene(this._engine);
  111702. this._configurationContainer.scene = this.scene;
  111703. // set a default PBR material
  111704. if (!sceneConfiguration.defaultMaterial) {
  111705. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  111706. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  111707. defaultMaterial.microSurface = 0.6;
  111708. if (this.scene.defaultMaterial) {
  111709. this.scene.defaultMaterial.dispose();
  111710. }
  111711. this.scene.defaultMaterial = defaultMaterial;
  111712. }
  111713. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  111714. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  111715. /*if (sceneConfiguration.glow) {
  111716. let options: Partial<IGlowLayerOptions> = {
  111717. mainTextureFixedSize: 512
  111718. };
  111719. if (typeof sceneConfiguration.glow === 'object') {
  111720. options = sceneConfiguration.glow
  111721. }
  111722. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  111723. }*/
  111724. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  111725. };
  111726. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  111727. if (clearModels === void 0) { clearModels = true; }
  111728. if (clearLights === void 0) { clearLights = false; }
  111729. if (clearModels) {
  111730. this.models.forEach(function (m) { return m.dispose(); });
  111731. this.models.length = 0;
  111732. }
  111733. if (clearLights) {
  111734. this.scene.lights.forEach(function (l) { return l.dispose(); });
  111735. }
  111736. };
  111737. /**
  111738. * This will update the scene's configuration, including camera, lights, environment.
  111739. * @param newConfiguration the delta that should be configured. This includes only the changes
  111740. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  111741. */
  111742. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  111743. var _this = this;
  111744. if (this._configurationContainer) {
  111745. this._globalConfiguration = this._configurationContainer.configuration;
  111746. }
  111747. else {
  111748. this._globalConfiguration = newConfiguration;
  111749. }
  111750. if (newConfiguration.lab) {
  111751. if (newConfiguration.lab.assetsRootURL) {
  111752. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  111753. }
  111754. }
  111755. // update scene configuration
  111756. if (newConfiguration.scene) {
  111757. this._configureScene(newConfiguration.scene);
  111758. }
  111759. // optimizer
  111760. if (newConfiguration.optimizer !== undefined) {
  111761. this._configureOptimizer(newConfiguration.optimizer);
  111762. }
  111763. // configure model
  111764. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  111765. this._configureModel(newConfiguration.model);
  111766. }*/
  111767. // lights
  111768. this._configureLights(newConfiguration.lights);
  111769. // environment
  111770. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  111771. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  111772. }
  111773. // camera
  111774. this._configureCamera(newConfiguration.camera);
  111775. if (newConfiguration.lab) {
  111776. if (newConfiguration.lab.environmentMap) {
  111777. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  111778. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  111779. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  111780. });
  111781. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  111782. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  111783. }
  111784. }
  111785. // rendering piplines
  111786. if (newConfiguration.lab.defaultRenderingPipelines) {
  111787. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  111788. if (typeof pipelineConfig === 'boolean') {
  111789. this.defaultRenderingPipelineEnabled = pipelineConfig;
  111790. }
  111791. else {
  111792. this.defaultRenderingPipelineEnabled = true;
  111793. }
  111794. }
  111795. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  111796. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  111797. this.environmentHelper.setMainColor(mainColor);
  111798. }
  111799. if (newConfiguration.lab.globalLightRotation !== undefined) {
  111800. // rotate all lights that are shadow lights
  111801. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  111802. // casting and '!' are safe, due to the constraints tested before
  111803. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  111804. });
  111805. this._forceShadowUpdate = true;
  111806. }
  111807. }
  111808. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  111809. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  111810. }
  111811. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  111812. this._defaultRenderingPipelineShouldBuild = false;
  111813. this._defaultRenderingPipeline.prepare();
  111814. }
  111815. };
  111816. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  111817. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  111818. if (this._defaultRenderingPipeline) {
  111819. this._defaultRenderingPipeline.dispose();
  111820. this._defaultRenderingPipeline = null;
  111821. this.scene.autoClearDepthAndStencil = true;
  111822. this.scene.autoClear = true;
  111823. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  111824. }
  111825. return;
  111826. }
  111827. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  111828. if (pipelineConfig) {
  111829. if (!this._defaultRenderingPipeline) {
  111830. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  111831. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  111832. }
  111833. this.scene.autoClear = false;
  111834. this.scene.autoClearDepthAndStencil = false;
  111835. this._defaultRenderingPipelineShouldBuild = true;
  111836. var bloomEnabled = this._bloomEnabled;
  111837. if (typeof pipelineConfig !== 'boolean') {
  111838. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  111839. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  111840. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  111841. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  111842. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  111843. }
  111844. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  111845. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  111846. }
  111847. };
  111848. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  111849. get: function () {
  111850. return this._bloomEnabled;
  111851. },
  111852. set: function (value) {
  111853. if (this._bloomEnabled === value) {
  111854. return;
  111855. }
  111856. this._bloomEnabled = value;
  111857. this._rebuildPostprocesses();
  111858. if (this._defaultRenderingPipeline) {
  111859. this._defaultRenderingPipelineShouldBuild = false;
  111860. this._defaultRenderingPipeline.prepare();
  111861. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111862. }
  111863. },
  111864. enumerable: true,
  111865. configurable: true
  111866. });
  111867. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  111868. get: function () {
  111869. return this._fxaaEnabled;
  111870. },
  111871. set: function (value) {
  111872. if (this._fxaaEnabled === value) {
  111873. return;
  111874. }
  111875. this._fxaaEnabled = value;
  111876. this._rebuildPostprocesses();
  111877. if (this._defaultRenderingPipeline) {
  111878. this._defaultRenderingPipelineShouldBuild = false;
  111879. this._defaultRenderingPipeline.prepare();
  111880. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111881. }
  111882. },
  111883. enumerable: true,
  111884. configurable: true
  111885. });
  111886. /**
  111887. * internally configure the scene using the provided configuration.
  111888. * The scene will not be recreated, but just updated.
  111889. * @param sceneConfig the (new) scene configuration
  111890. */
  111891. SceneManager.prototype._configureScene = function (sceneConfig) {
  111892. // sanity check!
  111893. if (!this.scene) {
  111894. return;
  111895. }
  111896. var cc = sceneConfig.clearColor;
  111897. var oldcc = this.scene.clearColor;
  111898. if (cc) {
  111899. if (cc.r !== undefined) {
  111900. oldcc.r = cc.r;
  111901. }
  111902. if (cc.g !== undefined) {
  111903. oldcc.g = cc.g;
  111904. }
  111905. if (cc.b !== undefined) {
  111906. oldcc.b = cc.b;
  111907. }
  111908. if (cc.a !== undefined) {
  111909. oldcc.a = cc.a;
  111910. }
  111911. }
  111912. // image processing configuration - optional.
  111913. if (sceneConfig.imageProcessingConfiguration) {
  111914. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  111915. }
  111916. //animation properties override
  111917. if (sceneConfig.animationPropertiesOverride) {
  111918. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  111919. }
  111920. if (sceneConfig.environmentTexture) {
  111921. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  111922. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  111923. this.scene.environmentTexture.dispose();
  111924. }
  111925. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  111926. this.scene.environmentTexture = environmentTexture;
  111927. }
  111928. }
  111929. if (sceneConfig.debug === true) {
  111930. this.scene.debugLayer.show();
  111931. }
  111932. else if (sceneConfig.debug === false) {
  111933. if (this.scene.debugLayer.isVisible()) {
  111934. this.scene.debugLayer.hide();
  111935. }
  111936. }
  111937. if (sceneConfig.disableHdr) {
  111938. this._handleHardwareLimitations(false);
  111939. }
  111940. else {
  111941. this._handleHardwareLimitations(true);
  111942. }
  111943. if (sceneConfig.renderInBackground !== undefined) {
  111944. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  111945. }
  111946. var canvas = this._engine.getRenderingCanvas();
  111947. if (canvas) {
  111948. if (this.camera && sceneConfig.disableCameraControl) {
  111949. this.camera.detachControl(canvas);
  111950. }
  111951. else if (this.camera && sceneConfig.disableCameraControl === false) {
  111952. this.camera.attachControl(canvas);
  111953. }
  111954. }
  111955. // process mainColor changes:
  111956. if (sceneConfig.mainColor) {
  111957. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  111958. var mc = sceneConfig.mainColor;
  111959. if (mc.r !== undefined) {
  111960. this.mainColor.r = mc.r;
  111961. }
  111962. if (mc.g !== undefined) {
  111963. this.mainColor.g = mc.g;
  111964. }
  111965. if (mc.b !== undefined) {
  111966. this.mainColor.b = mc.b;
  111967. }
  111968. this.reflectionColor.copyFrom(this.mainColor);
  111969. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  111970. // reflection color
  111971. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  111972. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  111973. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  111974. this.reflectionColor.copyFrom(tmpColor3);
  111975. //update the environment, if exists
  111976. if (this.environmentHelper) {
  111977. if (this.environmentHelper.groundMaterial) {
  111978. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  111979. }
  111980. if (this.environmentHelper.skyboxMaterial) {
  111981. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  111982. }
  111983. }
  111984. }
  111985. if (sceneConfig.defaultMaterial) {
  111986. var conf = sceneConfig.defaultMaterial;
  111987. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  111988. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  111989. this.scene.defaultMaterial.dispose();
  111990. if (conf.materialType === 'standard') {
  111991. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  111992. }
  111993. else {
  111994. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  111995. }
  111996. }
  111997. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  111998. }
  111999. if (sceneConfig.flags) {
  112000. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  112001. }
  112002. this.onSceneConfiguredObservable.notifyObservers({
  112003. sceneManager: this,
  112004. object: this.scene,
  112005. newConfiguration: sceneConfig
  112006. });
  112007. };
  112008. /**
  112009. * Configure the scene optimizer.
  112010. * The existing scene optimizer will be disposed and a new one will be created.
  112011. * @param optimizerConfig the (new) optimizer configuration
  112012. */
  112013. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  112014. var _this = this;
  112015. if (typeof optimizerConfig === 'boolean') {
  112016. if (this.sceneOptimizer) {
  112017. this.sceneOptimizer.stop();
  112018. this.sceneOptimizer.dispose();
  112019. delete this.sceneOptimizer;
  112020. }
  112021. if (optimizerConfig) {
  112022. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  112023. this.sceneOptimizer.start();
  112024. }
  112025. }
  112026. else {
  112027. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  112028. // check for degradation
  112029. if (optimizerConfig.degradation) {
  112030. switch (optimizerConfig.degradation) {
  112031. case "low":
  112032. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  112033. break;
  112034. case "moderate":
  112035. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  112036. break;
  112037. case "hight":
  112038. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  112039. break;
  112040. }
  112041. }
  112042. if (this.sceneOptimizer) {
  112043. this.sceneOptimizer.stop();
  112044. this.sceneOptimizer.dispose();
  112045. }
  112046. if (optimizerConfig.custom) {
  112047. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  112048. if (customOptimizer_1) {
  112049. optimizerOptions.addCustomOptimization(function () {
  112050. return customOptimizer_1(_this);
  112051. }, function () {
  112052. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  112053. });
  112054. }
  112055. }
  112056. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  112057. this.sceneOptimizer.start();
  112058. }
  112059. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  112060. sceneManager: this,
  112061. object: this.sceneOptimizer,
  112062. newConfiguration: optimizerConfig
  112063. });
  112064. };
  112065. /**
  112066. * configure all models using the configuration.
  112067. * @param modelConfiguration the configuration to use to reconfigure the models
  112068. */
  112069. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  112070. this.models.forEach(model => {
  112071. model.updateConfiguration(modelConfiguration);
  112072. });
  112073. this.onModelsConfiguredObservable.notifyObservers({
  112074. sceneManager: this,
  112075. object: this.models,
  112076. newConfiguration: modelConfiguration
  112077. });
  112078. }*/
  112079. /**
  112080. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  112081. * @param cameraConfig the new camera configuration
  112082. * @param model optionally use the model to configure the camera.
  112083. */
  112084. SceneManager.prototype._configureCamera = function (cameraConfig) {
  112085. var _this = this;
  112086. if (cameraConfig === void 0) { cameraConfig = {}; }
  112087. if (!this.scene.activeCamera) {
  112088. var attachControl = true;
  112089. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  112090. attachControl = false;
  112091. }
  112092. this.scene.createDefaultCamera(true, true, attachControl);
  112093. this.camera = this.scene.activeCamera;
  112094. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  112095. }
  112096. if (cameraConfig.position) {
  112097. var newPosition = this.camera.position.clone();
  112098. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  112099. this.camera.setPosition(newPosition);
  112100. }
  112101. if (cameraConfig.target) {
  112102. var newTarget = this.camera.target.clone();
  112103. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  112104. this.camera.setTarget(newTarget);
  112105. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  112106. this._focusOnModel(this.models[0]);
  112107. }*/
  112108. if (cameraConfig.rotation) {
  112109. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  112110. }
  112111. if (cameraConfig.behaviors) {
  112112. for (var name_1 in cameraConfig.behaviors) {
  112113. if (cameraConfig.behaviors[name_1] !== undefined) {
  112114. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  112115. }
  112116. }
  112117. }
  112118. ;
  112119. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  112120. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  112121. });
  112122. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  112123. var sceneDiagonalLenght = sceneDiagonal.length();
  112124. if (isFinite(sceneDiagonalLenght))
  112125. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  112126. // sanity check!
  112127. if (this.scene.imageProcessingConfiguration) {
  112128. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  112129. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  112130. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  112131. }
  112132. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  112133. this.onCameraConfiguredObservable.notifyObservers({
  112134. sceneManager: this,
  112135. object: this.camera,
  112136. newConfiguration: cameraConfig
  112137. });
  112138. };
  112139. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  112140. var _this = this;
  112141. if (!skyboxConifguration && !groundConfiguration) {
  112142. if (this.environmentHelper) {
  112143. this.environmentHelper.dispose();
  112144. this.environmentHelper = undefined;
  112145. }
  112146. ;
  112147. }
  112148. else {
  112149. var options = {
  112150. createGround: !!groundConfiguration && this._groundEnabled,
  112151. createSkybox: !!skyboxConifguration,
  112152. setupImageProcessing: false,
  112153. };
  112154. // will that cause problems with model ground configuration?
  112155. /*if (model) {
  112156. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  112157. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  112158. const halfSizeVec = sizeVec.scale(0.5);
  112159. const center = boundingInfo.min.add(halfSizeVec);
  112160. options.groundYBias = -center.y;
  112161. }*/
  112162. if (groundConfiguration) {
  112163. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  112164. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  112165. if (groundSize) {
  112166. options.groundSize = groundSize;
  112167. }
  112168. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  112169. if (groundConfig_1.shadowLevel !== undefined) {
  112170. options.groundShadowLevel = groundConfig_1.shadowLevel;
  112171. }
  112172. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  112173. if (groundConfig_1.texture) {
  112174. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  112175. }
  112176. if (groundConfig_1.color) {
  112177. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  112178. }
  112179. if (groundConfig_1.opacity !== undefined) {
  112180. options.groundOpacity = groundConfig_1.opacity;
  112181. }
  112182. if (groundConfig_1.mirror) {
  112183. options.enableGroundMirror = true;
  112184. // to prevent undefines
  112185. if (typeof groundConfig_1.mirror === "object") {
  112186. if (groundConfig_1.mirror.amount !== undefined)
  112187. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  112188. if (groundConfig_1.mirror.sizeRatio !== undefined)
  112189. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  112190. if (groundConfig_1.mirror.blurKernel !== undefined)
  112191. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  112192. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  112193. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  112194. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  112195. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  112196. if (this._defaultPipelineTextureType !== undefined)
  112197. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  112198. }
  112199. }
  112200. }
  112201. var postInitSkyboxMaterial = false;
  112202. if (skyboxConifguration) {
  112203. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  112204. if (conf.material && conf.material.imageProcessingConfiguration) {
  112205. options.setupImageProcessing = false; // will be configured later manually.
  112206. }
  112207. var skyboxSize = conf.scale;
  112208. if (skyboxSize) {
  112209. options.skyboxSize = skyboxSize;
  112210. }
  112211. options.sizeAuto = !options.skyboxSize;
  112212. if (conf.color) {
  112213. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  112214. }
  112215. if (conf.cubeTexture && conf.cubeTexture.url) {
  112216. if (typeof conf.cubeTexture.url === "string") {
  112217. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  112218. }
  112219. else {
  112220. // init later!
  112221. postInitSkyboxMaterial = true;
  112222. }
  112223. }
  112224. if (conf.material) {
  112225. postInitSkyboxMaterial = true;
  112226. }
  112227. }
  112228. options.setupImageProcessing = false; // TMP
  112229. if (!this.environmentHelper) {
  112230. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  112231. }
  112232. else {
  112233. // unlikely, but there might be a new scene! we need to dispose.
  112234. // get the scene used by the envHelper
  112235. var scene = this.environmentHelper.rootMesh.getScene();
  112236. // is it a different scene? Oh no!
  112237. if (scene !== this.scene) {
  112238. this.environmentHelper.dispose();
  112239. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  112240. }
  112241. else {
  112242. // recreate the ground
  112243. if (this.environmentHelper.ground) {
  112244. this.environmentHelper.ground.dispose();
  112245. }
  112246. // recreate the skybox
  112247. if (this.environmentHelper.skybox) {
  112248. this.environmentHelper.skybox.dispose();
  112249. }
  112250. this.environmentHelper.updateOptions(options);
  112251. // update doesn't change the size of the skybox and ground, so we have to recreate!
  112252. //this.environmentHelper.dispose();
  112253. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  112254. }
  112255. }
  112256. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  112257. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  112258. }
  112259. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  112260. if (this.environmentHelper.groundMaterial && groundConfig) {
  112261. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  112262. if (groundConfig.material) {
  112263. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  112264. }
  112265. if (this.environmentHelper.groundMirror) {
  112266. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  112267. // TODO user camera exposure value to set the mirror clear color
  112268. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  112269. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  112270. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  112271. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  112272. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  112273. this.environmentHelper.groundMirror.clearColor.a = 1;
  112274. if (!this.groundMirrorEnabled) {
  112275. this.environmentHelper.groundMaterial.reflectionTexture = null;
  112276. }
  112277. }
  112278. }
  112279. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  112280. if (skyboxMaterial) {
  112281. skyboxMaterial._perceptualColor = this.mainColor;
  112282. if (postInitSkyboxMaterial) {
  112283. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  112284. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  112285. }
  112286. }
  112287. }
  112288. }
  112289. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  112290. _this._updateGroundMirrorRenderList(model);
  112291. });
  112292. this.onEnvironmentConfiguredObservable.notifyObservers({
  112293. sceneManager: this,
  112294. object: this.environmentHelper,
  112295. newConfiguration: {
  112296. skybox: skyboxConifguration,
  112297. ground: groundConfiguration
  112298. }
  112299. });
  112300. };
  112301. /**
  112302. * configure the lights.
  112303. *
  112304. * @param lightsConfiguration the (new) light(s) configuration
  112305. * @param model optionally use the model to configure the camera.
  112306. */
  112307. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  112308. var _this = this;
  112309. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  112310. // sanity check!
  112311. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  112312. if (!lightKeys.length) {
  112313. if (!this.scene.lights.length)
  112314. this.scene.createDefaultLight(true);
  112315. }
  112316. else {
  112317. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  112318. // compare to the global (!) configuration object and dispose unneeded:
  112319. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  112320. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  112321. lightsAvailable_1.forEach(function (lName) {
  112322. if (lightsToConfigure_1.indexOf(lName) === -1) {
  112323. _this.scene.getLightByName(lName).dispose();
  112324. }
  112325. });
  112326. }
  112327. lightKeys.forEach(function (name, idx) {
  112328. var lightConfig = { type: 0 };
  112329. if (typeof lightsConfiguration[name] === 'object') {
  112330. lightConfig = lightsConfiguration[name];
  112331. }
  112332. if (typeof lightsConfiguration[name] === 'number') {
  112333. lightConfig.type = lightsConfiguration[name];
  112334. }
  112335. lightConfig.name = name;
  112336. var light;
  112337. // light is not already available
  112338. if (lightsAvailable_1.indexOf(name) === -1) {
  112339. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  112340. if (!constructor)
  112341. return;
  112342. light = constructor();
  112343. }
  112344. else {
  112345. // available? get it from the scene
  112346. light = _this.scene.getLightByName(name);
  112347. if (typeof lightsConfiguration[name] === 'boolean') {
  112348. lightConfig.type = light.getTypeID();
  112349. }
  112350. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  112351. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  112352. light.dispose();
  112353. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  112354. if (!constructor)
  112355. return;
  112356. light = constructor();
  112357. }
  112358. }
  112359. // if config set the light to false, dispose it.
  112360. if (lightsConfiguration[name] === false) {
  112361. light.dispose();
  112362. return;
  112363. }
  112364. //enabled
  112365. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  112366. light.setEnabled(enabled);
  112367. helper_1.extendClassWithConfig(light, lightConfig);
  112368. //position. Some lights don't support shadows
  112369. if (light instanceof babylonjs_1.ShadowLight) {
  112370. // set default values
  112371. light.shadowMinZ = light.shadowMinZ || 0.2;
  112372. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  112373. if (lightConfig.target) {
  112374. if (light.setDirectionToTarget) {
  112375. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  112376. light.setDirectionToTarget(target);
  112377. }
  112378. }
  112379. else if (lightConfig.direction) {
  112380. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  112381. light.direction = direction;
  112382. }
  112383. var isShadowEnabled = false;
  112384. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  112385. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  112386. isShadowEnabled = true;
  112387. }
  112388. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  112389. var spotLight = light;
  112390. if (lightConfig.spotAngle !== undefined) {
  112391. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  112392. }
  112393. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  112394. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  112395. }
  112396. isShadowEnabled = true;
  112397. }
  112398. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  112399. if (lightConfig.shadowFieldOfView) {
  112400. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  112401. }
  112402. isShadowEnabled = true;
  112403. }
  112404. var shadowGenerator_1 = light.getShadowGenerator();
  112405. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  112406. var bufferSize = lightConfig.shadowBufferSize || 256;
  112407. if (!shadowGenerator_1) {
  112408. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  112409. }
  112410. var blurKernel = _this.getBlurKernel(light, bufferSize);
  112411. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  112412. shadowGenerator_1.blurKernel = blurKernel;
  112413. //override defaults
  112414. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  112415. // add the focues meshes to the shadow list
  112416. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  112417. _this._updateShadowRenderList(shadowGenerator_1, model);
  112418. });
  112419. //if (model) {
  112420. _this._updateShadowRenderList(shadowGenerator_1);
  112421. //}
  112422. }
  112423. else if (shadowGenerator_1) {
  112424. shadowGenerator_1.dispose();
  112425. }
  112426. }
  112427. });
  112428. // render priority
  112429. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  112430. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  112431. var configuration = globalLightsConfiguration_1[name];
  112432. var light = _this.scene.getLightByName(name);
  112433. // sanity check
  112434. if (!light)
  112435. return;
  112436. light.renderPriority = -idx;
  112437. });
  112438. }
  112439. this.onLightsConfiguredObservable.notifyObservers({
  112440. sceneManager: this,
  112441. object: this.scene.lights,
  112442. newConfiguration: lightsConfiguration
  112443. });
  112444. };
  112445. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  112446. var focusMeshes = model ? model.meshes : this.scene.meshes;
  112447. // add the focues meshes to the shadow list
  112448. var shadownMap = shadowGenerator.getShadowMap();
  112449. if (!shadownMap)
  112450. return;
  112451. if (resetList && shadownMap.renderList) {
  112452. shadownMap.renderList.length = 0;
  112453. }
  112454. else {
  112455. shadownMap.renderList = shadownMap.renderList || [];
  112456. }
  112457. for (var index = 0; index < focusMeshes.length; index++) {
  112458. var mesh = focusMeshes[index];
  112459. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  112460. shadownMap.renderList.push(mesh);
  112461. }
  112462. }
  112463. if (!this._shadowGroundPlane) {
  112464. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  112465. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  112466. shadowGroundPlane.useVertexColors = false;
  112467. //material isn't ever used in rendering, just used to set back face culling
  112468. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  112469. shadowGroundPlane.material.backFaceCulling = false;
  112470. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  112471. shadowGroundPlane.freezeWorldMatrix();
  112472. this._shadowGroundPlane = shadowGroundPlane;
  112473. this.scene.removeMesh(shadowGroundPlane);
  112474. }
  112475. }
  112476. else {
  112477. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  112478. this._shadowGroundPlane.dispose();
  112479. this._shadowGroundPlane = null;
  112480. }
  112481. }
  112482. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  112483. shadownMap.renderList.push(this._shadowGroundPlane);
  112484. }
  112485. };
  112486. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  112487. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  112488. var focusMeshes = model ? model.meshes : this.scene.meshes;
  112489. var renderList = this.environmentHelper.groundMirror.renderList;
  112490. if (resetList) {
  112491. renderList.length = 0;
  112492. }
  112493. for (var index = 0; index < focusMeshes.length; index++) {
  112494. var mesh = focusMeshes[index];
  112495. if (renderList.indexOf(mesh) === -1) {
  112496. renderList.push(mesh);
  112497. }
  112498. }
  112499. }
  112500. };
  112501. /**
  112502. * Gets the shadow map blur kernel according to the light configuration.
  112503. * @param light The light used to generate the shadows
  112504. * @param bufferSize The size of the shadow map
  112505. * @return the kernel blur size
  112506. */
  112507. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  112508. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  112509. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  112510. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  112511. }
  112512. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  112513. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  112514. }
  112515. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  112516. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  112517. }
  112518. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  112519. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  112520. return blurKernel;
  112521. };
  112522. /**
  112523. * Alters render settings to reduce features based on hardware feature limitations
  112524. * @param enableHDR Allows the viewer to run in HDR mode.
  112525. */
  112526. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  112527. if (enableHDR === void 0) { enableHDR = true; }
  112528. //flip rendering settings switches based on hardware support
  112529. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  112530. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  112531. //shadows are disabled if there's not enough varyings for a single shadow
  112532. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  112533. this._maxShadows = 0;
  112534. }
  112535. else {
  112536. this._maxShadows = 3;
  112537. }
  112538. //can we render to any >= 16-bit targets (required for HDR)
  112539. var caps = this._engine.getCaps();
  112540. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  112541. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  112542. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  112543. if (linearHalfFloatTargets) {
  112544. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  112545. this._shadowGeneratorBias = 0.002;
  112546. }
  112547. else if (linearFloatTargets) {
  112548. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  112549. this._shadowGeneratorBias = 0.001;
  112550. }
  112551. else {
  112552. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  112553. this._shadowGeneratorBias = 0.001;
  112554. }
  112555. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  112556. };
  112557. /**
  112558. * Dispoe the entire viewer including the scene and the engine
  112559. */
  112560. SceneManager.prototype.dispose = function () {
  112561. // this.onCameraConfiguredObservable.clear();
  112562. this.onEnvironmentConfiguredObservable.clear();
  112563. this.onLightsConfiguredObservable.clear();
  112564. this.onModelsConfiguredObservable.clear();
  112565. this.onSceneConfiguredObservable.clear();
  112566. this.onSceneInitObservable.clear();
  112567. this.onSceneOptimizerConfiguredObservable.clear();
  112568. if (this.sceneOptimizer) {
  112569. this.sceneOptimizer.stop();
  112570. this.sceneOptimizer.dispose();
  112571. }
  112572. if (this.environmentHelper) {
  112573. this.environmentHelper.dispose();
  112574. }
  112575. this.models.forEach(function (model) {
  112576. model.dispose();
  112577. });
  112578. if (this._defaultRenderingPipeline) {
  112579. this._defaultRenderingPipeline.dispose();
  112580. }
  112581. this.models.length = 0;
  112582. if (this.scene) {
  112583. this.scene.dispose();
  112584. }
  112585. };
  112586. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  112587. var behavior;
  112588. var type;
  112589. if (typeof behaviorConfig === 'object') {
  112590. type = behaviorConfig.type;
  112591. }
  112592. else if (typeof behaviorConfig === 'number') {
  112593. type = behaviorConfig;
  112594. }
  112595. else {
  112596. type = this._cameraBehaviorMapping[name];
  112597. }
  112598. if (type === undefined)
  112599. return;
  112600. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  112601. var enabled = true;
  112602. if (typeof behaviorConfig === 'boolean') {
  112603. enabled = behaviorConfig;
  112604. }
  112605. // constructing behavior
  112606. switch (type) {
  112607. case 0 /* AUTOROTATION */:
  112608. this.camera.useAutoRotationBehavior = enabled;
  112609. behavior = this.camera.autoRotationBehavior;
  112610. break;
  112611. case 1 /* BOUNCING */:
  112612. this.camera.useBouncingBehavior = enabled;
  112613. behavior = this.camera.bouncingBehavior;
  112614. break;
  112615. case 2 /* FRAMING */:
  112616. this.camera.useFramingBehavior = enabled;
  112617. behavior = this.camera.framingBehavior;
  112618. break;
  112619. default:
  112620. behavior = null;
  112621. break;
  112622. }
  112623. if (behavior) {
  112624. this._cameraBehaviorMapping[name] = type;
  112625. if (typeof behaviorConfig === "object") {
  112626. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  112627. }
  112628. }
  112629. // post attach configuration. Some functionalities require the attached camera.
  112630. switch (type) {
  112631. case 0 /* AUTOROTATION */:
  112632. break;
  112633. case 1 /* BOUNCING */:
  112634. break;
  112635. case 2 /* FRAMING */:
  112636. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  112637. if (config.zoomOnBoundingInfo) {
  112638. behavior.zoomOnMeshHierarchy(model.rootMesh);
  112639. }
  112640. });
  112641. break;
  112642. }
  112643. };
  112644. return SceneManager;
  112645. }());
  112646. exports.SceneManager = SceneManager;
  112647. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUErakI7QUFDL2pCLGtEQUFtUjtBQUNuUixvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBc0ZJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQX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7U0FDSjtRQUVELCtFQUErRTtRQUMvRSxRQUFRLElBQUksRUFBRTtZQUNWO2dCQUNJLE1BQU07WUFDVjtnQkFDSSxNQUFNO1lBQ1Y7Z0JBQ0ksSUFBSSxDQUFDLG1CQUFtQixJQUFJLElBQUksQ0FBQyxtQkFBbUIsQ0FBQyx1QkFBdUIsQ0FBQyxHQUFHLENBQUMsVUFBQyxLQUFLO29CQUNuRixJQUFJLE1BQU0sQ0FBQyxrQkFBa0IsRUFBRTt3QkFDVCxRQUFTLENBQUMsbUJBQW1CLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxDQUFDO3FCQUNuRTtnQkFDTCxDQUFDLENBQUMsQ0FBQztnQkFDSCxNQUFNO1NBQ2I7SUFDTCxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBejNDRCxJQXkzQ0M7QUF6M0NZLG9DQUFZIn0=
  112648. /***/ }),
  112649. /* 23 */
  112650. /***/ (function(module, exports, __webpack_require__) {
  112651. "use strict";
  112652. Object.defineProperty(exports, "__esModule", { value: true });
  112653. /**
  112654. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  112655. * native GroupAnimation class.
  112656. */
  112657. var GroupModelAnimation = /** @class */ (function () {
  112658. /**
  112659. * Create a new GroupModelAnimation object using an AnimationGroup object
  112660. * @param _animationGroup The aniamtion group to base the class on
  112661. */
  112662. function GroupModelAnimation(_animationGroup) {
  112663. var _this = this;
  112664. this._animationGroup = _animationGroup;
  112665. this._state = 0 /* INIT */;
  112666. this._playMode = 1 /* LOOP */;
  112667. this._animationGroup.onAnimationEndObservable.add(function () {
  112668. _this.stop();
  112669. _this._state = 4 /* ENDED */;
  112670. });
  112671. }
  112672. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  112673. /**
  112674. * Get the animation's name
  112675. */
  112676. get: function () {
  112677. return this._animationGroup.name;
  112678. },
  112679. enumerable: true,
  112680. configurable: true
  112681. });
  112682. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  112683. /**
  112684. * Get the current animation's state
  112685. */
  112686. get: function () {
  112687. return this._state;
  112688. },
  112689. enumerable: true,
  112690. configurable: true
  112691. });
  112692. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  112693. /**
  112694. * Gets the speed ratio to use for all animations
  112695. */
  112696. get: function () {
  112697. return this._animationGroup.speedRatio;
  112698. },
  112699. /**
  112700. * Sets the speed ratio to use for all animations
  112701. */
  112702. set: function (value) {
  112703. this._animationGroup.speedRatio = value;
  112704. },
  112705. enumerable: true,
  112706. configurable: true
  112707. });
  112708. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  112709. /**
  112710. * Get the max numbers of frame available in the animation group
  112711. *
  112712. * In correlation to an arry, this would be ".length"
  112713. */
  112714. get: function () {
  112715. return this._animationGroup.to - this._animationGroup.from;
  112716. },
  112717. enumerable: true,
  112718. configurable: true
  112719. });
  112720. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  112721. /**
  112722. * Get the current frame playing right now.
  112723. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  112724. *
  112725. * In correlation to an array, this would be the current index
  112726. */
  112727. get: function () {
  112728. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  112729. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  112730. }
  112731. else {
  112732. return 0;
  112733. }
  112734. },
  112735. enumerable: true,
  112736. configurable: true
  112737. });
  112738. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  112739. /**
  112740. * Get the FPS value of this animation
  112741. */
  112742. get: function () {
  112743. // get the first currentFrame found
  112744. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  112745. var animatable = this._animationGroup.animatables[i];
  112746. var animations = animatable.getAnimations();
  112747. if (!animations || !animations.length) {
  112748. continue;
  112749. }
  112750. for (var idx = 0; idx < animations.length; ++idx) {
  112751. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  112752. return animations[idx].animation.framePerSecond;
  112753. }
  112754. }
  112755. }
  112756. return 0;
  112757. },
  112758. enumerable: true,
  112759. configurable: true
  112760. });
  112761. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  112762. /**
  112763. * What is the animation'S play mode (looping or played once)
  112764. */
  112765. get: function () {
  112766. return this._playMode;
  112767. },
  112768. /**
  112769. * Set the play mode.
  112770. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  112771. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  112772. */
  112773. set: function (value) {
  112774. if (value === this._playMode) {
  112775. return;
  112776. }
  112777. this._playMode = value;
  112778. if (this.state === 1 /* PLAYING */) {
  112779. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  112780. }
  112781. else {
  112782. this._animationGroup.reset();
  112783. this._state = 0 /* INIT */;
  112784. }
  112785. },
  112786. enumerable: true,
  112787. configurable: true
  112788. });
  112789. /**
  112790. * Reset the animation group
  112791. */
  112792. GroupModelAnimation.prototype.reset = function () {
  112793. this._animationGroup.reset();
  112794. };
  112795. /**
  112796. * Restart the animation group
  112797. */
  112798. GroupModelAnimation.prototype.restart = function () {
  112799. if (this.state === 2 /* PAUSED */)
  112800. this._animationGroup.restart();
  112801. else
  112802. this.start();
  112803. };
  112804. /**
  112805. *
  112806. * @param frameNumber Go to a specific frame in the animation
  112807. */
  112808. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  112809. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  112810. };
  112811. /**
  112812. * Start playing the animation.
  112813. */
  112814. GroupModelAnimation.prototype.start = function () {
  112815. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  112816. if (this._animationGroup.isStarted) {
  112817. this._state = 1 /* PLAYING */;
  112818. }
  112819. };
  112820. /**
  112821. * Pause the animation
  112822. */
  112823. GroupModelAnimation.prototype.pause = function () {
  112824. this._animationGroup.pause();
  112825. this._state = 2 /* PAUSED */;
  112826. };
  112827. /**
  112828. * Stop the animation.
  112829. * This will fail silently if the animation group is already stopped.
  112830. */
  112831. GroupModelAnimation.prototype.stop = function () {
  112832. this._animationGroup.stop();
  112833. if (!this._animationGroup.isStarted) {
  112834. this._state = 3 /* STOPPED */;
  112835. }
  112836. };
  112837. /**
  112838. * Dispose this animation object.
  112839. */
  112840. GroupModelAnimation.prototype.dispose = function () {
  112841. this._animationGroup.dispose();
  112842. };
  112843. return GroupModelAnimation;
  112844. }());
  112845. exports.GroupModelAnimation = GroupModelAnimation;
  112846. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O1dBRUc7YUFDSDtZQUNJLE9BQU8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BSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  112847. /***/ }),
  112848. /* 24 */
  112849. /***/ (function(module, exports, __webpack_require__) {
  112850. "use strict";
  112851. Object.defineProperty(exports, "__esModule", { value: true });
  112852. var environmentSerializer_1 = __webpack_require__(25);
  112853. var babylonjs_1 = __webpack_require__(0);
  112854. var texture_1 = __webpack_require__(12);
  112855. /**
  112856. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  112857. * The APIs in all labs-related classes and configuration might change.
  112858. * Once stable, lab features will be moved to the publis API and configuration object.
  112859. */
  112860. var ViewerLabs = /** @class */ (function () {
  112861. function ViewerLabs(_scene) {
  112862. this._scene = _scene;
  112863. this.environment = {
  112864. //irradiance
  112865. irradiancePolynomialCoefficients: {
  112866. x: new babylonjs_1.Vector3(0, 0, 0),
  112867. y: new babylonjs_1.Vector3(0, 0, 0),
  112868. z: new babylonjs_1.Vector3(0, 0, 0),
  112869. xx: new babylonjs_1.Vector3(0, 0, 0),
  112870. yy: new babylonjs_1.Vector3(0, 0, 0),
  112871. zz: new babylonjs_1.Vector3(0, 0, 0),
  112872. yz: new babylonjs_1.Vector3(0, 0, 0),
  112873. zx: new babylonjs_1.Vector3(0, 0, 0),
  112874. xy: new babylonjs_1.Vector3(0, 0, 0)
  112875. },
  112876. textureIntensityScale: 1.0
  112877. };
  112878. }
  112879. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  112880. var _this = this;
  112881. //@! todo: should loadEnvironment cancel any currently loading environments?
  112882. if (data instanceof ArrayBuffer) {
  112883. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  112884. if (onSuccess)
  112885. onSuccess(this.environment);
  112886. }
  112887. else if (typeof data === 'string') {
  112888. var url = this.getAssetUrl(data);
  112889. this._scene._loadFile(url, function (arrayBuffer) {
  112890. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  112891. if (onSuccess)
  112892. onSuccess(_this.environment);
  112893. }, function (progressEvent) { if (onProgress)
  112894. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  112895. if (onError) {
  112896. onError(e);
  112897. }
  112898. });
  112899. }
  112900. else {
  112901. //data assumed to be PBREnvironment object
  112902. this.environment = data;
  112903. if (onSuccess)
  112904. onSuccess(data);
  112905. }
  112906. };
  112907. /**
  112908. * Applies an `EnvironmentMapConfiguration` to the scene
  112909. * @param environmentMapConfiguration Environment map configuration to apply
  112910. */
  112911. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  112912. if (!this.environment)
  112913. return;
  112914. //set orientation
  112915. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  112916. // Add env texture to the scene.
  112917. if (this.environment.specularTexture) {
  112918. // IE crashes when disposing the old texture and setting a new one
  112919. if (!this._scene.environmentTexture) {
  112920. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  112921. }
  112922. if (this._scene.environmentTexture) {
  112923. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  112924. this._scene.environmentTexture.invertZ = true;
  112925. this._scene.environmentTexture.lodLevelInAlpha = true;
  112926. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  112927. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  112928. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  112929. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  112930. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  112931. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  112932. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  112933. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  112934. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  112935. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  112936. this._scene.environmentTexture.sphericalPolynomial = poly;
  112937. //set orientation
  112938. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  112939. }
  112940. }
  112941. };
  112942. /**
  112943. * Get an environment asset url by using the configuration if the path is not absolute.
  112944. * @param url Asset url
  112945. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  112946. */
  112947. ViewerLabs.prototype.getAssetUrl = function (url) {
  112948. var returnUrl = url;
  112949. if (url && url.toLowerCase().indexOf("//") === -1) {
  112950. if (!this.assetsRootURL) {
  112951. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  112952. return url;
  112953. }
  112954. returnUrl = this.assetsRootURL + returnUrl;
  112955. }
  112956. return returnUrl;
  112957. };
  112958. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  112959. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  112960. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  112961. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  112962. axis.normalize();
  112963. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  112964. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  112965. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  112966. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  112967. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  112968. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  112969. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  112970. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  112971. shadowLight.setDirectionToTarget(target);
  112972. };
  112973. return ViewerLabs;
  112974. }());
  112975. exports.ViewerLabs = ViewerLabs;
  112976. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQU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QUMsQ0FBQyxDQUFDO1FBQ3pDLGtCQUFNLENBQUMsaUJBQWlCLENBQUMsSUFBSSxFQUFFLE1BQU0sRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDdEQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  112977. /***/ }),
  112978. /* 25 */
  112979. /***/ (function(module, exports, __webpack_require__) {
  112980. "use strict";
  112981. Object.defineProperty(exports, "__esModule", { value: true });
  112982. var babylonjs_1 = __webpack_require__(0);
  112983. var texture_1 = __webpack_require__(12);
  112984. /**
  112985. * A static class proving methods to aid parsing Spectre environment files
  112986. */
  112987. var EnvironmentDeserializer = /** @class */ (function () {
  112988. function EnvironmentDeserializer() {
  112989. }
  112990. /**
  112991. * Parses an arraybuffer into a new PBREnvironment object
  112992. * @param arrayBuffer The arraybuffer of the Spectre environment file
  112993. * @return a PBREnvironment object
  112994. */
  112995. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  112996. var environment = {
  112997. //irradiance
  112998. irradiancePolynomialCoefficients: {
  112999. x: new babylonjs_1.Vector3(0, 0, 0),
  113000. y: new babylonjs_1.Vector3(0, 0, 0),
  113001. z: new babylonjs_1.Vector3(0, 0, 0),
  113002. xx: new babylonjs_1.Vector3(0, 0, 0),
  113003. yy: new babylonjs_1.Vector3(0, 0, 0),
  113004. zz: new babylonjs_1.Vector3(0, 0, 0),
  113005. yz: new babylonjs_1.Vector3(0, 0, 0),
  113006. zx: new babylonjs_1.Vector3(0, 0, 0),
  113007. xy: new babylonjs_1.Vector3(0, 0, 0)
  113008. },
  113009. //specular
  113010. textureIntensityScale: 1.0,
  113011. };
  113012. //read .env
  113013. var littleEndian = false;
  113014. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  113015. var dataView = new DataView(arrayBuffer);
  113016. var pos = 0;
  113017. for (var i = 0; i < magicBytes.length; i++) {
  113018. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  113019. babylonjs_1.Tools.Error('Not a Spectre environment map');
  113020. }
  113021. }
  113022. var version = dataView.getUint16(pos, littleEndian);
  113023. pos += 2;
  113024. if (version !== 1) {
  113025. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  113026. }
  113027. //read json descriptor - collect characters up to null terminator
  113028. var descriptorString = '';
  113029. var charCode = 0x00;
  113030. while ((charCode = dataView.getUint8(pos++))) {
  113031. descriptorString += String.fromCharCode(charCode);
  113032. }
  113033. var descriptor = JSON.parse(descriptorString);
  113034. var payloadPos = pos;
  113035. //irradiance
  113036. switch (descriptor.irradiance.type) {
  113037. case 'irradiance_sh_coefficients_9':
  113038. //irradiance
  113039. var harmonics = descriptor.irradiance;
  113040. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  113041. //harmonics now represent radiance
  113042. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  113043. break;
  113044. default:
  113045. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  113046. }
  113047. //specular
  113048. switch (descriptor.specular.type) {
  113049. case 'cubemap_faces':
  113050. var specularDescriptor = descriptor.specular;
  113051. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  113052. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  113053. var mipmaps = specularDescriptor.mipmaps;
  113054. var imageType = specularDescriptor.imageType;
  113055. for (var l = 0; l < mipmaps.length; l++) {
  113056. var faceRanges = mipmaps[l];
  113057. specularTexture.source[l] = [];
  113058. for (var i = 0; i < 6; i++) {
  113059. var range = faceRanges[i];
  113060. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  113061. switch (imageType) {
  113062. case 'png':
  113063. //construct image element from bytes
  113064. var image = new Image();
  113065. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  113066. image.src = src;
  113067. specularTexture.source[l][i] = image;
  113068. break;
  113069. default:
  113070. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  113071. }
  113072. }
  113073. }
  113074. break;
  113075. default:
  113076. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  113077. }
  113078. return environment;
  113079. };
  113080. /**
  113081. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  113082. * L = (1/pi) * E * rho
  113083. *
  113084. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  113085. * @param harmonics Spherical harmonic coefficients (9)
  113086. */
  113087. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  113088. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  113089. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  113090. // (The pixel shader must apply albedo after texture fetches, etc).
  113091. };
  113092. /**
  113093. * Convert spherical harmonics to spherical polynomial coefficients
  113094. * @param harmonics Spherical harmonic coefficients (9)
  113095. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  113096. */
  113097. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  113098. var rPi = 1 / Math.PI;
  113099. //x
  113100. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  113101. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  113102. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  113103. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  113104. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  113105. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  113106. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  113107. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  113108. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  113109. //xx
  113110. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  113111. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  113112. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  113113. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  113114. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  113115. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  113116. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  113117. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  113118. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  113119. //yz
  113120. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  113121. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  113122. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  113123. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  113124. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  113125. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  113126. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  113127. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  113128. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  113129. };
  113130. /**
  113131. * Multiplies harmonic coefficients in place
  113132. * @param harmonics Spherical harmonic coefficients (9)
  113133. * @param scaleFactor Value to multiply by
  113134. */
  113135. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  113136. harmonics.l00[0] *= scaleFactor;
  113137. harmonics.l00[1] *= scaleFactor;
  113138. harmonics.l00[2] *= scaleFactor;
  113139. harmonics.l1_1[0] *= scaleFactor;
  113140. harmonics.l1_1[1] *= scaleFactor;
  113141. harmonics.l1_1[2] *= scaleFactor;
  113142. harmonics.l10[0] *= scaleFactor;
  113143. harmonics.l10[1] *= scaleFactor;
  113144. harmonics.l10[2] *= scaleFactor;
  113145. harmonics.l11[0] *= scaleFactor;
  113146. harmonics.l11[1] *= scaleFactor;
  113147. harmonics.l11[2] *= scaleFactor;
  113148. harmonics.l2_2[0] *= scaleFactor;
  113149. harmonics.l2_2[1] *= scaleFactor;
  113150. harmonics.l2_2[2] *= scaleFactor;
  113151. harmonics.l2_1[0] *= scaleFactor;
  113152. harmonics.l2_1[1] *= scaleFactor;
  113153. harmonics.l2_1[2] *= scaleFactor;
  113154. harmonics.l20[0] *= scaleFactor;
  113155. harmonics.l20[1] *= scaleFactor;
  113156. harmonics.l20[2] *= scaleFactor;
  113157. harmonics.l21[0] *= scaleFactor;
  113158. harmonics.l21[1] *= scaleFactor;
  113159. harmonics.l21[2] *= scaleFactor;
  113160. harmonics.l22[0] *= scaleFactor;
  113161. harmonics.l22[1] *= scaleFactor;
  113162. harmonics.l22[2] *= scaleFactor;
  113163. };
  113164. return EnvironmentDeserializer;
  113165. }());
  113166. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  113167. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7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LFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  113168. /***/ }),
  113169. /* 26 */
  113170. /***/ (function(module, exports, __webpack_require__) {
  113171. "use strict";
  113172. Object.defineProperty(exports, "__esModule", { value: true });
  113173. var extended_1 = __webpack_require__(27);
  113174. var cache = {};
  113175. /**
  113176. *
  113177. * @param name the name of the custom optimizer configuration
  113178. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  113179. */
  113180. function getCustomOptimizerByName(name, upgrade) {
  113181. if (!cache[name]) {
  113182. switch (name) {
  113183. case 'extended':
  113184. if (upgrade) {
  113185. return extended_1.extendedUpgrade;
  113186. }
  113187. else {
  113188. return extended_1.extendedDegrade;
  113189. }
  113190. }
  113191. }
  113192. return cache[name];
  113193. }
  113194. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  113195. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  113196. /***/ }),
  113197. /* 27 */
  113198. /***/ (function(module, exports, __webpack_require__) {
  113199. "use strict";
  113200. Object.defineProperty(exports, "__esModule", { value: true });
  113201. var babylonjs_1 = __webpack_require__(0);
  113202. /**
  113203. * A custom upgrade-oriented function configuration for the scene optimizer.
  113204. *
  113205. * @param viewer the viewer to optimize
  113206. */
  113207. function extendedUpgrade(sceneManager) {
  113208. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  113209. // if (!this.Scene.BackgroundHelper) {
  113210. // this.Scene.EngineScene.autoClear = false;
  113211. // this.Scene.BackgroundHelper = true;
  113212. // Would require a dedicated clear color;
  113213. // return false;
  113214. // }
  113215. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  113216. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  113217. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  113218. return false;
  113219. }
  113220. if (!sceneManager.scene.postProcessesEnabled) {
  113221. sceneManager.scene.postProcessesEnabled = true;
  113222. return false;
  113223. }
  113224. if (!sceneManager.groundEnabled) {
  113225. sceneManager.groundEnabled = true;
  113226. return false;
  113227. }
  113228. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  113229. sceneManager.fxaaEnabled = true;
  113230. return false;
  113231. }
  113232. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  113233. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  113234. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  113235. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  113236. return false;
  113237. }
  113238. if (!sceneManager.processShadows) {
  113239. sceneManager.processShadows = true;
  113240. return false;
  113241. }
  113242. if (defaultPipeline && !sceneManager.bloomEnabled) {
  113243. sceneManager.bloomEnabled = true;
  113244. return false;
  113245. }
  113246. if (!sceneManager.groundMirrorEnabled) {
  113247. sceneManager.groundMirrorEnabled = true;
  113248. return false;
  113249. }
  113250. return true;
  113251. }
  113252. exports.extendedUpgrade = extendedUpgrade;
  113253. /**
  113254. * A custom degrade-oriented function configuration for the scene optimizer.
  113255. *
  113256. * @param viewer the viewer to optimize
  113257. */
  113258. function extendedDegrade(sceneManager) {
  113259. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  113260. if (sceneManager.groundMirrorEnabled) {
  113261. sceneManager.groundMirrorEnabled = false;
  113262. return false;
  113263. }
  113264. if (defaultPipeline && sceneManager.bloomEnabled) {
  113265. sceneManager.bloomEnabled = false;
  113266. return false;
  113267. }
  113268. if (sceneManager.processShadows) {
  113269. sceneManager.processShadows = false;
  113270. return false;
  113271. }
  113272. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  113273. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  113274. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  113275. return false;
  113276. }
  113277. if (defaultPipeline && sceneManager.fxaaEnabled) {
  113278. sceneManager.fxaaEnabled = false;
  113279. return false;
  113280. }
  113281. if (sceneManager.groundEnabled) {
  113282. sceneManager.groundEnabled = false;
  113283. return false;
  113284. }
  113285. if (sceneManager.scene.postProcessesEnabled) {
  113286. sceneManager.scene.postProcessesEnabled = false;
  113287. return false;
  113288. }
  113289. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  113290. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  113291. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  113292. return false;
  113293. }
  113294. // if (this.Scene.BackgroundHelper) {
  113295. // this.Scene.EngineScene.autoClear = true;
  113296. // this.Scene.BackgroundHelper = false;
  113297. // Would require a dedicated clear color;
  113298. // return false;
  113299. // }
  113300. return true;
  113301. }
  113302. exports.extendedDegrade = extendedDegrade;
  113303. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFv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UFZLENBQUMsYUFBYSxHQUFHLEtBQUssQ0FBQztRQUNuQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxvQkFBb0IsRUFBRTtRQUN6QyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  113304. /***/ }),
  113305. /* 28 */
  113306. /***/ (function(module, exports, __webpack_require__) {
  113307. "use strict";
  113308. Object.defineProperty(exports, "__esModule", { value: true });
  113309. var mappers_1 = __webpack_require__(3);
  113310. var types_1 = __webpack_require__(29);
  113311. var configurationCompatibility_1 = __webpack_require__(53);
  113312. var _1 = __webpack_require__(1);
  113313. var babylonjs_1 = __webpack_require__(0);
  113314. /**
  113315. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  113316. * parse the object and return a conform ViewerConfiguration.
  113317. * It is a private member of the scene.
  113318. */
  113319. var ConfigurationLoader = /** @class */ (function () {
  113320. function ConfigurationLoader(_enableCache) {
  113321. if (_enableCache === void 0) { _enableCache = false; }
  113322. this._enableCache = _enableCache;
  113323. this._configurationCache = {};
  113324. this._loadRequests = [];
  113325. }
  113326. /**
  113327. * load a configuration object that is defined in the initial configuration provided.
  113328. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  113329. *
  113330. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  113331. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  113332. * @returns A promise that delivers the extended viewer configuration, when done.
  113333. */
  113334. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  113335. var _this = this;
  113336. if (initConfig === void 0) { initConfig = {}; }
  113337. var loadedConfig = _1.deepmerge({}, initConfig);
  113338. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  113339. if (loadedConfig.configuration) {
  113340. var mapperType_1 = "json";
  113341. return Promise.resolve().then(function () {
  113342. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  113343. // a file to load
  113344. var url = '';
  113345. if (typeof loadedConfig.configuration === "string") {
  113346. url = loadedConfig.configuration;
  113347. }
  113348. // if configuration is an object
  113349. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  113350. url = loadedConfig.configuration.url;
  113351. var type = loadedConfig.configuration.mapper;
  113352. // empty string?
  113353. if (!type) {
  113354. // load mapper type from filename / url
  113355. type = loadedConfig.configuration.url.split('.').pop();
  113356. }
  113357. mapperType_1 = type || mapperType_1;
  113358. }
  113359. return _this._loadFile(url);
  113360. }
  113361. else {
  113362. if (typeof loadedConfig.configuration === "object") {
  113363. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  113364. return loadedConfig.configuration.payload || {};
  113365. }
  113366. return {};
  113367. }
  113368. }).then(function (data) {
  113369. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  113370. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  113371. var merged = _1.deepmerge(extendedConfiguration, parsed);
  113372. configurationCompatibility_1.processConfigurationCompatibility(merged);
  113373. if (callback)
  113374. callback(merged);
  113375. return merged;
  113376. });
  113377. }
  113378. else {
  113379. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  113380. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  113381. if (callback)
  113382. callback(loadedConfig);
  113383. return Promise.resolve(loadedConfig);
  113384. }
  113385. };
  113386. /**
  113387. * Dispose the configuration loader. This will cancel file requests, if active.
  113388. */
  113389. ConfigurationLoader.prototype.dispose = function () {
  113390. this._loadRequests.forEach(function (request) {
  113391. request.abort();
  113392. });
  113393. this._loadRequests.length = 0;
  113394. };
  113395. ConfigurationLoader.prototype._loadFile = function (url) {
  113396. var _this = this;
  113397. var cacheReference = this._configurationCache;
  113398. if (this._enableCache && cacheReference[url]) {
  113399. return Promise.resolve(cacheReference[url]);
  113400. }
  113401. return new Promise(function (resolve, reject) {
  113402. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  113403. var idx = _this._loadRequests.indexOf(fileRequest);
  113404. if (idx !== -1)
  113405. _this._loadRequests.splice(idx, 1);
  113406. if (_this._enableCache)
  113407. cacheReference[url] = result;
  113408. resolve(result);
  113409. }, undefined, undefined, false, function (request, error) {
  113410. var idx = _this._loadRequests.indexOf(fileRequest);
  113411. if (idx !== -1)
  113412. _this._loadRequests.splice(idx, 1);
  113413. reject(error);
  113414. });
  113415. _this._loadRequests.push(fileRequest);
  113416. });
  113417. };
  113418. return ConfigurationLoader;
  113419. }());
  113420. exports.ConfigurationLoader = ConfigurationLoader;
  113421. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ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LENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9
  113422. /***/ }),
  113423. /* 29 */
  113424. /***/ (function(module, exports, __webpack_require__) {
  113425. "use strict";
  113426. Object.defineProperty(exports, "__esModule", { value: true });
  113427. var minimal_1 = __webpack_require__(30);
  113428. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  113429. var default_1 = __webpack_require__(49);
  113430. exports.defaultConfiguration = default_1.defaultConfiguration;
  113431. var extended_1 = __webpack_require__(50);
  113432. var shadowLight_1 = __webpack_require__(51);
  113433. var environmentMap_1 = __webpack_require__(52);
  113434. var _1 = __webpack_require__(1);
  113435. /**
  113436. * Get the configuration type you need to use as the base for your viewer.
  113437. * The types can either be a single string, or comma separated types that will extend each other. for example:
  113438. *
  113439. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  113440. *
  113441. * @param types a comma-separated string of the type(s) or configuration to load.
  113442. */
  113443. var getConfigurationType = function (types) {
  113444. var config = {};
  113445. var typesSeparated = types.split(",");
  113446. typesSeparated.forEach(function (type) {
  113447. switch (type.trim()) {
  113448. case 'environmentMap':
  113449. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  113450. break;
  113451. case 'shadowDirectionalLight':
  113452. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  113453. break;
  113454. case 'shadowSpotLight':
  113455. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  113456. break;
  113457. case 'extended':
  113458. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  113459. break;
  113460. case 'minimal':
  113461. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  113462. break;
  113463. case 'none':
  113464. break;
  113465. case 'default':
  113466. default:
  113467. config = _1.deepmerge(config, default_1.defaultConfiguration);
  113468. break;
  113469. }
  113470. if (config.extends) {
  113471. config = _1.deepmerge(config, getConfigurationType(config.extends));
  113472. }
  113473. });
  113474. return config;
  113475. };
  113476. exports.getConfigurationType = getConfigurationType;
  113477. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQUMsT0FBTyxDQUFDLFVBQUEsSUFBSTtRQUN2QixRQUFRLElBQUksQ0FBQyxJQUFJLEVBQUUsRUFBRTtZQUNqQixLQUFLLGdCQUFnQjtnQkFDakIsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsNENBQTJCLENBQUMsQ0FBQztnQkFDeEQsTUFBTTtZQUNWLEtBQUssd0JBQXdCO2dCQUN6QixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxpREFBbUMsQ0FBQyxDQUFDO2dCQUNoRSxNQUFNO1lBQ1YsS0FBSyxpQkFBaUI7Z0JBQ2xCLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDJDQUE2QixDQUFDLENBQUM7Z0JBQzFELE1BQU07WUFDVixLQUFLLFVBQVU7Z0JBQ1gsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsZ0NBQXFCLENBQUMsQ0FBQztnQkFDbEQsTUFBTTtZQUNWLEtBQUssU0FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  113478. /***/ }),
  113479. /* 30 */
  113480. /***/ (function(module, exports, __webpack_require__) {
  113481. "use strict";
  113482. Object.defineProperty(exports, "__esModule", { value: true });
  113483. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  113484. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  113485. /**
  113486. * The minimal configuration needed to make the viewer work.
  113487. * Some functionalities might not work correctly (like fill-screen)
  113488. */
  113489. exports.minimalConfiguration = {
  113490. version: "0.1",
  113491. templates: {
  113492. main: {
  113493. html: babylonjs_viewer_assets_1.defaultTemplate
  113494. },
  113495. fillContainer: {
  113496. html: babylonjs_viewer_assets_1.fillContainer,
  113497. params: {
  113498. disable: false
  113499. }
  113500. },
  113501. loadingScreen: {
  113502. html: babylonjs_viewer_assets_1.loadingScreen,
  113503. params: {
  113504. backgroundColor: "#000000",
  113505. loadingImage: babylonjs_viewer_assets_2.loading
  113506. }
  113507. },
  113508. viewer: {
  113509. html: babylonjs_viewer_assets_1.defaultViewer,
  113510. },
  113511. overlay: {
  113512. html: babylonjs_viewer_assets_1.overlay,
  113513. params: {
  113514. closeImage: babylonjs_viewer_assets_2.close,
  113515. closeText: 'Close'
  113516. }
  113517. },
  113518. error: {
  113519. html: babylonjs_viewer_assets_1.error
  113520. }
  113521. },
  113522. engine: {
  113523. antialiasing: true
  113524. }
  113525. };
  113526. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  113527. /***/ }),
  113528. /* 31 */
  113529. /***/ (function(module, exports, __webpack_require__) {
  113530. "use strict";
  113531. Object.defineProperty(exports, "__esModule", { value: true });
  113532. exports.babylonFont = __webpack_require__(32);
  113533. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  113534. /***/ }),
  113535. /* 32 */
  113536. /***/ (function(module, exports) {
  113537. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABMwAA8AAAAAIYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp+FVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAAB7AAAAvq1MrYZjdnQgAAAEJAAAACAAAAAqCdkJr2ZwZ20AAAREAAAA8AAAAVn8nuaOZ2FzcAAABTQAAAAMAAAADAAIABtnbHlmAAAFQAAAB1kAAAoyCcJmr2hlYWQAAAycAAAAMgAAADb+XTcFaGhlYQAADNAAAAAVAAAAJBABCAZobXR4AAAM6AAAACcAAAAuErQDvGxvY2EAAA0QAAAAJgAAACYPBAyHbWF4cAAADTgAAAA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ucl2wSsyWNJFS7SbsAq0MNL7xGC9N4wxZpfZpSe4OqY+zz3i0bBysMaIBDyOok9BOiX+hyDDDPEmI91FuU/oXEH2nXYC+xTOWFNFmcb/oWpYIwfSq2wI/5r+MfA9aR97P0PADbFMiKcEhgakY2LDbIcLvVuKuYQqKeoBn1lg3x5QTpwq0cBeUe3aSrQV67RRpilrAxqYh2QDOKekV1KvGpK0M8ZBZuCutU08i/RnQdwldRZzdnSHViOKo+tEThmhVRdXa2GpC+YpyXiWw+BfdbWkcwo2CZwHVK92Xlu/g5mfJzNQNIs11SmBdXHNap8paieQTUVzly6sPdrkhM6B/nnYcUJHvi6L2NsY/m9t5+wpMU1AZmiOHXUumc3qogw670/Hda03A5hJm4sjf91bgPxtrilIaspc01v5rNkTh6ZKUl+0X9usWlzRm1WRJUbbdbPjQc2c3uR/ntH2q1b4zszZuzdE+Srj/GC8I6p029v5F1nQBHfnP+HU/1rLQ99k+iofugfv0avRZvR+9G70NqxXDjEVYH8H9B5R3Yo2yuD74JuQUTd3QNNAvJiN+BtTGIWpeNpjYGYAg/9+DOUMWAAAKSoByAB42tvAoM2wiZGTSZtxExeI3M7Vmhtqq8rAob2dOzXYQU8GxOKJ8LDQkASxeJ3NteWFQSw+HRUZER4Qi19OQpiPA8QS4OPhZGcBsQTBAMQS2jChIMAAyGLYzgg3mgluNDPcaBa40axwo9nkJKFGs8ON5oAbzQk3epMwI7v2BgYF19pMCRcAxAEoGgAAAA=="
  113538. /***/ }),
  113539. /* 33 */
  113540. /***/ (function(module, exports, __webpack_require__) {
  113541. "use strict";
  113542. Object.defineProperty(exports, "__esModule", { value: true });
  113543. exports.babylonLogo = __webpack_require__(34);
  113544. exports.close = __webpack_require__(35);
  113545. exports.fullscreen = __webpack_require__(36);
  113546. exports.helpCircle = __webpack_require__(37);
  113547. exports.loading = __webpack_require__(38);
  113548. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  113549. /***/ }),
  113550. /* 34 */
  113551. /***/ (function(module, exports) {
  113552. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJm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YTUbRmm1JgN7HCBgAAAKAiymwAAA7tLMlXMbzYIqXAXokCAAAAgBopswEAOIaPSf4Uw5NZYQMAAAAwGspsAACOpUlyLoZHuUopsVeiAAAAAGAslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  113553. /***/ }),
  113554. /* 35 */
  113555. /***/ (function(module, exports) {
  113556. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  113557. /***/ }),
  113558. /* 36 */
  113559. /***/ (function(module, exports) {
  113560. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  113561. /***/ }),
  113562. /* 37 */
  113563. /***/ (function(module, exports) {
  113564. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  113565. /***/ }),
  113566. /* 38 */
  113567. /***/ (function(module, exports) {
  113568. 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/A4nlMAxvjbKa0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Eid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  113569. /***/ }),
  113570. /* 39 */
  113571. /***/ (function(module, exports, __webpack_require__) {
  113572. "use strict";
  113573. Object.defineProperty(exports, "__esModule", { value: true });
  113574. exports.defaultTemplate = __webpack_require__(40);
  113575. exports.defaultViewer = __webpack_require__(41);
  113576. exports.error = __webpack_require__(42);
  113577. exports.fillContainer = __webpack_require__(43);
  113578. exports.help = __webpack_require__(44);
  113579. exports.loadingScreen = __webpack_require__(45);
  113580. exports.navbar = __webpack_require__(46);
  113581. exports.overlay = __webpack_require__(47);
  113582. exports.share = __webpack_require__(48);
  113583. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  113584. /***/ }),
  113585. /* 40 */
  113586. /***/ (function(module, exports) {
  113587. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  113588. /***/ }),
  113589. /* 41 */
  113590. /***/ (function(module, exports) {
  113591. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  113592. /***/ }),
  113593. /* 42 */
  113594. /***/ (function(module, exports) {
  113595. module.exports = "Error loading the model";
  113596. /***/ }),
  113597. /* 43 */
  113598. /***/ (function(module, exports) {
  113599. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  113600. /***/ }),
  113601. /* 44 */
  113602. /***/ (function(module, exports) {
  113603. module.exports = "HELP";
  113604. /***/ }),
  113605. /* 45 */
  113606. /***/ (function(module, exports) {
  113607. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  113608. /***/ }),
  113609. /* 46 */
  113610. /***/ (function(module, exports) {
  113611. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}viewer:fullscreen .fullscreen-icon:after{content:\"\\E73F\"}viewer:-webkit-full-screen .fullscreen-icon:after{content:\"\\E73F\"}viewer:-moz-full-screen .fullscreen-icon:after{content:\"\\E73F\"}viewer:-ms-full-screen .fullscreen-icon:after{content:\"\\E73F\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.hd-icon:after{font-size:16px;content:\"\\F765\"}.sd-icon:after{font-size:16px;content:\"\\F766\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer: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=\"nav-container navbar-control\"> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container types-button animation-buttons\"> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container label-option-button animation-buttons\" data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control> <button class=\"play-pause play-pause-button\"> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=\"flex-container speed-button\"> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=\"flex-container speed-option-button\" data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHdButton}} <button class=\"hd-button hd-button\" title={{text.hdButton}}> {{#if hdEnabled}} <span class=\"icon sd-icon\"></span> {{else}} <span class=\"icon hd-icon\"></span> {{/if}} </button> {{/unless}} {{#unless hideHelp}} <button class=\"help help-button\" title={{text.helpButton}}> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=\"fullscreen fullscreen-button\" title={{text.fullscreenButton}}> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  113612. /***/ }),
  113613. /* 47 */
  113614. /***/ (function(module, exports) {
  113615. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:none;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  113616. /***/ }),
  113617. /* 48 */
  113618. /***/ (function(module, exports) {
  113619. module.exports = "SHARE";
  113620. /***/ }),
  113621. /* 49 */
  113622. /***/ (function(module, exports, __webpack_require__) {
  113623. "use strict";
  113624. Object.defineProperty(exports, "__esModule", { value: true });
  113625. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  113626. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  113627. var images = __webpack_require__(2);
  113628. /**
  113629. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  113630. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  113631. */
  113632. exports.defaultConfiguration = {
  113633. version: "3.2.0-alpha4",
  113634. templates: {
  113635. main: {
  113636. html: babylonjs_viewer_assets_1.defaultTemplate,
  113637. params: {
  113638. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  113639. noEscape: true
  113640. }
  113641. },
  113642. fillContainer: {
  113643. html: babylonjs_viewer_assets_1.fillContainer,
  113644. params: {
  113645. disable: false
  113646. }
  113647. },
  113648. loadingScreen: {
  113649. html: babylonjs_viewer_assets_1.loadingScreen,
  113650. params: {
  113651. backgroundColor: "#000000",
  113652. loadingImage: images.loading
  113653. }
  113654. },
  113655. viewer: {
  113656. html: babylonjs_viewer_assets_1.defaultViewer,
  113657. params: {
  113658. enableDragAndDrop: false
  113659. }
  113660. },
  113661. navBar: {
  113662. html: babylonjs_viewer_assets_1.navbar,
  113663. params: {
  113664. speedList: {
  113665. "0.5x": "0.5",
  113666. "1.0x": "1.0",
  113667. "1.5x": "1.5",
  113668. "2.0x": "2.0",
  113669. },
  113670. logoImage: images.babylonLogo,
  113671. logoText: 'BabylonJS',
  113672. logoLink: 'https://babylonjs.com',
  113673. hideHelp: true,
  113674. hideHdButton: true,
  113675. disableOnFullscreen: false,
  113676. text: {
  113677. hdButton: "Toggle HD",
  113678. fullscreenButton: "Fullscreen",
  113679. helpButton: "Help"
  113680. }
  113681. },
  113682. events: {
  113683. pointerdown: {
  113684. '.navbar-control': true,
  113685. '.help-button': true
  113686. },
  113687. input: {
  113688. '.progress-wrapper': true
  113689. },
  113690. pointerup: {
  113691. '.progress-wrapper': true
  113692. }
  113693. }
  113694. },
  113695. overlay: {
  113696. html: babylonjs_viewer_assets_1.overlay,
  113697. params: {
  113698. closeImage: images.close,
  113699. closeText: 'Close'
  113700. }
  113701. },
  113702. help: {
  113703. html: babylonjs_viewer_assets_1.help
  113704. },
  113705. share: {
  113706. html: babylonjs_viewer_assets_1.share
  113707. },
  113708. error: {
  113709. html: babylonjs_viewer_assets_1.error
  113710. }
  113711. },
  113712. camera: {
  113713. behaviors: {
  113714. autoRotate: {
  113715. type: 0
  113716. },
  113717. framing: {
  113718. type: 2,
  113719. zoomOnBoundingInfo: true,
  113720. zoomStopsAnimation: false
  113721. },
  113722. bouncing: {
  113723. type: 1
  113724. }
  113725. }
  113726. },
  113727. skybox: {},
  113728. ground: {
  113729. receiveShadows: true
  113730. },
  113731. engine: {
  113732. antialiasing: true
  113733. },
  113734. scene: {}
  113735. };
  113736. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQUs7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osZUFBZSxFQUFFLFNBQVM7Z0JBQzFCLFlBQVksRUFBRSxNQUFN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eEIsU0FBUyxFQUFFLE9BQU87YUFDckI7U0FDSjtRQUNELElBQUksRUFBRTtZQUNGLElBQUksRUFBRSw4QkFBSTtTQUNiO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtLQUVKO0lBQ0QsTUFBTSxFQUFFO1FBQ0osU0FBUyxFQUFFO1lBQ1AsVUFBVSxFQUFFO2dCQUNSLElBQUksRUFBRSxDQUFDO2FBQ1Y7WUFDRCxPQUFPLEVBQUU7Z0JBQ0wsSUFBSSxFQUFFLENBQUM7Z0JBQ1Asa0JBQWtCLEVBQUUsSUFBSTtnQkFDeEIsa0JBQWtCLEVBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  113737. /***/ }),
  113738. /* 50 */
  113739. /***/ (function(module, exports, __webpack_require__) {
  113740. "use strict";
  113741. Object.defineProperty(exports, "__esModule", { value: true });
  113742. var babylonjs_1 = __webpack_require__(0);
  113743. /**
  113744. * The viewer's "extended" configuration.
  113745. * This configuration defines specific obejcts and parameters that we think make any model look good.
  113746. */
  113747. exports.extendedConfiguration = {
  113748. version: "3.2.0",
  113749. extends: "default",
  113750. camera: {
  113751. exposure: 3.034578,
  113752. fov: 0.7853981633974483,
  113753. contrast: 1.6,
  113754. toneMappingEnabled: true,
  113755. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  113756. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  113757. behaviors: {
  113758. framing: {
  113759. type: 2,
  113760. mode: 0,
  113761. positionScale: 0.5,
  113762. defaultElevation: 0.2617993877991494,
  113763. elevationReturnWaitTime: 3000,
  113764. elevationReturnTime: 2000,
  113765. framingTime: 500,
  113766. zoomStopsAnimation: false,
  113767. radiusScale: 0.866
  113768. },
  113769. autoRotate: {
  113770. type: 0,
  113771. idleRotationWaitTime: 4000,
  113772. idleRotationSpeed: 0.17453292519943295,
  113773. idleRotationSpinupTime: 2500,
  113774. zoomStopsAnimation: false
  113775. },
  113776. bouncing: {
  113777. type: 1,
  113778. lowerRadiusTransitionRange: 0.05,
  113779. upperRadiusTransitionRange: -0.2
  113780. }
  113781. },
  113782. upperRadiusLimit: 5,
  113783. lowerRadiusLimit: 0.5,
  113784. frameOnModelLoad: true,
  113785. framingElevation: 0.2617993877991494,
  113786. framingRotation: 1.5707963267948966,
  113787. radius: 2,
  113788. alpha: 1.5708,
  113789. beta: Math.PI * 0.5 - 0.2618,
  113790. wheelPrecision: 300,
  113791. minZ: 0.1,
  113792. maxZ: 50,
  113793. fovMode: 0,
  113794. pinchPrecision: 1500,
  113795. panningSensibility: 3000
  113796. },
  113797. lights: {
  113798. light0: {
  113799. type: 0,
  113800. frustumEdgeFalloff: 0,
  113801. intensity: 7,
  113802. intensityMode: 0,
  113803. radius: 0.6,
  113804. range: 0.6,
  113805. spotAngle: 60,
  113806. diffuse: {
  113807. r: 1,
  113808. g: 1,
  113809. b: 1
  113810. },
  113811. position: {
  113812. x: -2,
  113813. y: 2.5,
  113814. z: 2
  113815. },
  113816. target: {
  113817. x: 0,
  113818. y: 0,
  113819. z: 0
  113820. },
  113821. enabled: true,
  113822. shadowEnabled: true,
  113823. shadowBufferSize: 512,
  113824. shadowMinZ: 1,
  113825. shadowMaxZ: 10,
  113826. shadowFieldOfView: 60,
  113827. shadowFrustumSize: 2,
  113828. shadowConfig: {
  113829. useBlurCloseExponentialShadowMap: true,
  113830. useKernelBlur: true,
  113831. blurScale: 1.0,
  113832. bias: 0.001,
  113833. depthScale: 50 * (10 - 1),
  113834. frustumEdgeFalloff: 0
  113835. }
  113836. },
  113837. light1: {
  113838. type: 0,
  113839. frustumEdgeFalloff: 0,
  113840. intensity: 7,
  113841. intensityMode: 0,
  113842. radius: 0.4,
  113843. range: 0.4,
  113844. spotAngle: 57,
  113845. diffuse: {
  113846. r: 1,
  113847. g: 1,
  113848. b: 1
  113849. },
  113850. position: {
  113851. x: 4,
  113852. y: 3,
  113853. z: -0.5
  113854. },
  113855. target: {
  113856. x: 0,
  113857. y: 0,
  113858. z: 0
  113859. },
  113860. enabled: true,
  113861. shadowEnabled: false,
  113862. shadowBufferSize: 512,
  113863. shadowMinZ: 0.2,
  113864. shadowMaxZ: 10,
  113865. shadowFieldOfView: 28,
  113866. shadowFrustumSize: 2
  113867. },
  113868. light2: {
  113869. type: 0,
  113870. frustumEdgeFalloff: 0,
  113871. intensity: 1,
  113872. intensityMode: 0,
  113873. radius: 0.5,
  113874. range: 0.5,
  113875. spotAngle: 42.85,
  113876. diffuse: {
  113877. r: 0.8,
  113878. g: 0.8,
  113879. b: 0.8
  113880. },
  113881. position: {
  113882. x: -1,
  113883. y: 3,
  113884. z: -3
  113885. },
  113886. target: {
  113887. x: 0,
  113888. y: 0,
  113889. z: 0
  113890. },
  113891. enabled: true,
  113892. shadowEnabled: false,
  113893. shadowBufferSize: 512,
  113894. shadowMinZ: 0.2,
  113895. shadowMaxZ: 10,
  113896. shadowFieldOfView: 45,
  113897. shadowFrustumSize: 2
  113898. }
  113899. },
  113900. ground: {
  113901. shadowLevel: 0.9,
  113902. texture: "Ground_2.0-1024.png",
  113903. material: {
  113904. primaryColorHighlightLevel: 0.035,
  113905. primaryColorShadowLevel: 0,
  113906. enableNoise: true,
  113907. useRGBColor: false,
  113908. maxSimultaneousLights: 1,
  113909. diffuseTexture: {
  113910. gammaSpace: true
  113911. }
  113912. },
  113913. opacity: 1,
  113914. mirror: false,
  113915. receiveShadows: true,
  113916. size: 5
  113917. },
  113918. skybox: {
  113919. scale: 11,
  113920. cubeTexture: {
  113921. url: "Skybox_2.0-256.dds"
  113922. },
  113923. material: {
  113924. primaryColorHighlightLevel: 0.03,
  113925. primaryColorShadowLevel: 0.03,
  113926. enableNoise: true,
  113927. useRGBColor: false,
  113928. reflectionTexture: {
  113929. gammaSpace: true
  113930. }
  113931. }
  113932. },
  113933. engine: {
  113934. renderInBackground: true
  113935. },
  113936. scene: {
  113937. flags: {
  113938. shadowsEnabled: true,
  113939. particlesEnabled: false,
  113940. collisionsEnabled: false,
  113941. lightsEnabled: true,
  113942. texturesEnabled: true,
  113943. lensFlaresEnabled: false,
  113944. proceduralTexturesEnabled: false,
  113945. renderTargetsEnabled: true,
  113946. spritesEnabled: false,
  113947. skeletonsEnabled: true,
  113948. audioEnabled: false,
  113949. },
  113950. defaultMaterial: {
  113951. materialType: 'pbr',
  113952. reflectivityColor: {
  113953. r: 0.1,
  113954. g: 0.1,
  113955. b: 0.1
  113956. },
  113957. microSurface: 0.6
  113958. },
  113959. clearColor: {
  113960. r: 0.9,
  113961. g: 0.9,
  113962. b: 0.9,
  113963. a: 1.0
  113964. },
  113965. imageProcessingConfiguration: {
  113966. vignetteCentreX: 0,
  113967. vignetteCentreY: 0,
  113968. vignetteColor: {
  113969. r: 0.086,
  113970. g: 0.184,
  113971. b: 0.259,
  113972. a: 1
  113973. },
  113974. vignetteWeight: 0.855,
  113975. vignetteStretch: 0.5,
  113976. vignetteBlendMode: 0,
  113977. vignetteCameraFov: 0.7853981633974483,
  113978. isEnabled: true,
  113979. colorCurves: {
  113980. shadowsHue: 0,
  113981. shadowsDensity: 0,
  113982. shadowsSaturation: 0,
  113983. shadowsExposure: 0,
  113984. midtonesHue: 0,
  113985. midtonesDensity: 0,
  113986. midtonesExposure: 0,
  113987. midtonesSaturation: 0,
  113988. highlightsHue: 0,
  113989. highlightsDensity: 0,
  113990. highlightsExposure: 0,
  113991. highlightsSaturation: 0
  113992. }
  113993. },
  113994. mainColor: {
  113995. r: 0.8823529411764706,
  113996. g: 0.8823529411764706,
  113997. b: 0.8823529411764706
  113998. }
  113999. },
  114000. loaderPlugins: {
  114001. extendedMaterial: true,
  114002. applyMaterialConfig: true,
  114003. msftLod: true,
  114004. telemetry: true
  114005. },
  114006. model: {
  114007. rotationOffsetAxis: {
  114008. x: 0,
  114009. y: -1,
  114010. z: 0
  114011. },
  114012. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  114013. material: {
  114014. directEnabled: true,
  114015. directIntensity: 0.884,
  114016. emissiveIntensity: 1.04,
  114017. environmentIntensity: 0.6
  114018. },
  114019. entryAnimation: {
  114020. scaling: {
  114021. x: 0,
  114022. y: 0,
  114023. z: 0
  114024. },
  114025. time: 0.5,
  114026. easingFunction: 4,
  114027. easingMode: 1
  114028. },
  114029. exitAnimation: {
  114030. scaling: {
  114031. x: 0,
  114032. y: 0,
  114033. z: 0
  114034. },
  114035. time: 0.5,
  114036. easingFunction: 4,
  114037. easingMode: 1
  114038. },
  114039. normalize: true,
  114040. castShadow: true,
  114041. receiveShadows: true
  114042. },
  114043. lab: {
  114044. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  114045. environmentMap: {
  114046. texture: "EnvMap_2.0-256.env",
  114047. rotationY: 3,
  114048. tintLevel: 0.4
  114049. },
  114050. defaultRenderingPipelines: {
  114051. bloomEnabled: true,
  114052. bloomThreshold: 1.0,
  114053. fxaaEnabled: true,
  114054. bloomWeight: 0.05
  114055. }
  114056. }
  114057. };
  114058. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBL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BQ0QsSUFBSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELFNBQVMsRUFBRSxJQUFJO1FBQ2YsVUFBVSxFQUFFLElBQUk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  114059. /***/ }),
  114060. /* 51 */
  114061. /***/ (function(module, exports, __webpack_require__) {
  114062. "use strict";
  114063. Object.defineProperty(exports, "__esModule", { value: true });
  114064. /**
  114065. * Defines a default directional shadow light for normalized objects (!)
  114066. */
  114067. exports.shadowDirectionalLightConfiguration = {
  114068. model: {
  114069. receiveShadows: true,
  114070. castShadow: true
  114071. },
  114072. ground: {
  114073. receiveShadows: true
  114074. },
  114075. lights: {
  114076. shadowDirectionalLight: {
  114077. type: 1,
  114078. shadowEnabled: true,
  114079. target: { x: 0, y: 0, z: 0.5 },
  114080. position: { x: 1.49, y: 2.39, z: -1.33 },
  114081. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  114082. intensity: 4.887,
  114083. intensityMode: 0,
  114084. shadowBufferSize: 1024,
  114085. shadowFrustumSize: 6.0,
  114086. shadowFieldOfView: 50.977,
  114087. shadowMinZ: 0.1,
  114088. shadowMaxZ: 10.0,
  114089. shadowConfig: {
  114090. blurKernel: 32,
  114091. useBlurCloseExponentialShadowMap: true
  114092. }
  114093. }
  114094. }
  114095. };
  114096. /**
  114097. * Defines a default shadow-enabled spot light for normalized objects.
  114098. */
  114099. exports.shadowSpotlLightConfiguration = {
  114100. model: {
  114101. receiveShadows: true,
  114102. castShadow: true
  114103. },
  114104. ground: {
  114105. receiveShadows: true
  114106. },
  114107. lights: {
  114108. shadowSpotLight: {
  114109. type: 2,
  114110. intensity: 2,
  114111. shadowEnabled: true,
  114112. target: { x: 0, y: 0, z: 0.5 },
  114113. position: { x: 0, y: 3.5, z: 3.7 },
  114114. angle: 1,
  114115. shadowOrthoScale: 0.5,
  114116. shadowBufferSize: 1024,
  114117. shadowMinZ: 0.1,
  114118. shadowMaxZ: 50.0,
  114119. shadowConfig: {
  114120. frustumEdgeFalloff: 0.5,
  114121. blurKernel: 32,
  114122. useBlurExponentialShadowMap: true
  114123. }
  114124. }
  114125. }
  114126. };
  114127. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFF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FDLEVBQUUsR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  114128. /***/ }),
  114129. /* 52 */
  114130. /***/ (function(module, exports, __webpack_require__) {
  114131. "use strict";
  114132. Object.defineProperty(exports, "__esModule", { value: true });
  114133. /**
  114134. * Lab-oriented default .env support
  114135. */
  114136. exports.environmentMapConfiguration = {
  114137. lab: {
  114138. assetsRootURL: '/assets/environment/',
  114139. environmentMap: {
  114140. texture: 'EnvMap_2.0-256.env',
  114141. rotationY: 0,
  114142. tintLevel: 0.4
  114143. }
  114144. }
  114145. };
  114146. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  114147. /***/ }),
  114148. /* 53 */
  114149. /***/ (function(module, exports, __webpack_require__) {
  114150. "use strict";
  114151. Object.defineProperty(exports, "__esModule", { value: true });
  114152. var configuration_1 = __webpack_require__(11);
  114153. /**
  114154. * This function will make sure the configuration file is taking deprecated fields into account
  114155. * and is setting them to the correct keys and values.
  114156. *
  114157. * @param configuration The configuration to process. Mutable!
  114158. */
  114159. function processConfigurationCompatibility(configuration) {
  114160. if (configuration.camera) {
  114161. // camera contrast -> image processing contrast
  114162. if (configuration.camera.contrast !== undefined) {
  114163. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  114164. }
  114165. // camera exposure -> image processing exposure
  114166. if (configuration.camera.exposure !== undefined) {
  114167. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  114168. }
  114169. }
  114170. if (configuration.scene) {
  114171. //glow
  114172. if (configuration.scene.glow) {
  114173. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  114174. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  114175. if (enabledProcessing !== false) {
  114176. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  114177. }
  114178. }
  114179. }
  114180. }
  114181. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  114182. function setKeyInObject(object, keys, value, shouldOverwrite) {
  114183. var keySplit = keys.split(".");
  114184. if (keySplit.length === 0)
  114185. return;
  114186. var lastKey = keySplit.pop();
  114187. if (!lastKey)
  114188. return;
  114189. var curObj = object;
  114190. keySplit.forEach(function (key) {
  114191. curObj[key] = curObj[key] || {};
  114192. curObj = curObj[key];
  114193. });
  114194. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  114195. return;
  114196. curObj[lastKey] = value;
  114197. }
  114198. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbX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Q0FBQztBQTFCRCw4RUEwQkM7QUFFRCx3QkFBd0IsTUFBVyxFQUFFLElBQVksRUFBRSxLQUFVLEVBQUUsZUFBeUI7SUFDcEYsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUMvQixJQUFJLFFBQVEsQ0FBQyxNQUFNLEtBQUssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  114199. /***/ }),
  114200. /* 54 */
  114201. /***/ (function(module, exports, __webpack_require__) {
  114202. "use strict";
  114203. Object.defineProperty(exports, "__esModule", { value: true });
  114204. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  114205. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  114206. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  114207. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  114208. var applyMaterialConfig_1 = __webpack_require__(57);
  114209. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  114210. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  114211. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  114212. var babylonjs_1 = __webpack_require__(0);
  114213. var pluginCache = {};
  114214. /**
  114215. * Get a loader plugin according to its name.
  114216. * The plugin will be cached and will be reused if called for again.
  114217. *
  114218. * @param name the name of the plugin
  114219. */
  114220. function getLoaderPluginByName(name) {
  114221. if (!pluginCache[name]) {
  114222. switch (name) {
  114223. case 'telemetry':
  114224. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  114225. break;
  114226. case 'msftLod':
  114227. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  114228. break;
  114229. case 'applyMaterialConfig':
  114230. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  114231. break;
  114232. case 'extendedMaterial':
  114233. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  114234. break;
  114235. }
  114236. }
  114237. return pluginCache[name];
  114238. }
  114239. exports.getLoaderPluginByName = getLoaderPluginByName;
  114240. /**
  114241. *
  114242. */
  114243. function addLoaderPlugin(name, plugin) {
  114244. if (pluginCache[name]) {
  114245. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  114246. }
  114247. pluginCache[name] = plugin;
  114248. }
  114249. exports.addLoaderPlugin = addLoaderPlugin;
  114250. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXF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FO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  114251. /***/ }),
  114252. /* 55 */
  114253. /***/ (function(module, exports, __webpack_require__) {
  114254. "use strict";
  114255. Object.defineProperty(exports, "__esModule", { value: true });
  114256. var telemetryManager_1 = __webpack_require__(6);
  114257. var babylonjs_1 = __webpack_require__(0);
  114258. var TelemetryLoaderPlugin = /** @class */ (function () {
  114259. function TelemetryLoaderPlugin() {
  114260. }
  114261. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  114262. this._model = model;
  114263. this._loadStart = babylonjs_1.Tools.Now;
  114264. };
  114265. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  114266. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  114267. model: model,
  114268. loadTime: babylonjs_1.Tools.Now - this._loadStart
  114269. });
  114270. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  114271. };
  114272. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  114273. this._loadEnd = babylonjs_1.Tools.Now;
  114274. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  114275. model: this._model,
  114276. loadTime: this._loadEnd - this._loadStart
  114277. });
  114278. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  114279. };
  114280. TelemetryLoaderPlugin.prototype.onComplete = function () {
  114281. this._loadEnd = babylonjs_1.Tools.Now;
  114282. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  114283. model: this._model,
  114284. loadTime: this._loadEnd - this._loadStart
  114285. });
  114286. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  114287. };
  114288. return TelemetryLoaderPlugin;
  114289. }());
  114290. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  114291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LFdBQVcsRUFBRSxFQUFFO1lBQ2hFLEtBQUssRUFBRSxJQUFJLENBQUMsTUFBTTtZQUNsQixRQUFRLEVBQUUsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUMsVUFBVTtTQUM1QyxDQUFDLENBQUM7UUFFSCxtQ0FBZ0IsQ0FBQyxnQkFBZ0IsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  114292. /***/ }),
  114293. /* 56 */
  114294. /***/ (function(module, exports, __webpack_require__) {
  114295. "use strict";
  114296. Object.defineProperty(exports, "__esModule", { value: true });
  114297. /**
  114298. * A loder plugin to use MSFT_lod extension correctly (glTF)
  114299. */
  114300. var MSFTLodLoaderPlugin = /** @class */ (function () {
  114301. function MSFTLodLoaderPlugin() {
  114302. }
  114303. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  114304. this._model = model;
  114305. };
  114306. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  114307. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  114308. var MSFT_lod = extension;
  114309. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  114310. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  114311. }
  114312. };
  114313. return MSFTLodLoaderPlugin;
  114314. }());
  114315. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  114316. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  114317. /***/ }),
  114318. /* 57 */
  114319. /***/ (function(module, exports, __webpack_require__) {
  114320. "use strict";
  114321. Object.defineProperty(exports, "__esModule", { value: true });
  114322. /**
  114323. * Force-apply material configuration right after a material was loaded.
  114324. */
  114325. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  114326. function ApplyMaterialConfigPlugin() {
  114327. }
  114328. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  114329. this._model = model;
  114330. };
  114331. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  114332. this._model && this._model._applyModelMaterialConfiguration(material);
  114333. };
  114334. return ApplyMaterialConfigPlugin;
  114335. }());
  114336. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  114337. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  114338. /***/ }),
  114339. /* 58 */
  114340. /***/ (function(module, exports, __webpack_require__) {
  114341. "use strict";
  114342. Object.defineProperty(exports, "__esModule", { value: true });
  114343. var babylonjs_1 = __webpack_require__(0);
  114344. /**
  114345. * A (PBR) material will be extended using this function.
  114346. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  114347. */
  114348. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  114349. function ExtendedMaterialLoaderPlugin() {
  114350. }
  114351. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  114352. var material = baseMaterial;
  114353. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114354. };
  114355. return ExtendedMaterialLoaderPlugin;
  114356. }());
  114357. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  114358. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  114359. /***/ }),
  114360. /* 59 */
  114361. /***/ (function(module, exports, __webpack_require__) {
  114362. "use strict";
  114363. Object.defineProperty(exports, "__esModule", { value: true });
  114364. var babylonjs_1 = __webpack_require__(0);
  114365. var ObservablesManager = /** @class */ (function () {
  114366. function ObservablesManager() {
  114367. this.onSceneInitObservable = new babylonjs_1.Observable();
  114368. this.onEngineInitObservable = new babylonjs_1.Observable();
  114369. this.onModelLoadedObservable = new babylonjs_1.Observable();
  114370. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  114371. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  114372. this.onModelAddedObservable = new babylonjs_1.Observable();
  114373. this.onModelRemovedObservable = new babylonjs_1.Observable();
  114374. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  114375. this.onLoaderInitObservable = new babylonjs_1.Observable();
  114376. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  114377. }
  114378. ObservablesManager.prototype.dispose = function () {
  114379. this.onSceneInitObservable.clear();
  114380. this.onEngineInitObservable.clear();
  114381. this.onModelLoadedObservable.clear();
  114382. this.onModelLoadProgressObservable.clear();
  114383. this.onModelLoadErrorObservable.clear();
  114384. this.onModelAddedObservable.clear();
  114385. this.onModelRemovedObservable.clear();
  114386. this.onViewerInitDoneObservable.clear();
  114387. this.onLoaderInitObservable.clear();
  114388. this.onFrameRenderedObservable.clear();
  114389. };
  114390. return ObservablesManager;
  114391. }());
  114392. exports.ObservablesManager = ObservablesManager;
  114393. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL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BQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUN0QyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  114394. /***/ }),
  114395. /* 60 */
  114396. /***/ (function(module, exports, __webpack_require__) {
  114397. "use strict";
  114398. Object.defineProperty(exports, "__esModule", { value: true });
  114399. var babylonjs_1 = __webpack_require__(0);
  114400. var ConfigurationContainer = /** @class */ (function () {
  114401. function ConfigurationContainer() {
  114402. this.mainColor = babylonjs_1.Color3.White();
  114403. this.reflectionColor = babylonjs_1.Color3.White();
  114404. }
  114405. return ConfigurationContainer;
  114406. }());
  114407. exports.ConfigurationContainer = ConfigurationContainer;
  114408. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  114409. /***/ }),
  114410. /* 61 */
  114411. /***/ (function(module, exports, __webpack_require__) {
  114412. "use strict";
  114413. Object.defineProperty(exports, "__esModule", { value: true });
  114414. var babylonjs_1 = __webpack_require__(0);
  114415. var helper_1 = __webpack_require__(1);
  114416. var Handlebars = __webpack_require__(62);
  114417. var eventManager_1 = __webpack_require__(63);
  114418. var _1 = __webpack_require__(1);
  114419. /**
  114420. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  114421. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  114422. */
  114423. var TemplateManager = /** @class */ (function () {
  114424. function TemplateManager(containerElement) {
  114425. this.containerElement = containerElement;
  114426. this.templates = {};
  114427. this.onTemplateInit = new babylonjs_1.Observable();
  114428. this.onTemplateLoaded = new babylonjs_1.Observable();
  114429. this.onTemplateStateChange = new babylonjs_1.Observable();
  114430. this.onAllLoaded = new babylonjs_1.Observable();
  114431. this.onEventTriggered = new babylonjs_1.Observable();
  114432. this.eventManager = new eventManager_1.EventManager(this);
  114433. }
  114434. /**
  114435. * Initialize the template(s) for the viewer. Called bay the Viewer class
  114436. * @param templates the templates to be used to initialize the main template
  114437. */
  114438. TemplateManager.prototype.initTemplate = function (templates) {
  114439. var _this = this;
  114440. var internalInit = function (dependencyMap, name, parentTemplate) {
  114441. //init template
  114442. var template = _this.templates[name];
  114443. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  114444. return internalInit(dependencyMap[childName], childName, template);
  114445. });
  114446. // register the observers
  114447. //template.onLoaded.add(() => {
  114448. var addToParent = function () {
  114449. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  114450. template.appendTo(containingElement);
  114451. _this._checkLoadedState();
  114452. };
  114453. if (parentTemplate && !parentTemplate.parent) {
  114454. parentTemplate.onAppended.add(function () {
  114455. addToParent();
  114456. });
  114457. }
  114458. else {
  114459. addToParent();
  114460. }
  114461. //});
  114462. return template;
  114463. };
  114464. //build the html tree
  114465. return this._buildHTMLTree(templates).then(function (htmlTree) {
  114466. if (_this.templates['main']) {
  114467. internalInit(htmlTree, 'main');
  114468. }
  114469. else {
  114470. _this._checkLoadedState();
  114471. }
  114472. return;
  114473. });
  114474. };
  114475. /**
  114476. *
  114477. * This function will create a simple map with child-dependencies of the template html tree.
  114478. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  114479. * It is expected that the main template will be called main!
  114480. *
  114481. * @param templates
  114482. */
  114483. TemplateManager.prototype._buildHTMLTree = function (templates) {
  114484. var _this = this;
  114485. var promises = Object.keys(templates).map(function (name) {
  114486. // if the template was overridden
  114487. if (!templates[name])
  114488. return Promise.resolve(false);
  114489. // else - we have a template, let's do our job!
  114490. var template = new Template(name, templates[name]);
  114491. template.onLoaded.add(function () {
  114492. _this.onTemplateLoaded.notifyObservers(template);
  114493. });
  114494. template.onStateChange.add(function () {
  114495. _this.onTemplateStateChange.notifyObservers(template);
  114496. });
  114497. _this.onTemplateInit.notifyObservers(template);
  114498. // make sure the global onEventTriggered is called as well
  114499. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  114500. _this.templates[name] = template;
  114501. return template.initPromise;
  114502. });
  114503. return Promise.all(promises).then(function () {
  114504. var templateStructure = {};
  114505. // now iterate through all templates and check for children:
  114506. var buildTree = function (parentObject, name) {
  114507. _this.templates[name].isInHtmlTree = true;
  114508. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  114509. childNodes.forEach(function (element) {
  114510. parentObject[element] = {};
  114511. buildTree(parentObject[element], element);
  114512. });
  114513. };
  114514. if (_this.templates['main']) {
  114515. buildTree(templateStructure, "main");
  114516. }
  114517. return templateStructure;
  114518. });
  114519. };
  114520. /**
  114521. * Get the canvas in the template tree.
  114522. * There must be one and only one canvas inthe template.
  114523. */
  114524. TemplateManager.prototype.getCanvas = function () {
  114525. return this.containerElement.querySelector('canvas');
  114526. };
  114527. /**
  114528. * Get a specific template from the template tree
  114529. * @param name the name of the template to load
  114530. */
  114531. TemplateManager.prototype.getTemplate = function (name) {
  114532. return this.templates[name];
  114533. };
  114534. TemplateManager.prototype._checkLoadedState = function () {
  114535. var _this = this;
  114536. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  114537. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  114538. });
  114539. if (done) {
  114540. this.onAllLoaded.notifyObservers(this);
  114541. }
  114542. };
  114543. /**
  114544. * Dispose the template manager
  114545. */
  114546. TemplateManager.prototype.dispose = function () {
  114547. var _this = this;
  114548. // dispose all templates
  114549. Object.keys(this.templates).forEach(function (template) {
  114550. _this.templates[template].dispose();
  114551. });
  114552. this.templates = {};
  114553. this.eventManager.dispose();
  114554. this.onTemplateInit.clear();
  114555. this.onAllLoaded.clear();
  114556. this.onEventTriggered.clear();
  114557. this.onTemplateLoaded.clear();
  114558. this.onTemplateStateChange.clear();
  114559. };
  114560. return TemplateManager;
  114561. }());
  114562. exports.TemplateManager = TemplateManager;
  114563. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  114564. Handlebars.registerHelper('eachInMap', function (map, block) {
  114565. var out = '';
  114566. Object.keys(map).map(function (prop) {
  114567. var data = map[prop];
  114568. if (typeof data === 'object') {
  114569. data.id = data.id || prop;
  114570. out += block.fn(data);
  114571. }
  114572. else {
  114573. out += block.fn({ id: prop, value: data });
  114574. }
  114575. });
  114576. return out;
  114577. });
  114578. Handlebars.registerHelper('add', function (a, b) {
  114579. var out = a + b;
  114580. return out;
  114581. });
  114582. Handlebars.registerHelper('eq', function (a, b) {
  114583. var out = (a == b);
  114584. return out;
  114585. });
  114586. Handlebars.registerHelper('or', function (a, b) {
  114587. var out = a || b;
  114588. return out;
  114589. });
  114590. Handlebars.registerHelper('not', function (a) {
  114591. var out = !a;
  114592. return out;
  114593. });
  114594. Handlebars.registerHelper('count', function (map) {
  114595. return map.length;
  114596. });
  114597. Handlebars.registerHelper('gt', function (a, b) {
  114598. var out = a > b;
  114599. return out;
  114600. });
  114601. /**
  114602. * This class represents a single template in the viewer's template tree.
  114603. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  114604. * A template is injected using the template manager in the correct position.
  114605. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  114606. *
  114607. * For further information please refer to the documentation page, https://doc.babylonjs.com
  114608. */
  114609. var Template = /** @class */ (function () {
  114610. function Template(name, _configuration) {
  114611. var _this = this;
  114612. this.name = name;
  114613. this._configuration = _configuration;
  114614. this.onLoaded = new babylonjs_1.Observable();
  114615. this.onAppended = new babylonjs_1.Observable();
  114616. this.onStateChange = new babylonjs_1.Observable();
  114617. this.onEventTriggered = new babylonjs_1.Observable();
  114618. this.loadRequests = [];
  114619. this.isLoaded = false;
  114620. this.isShown = false;
  114621. this.isInHtmlTree = false;
  114622. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  114623. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  114624. if (htmlTemplate) {
  114625. _this._htmlTemplate = htmlTemplate;
  114626. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  114627. var config = _this._configuration.params || {};
  114628. _this._rawHtml = compiledTemplate(config);
  114629. try {
  114630. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  114631. }
  114632. catch (e) {
  114633. var test = document.createElement(_this.name);
  114634. test.innerHTML = _this._rawHtml;
  114635. _this._fragment = test;
  114636. }
  114637. _this.isLoaded = true;
  114638. _this.isShown = true;
  114639. _this.onLoaded.notifyObservers(_this);
  114640. }
  114641. return _this;
  114642. });
  114643. }
  114644. /**
  114645. * Some templates have parameters (like background color for example).
  114646. * The parameters are provided to Handlebars which in turn generates the template.
  114647. * This function will update the template with the new parameters
  114648. *
  114649. * Note that when updating parameters the events will be registered again (after being cleared).
  114650. *
  114651. * @param params the new template parameters
  114652. */
  114653. Template.prototype.updateParams = function (params, append) {
  114654. if (append === void 0) { append = true; }
  114655. if (append) {
  114656. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  114657. }
  114658. else {
  114659. this._configuration.params = params;
  114660. }
  114661. // update the template
  114662. if (this.isLoaded) {
  114663. // this.dispose();
  114664. }
  114665. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  114666. var config = this._configuration.params || {};
  114667. this._rawHtml = compiledTemplate(config);
  114668. try {
  114669. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  114670. }
  114671. catch (e) {
  114672. var test = document.createElement(this.name);
  114673. test.innerHTML = this._rawHtml;
  114674. this._fragment = test;
  114675. }
  114676. if (this.parent) {
  114677. this.appendTo(this.parent, true);
  114678. }
  114679. };
  114680. Object.defineProperty(Template.prototype, "configuration", {
  114681. /**
  114682. * Get the template'S configuration
  114683. */
  114684. get: function () {
  114685. return this._configuration;
  114686. },
  114687. enumerable: true,
  114688. configurable: true
  114689. });
  114690. /**
  114691. * A template can be a parent element for other templates or HTML elements.
  114692. * This function will deliver all child HTML elements of this template.
  114693. */
  114694. Template.prototype.getChildElements = function () {
  114695. var childrenArray = [];
  114696. //Edge and IE don't support frage,ent.children
  114697. var children = this._fragment && this._fragment.children;
  114698. if (!this._fragment) {
  114699. var fragment = this.parent.querySelector(this.name);
  114700. if (fragment) {
  114701. children = fragment.querySelectorAll('*');
  114702. }
  114703. }
  114704. if (!children) {
  114705. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  114706. children = this._fragment.querySelectorAll('*');
  114707. }
  114708. for (var i = 0; i < children.length; ++i) {
  114709. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  114710. }
  114711. return childrenArray;
  114712. };
  114713. /**
  114714. * Appending the template to a parent HTML element.
  114715. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  114716. * @param parent the parent to which the template is added
  114717. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  114718. */
  114719. Template.prototype.appendTo = function (parent, forceRemove) {
  114720. var _this = this;
  114721. if (this.parent) {
  114722. if (forceRemove && this._addedFragment) {
  114723. /*let fragement = this.parent.querySelector(this.name)
  114724. if (fragement)
  114725. this.parent.removeChild(fragement);*/
  114726. this.parent.innerHTML = '';
  114727. }
  114728. else {
  114729. return;
  114730. }
  114731. }
  114732. this.parent = parent;
  114733. if (this._configuration.id) {
  114734. this.parent.id = this._configuration.id;
  114735. }
  114736. if (this._fragment) {
  114737. this.parent.appendChild(this._fragment);
  114738. this._addedFragment = this._fragment;
  114739. }
  114740. else {
  114741. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  114742. }
  114743. // appended only one frame after.
  114744. setTimeout(function () {
  114745. _this._registerEvents();
  114746. _this.onAppended.notifyObservers(_this);
  114747. });
  114748. };
  114749. /**
  114750. * Show the template using the provided visibilityFunction, or natively using display: flex.
  114751. * The provided function returns a promise that should be fullfilled when the element is shown.
  114752. * Since it is a promise async operations are more than possible.
  114753. * See the default viewer for an opacity example.
  114754. * @param visibilityFunction The function to execute to show the template.
  114755. */
  114756. Template.prototype.show = function (visibilityFunction) {
  114757. var _this = this;
  114758. if (this._isHiding)
  114759. return Promise.resolve(this);
  114760. return Promise.resolve().then(function () {
  114761. _this._isShowing = true;
  114762. if (visibilityFunction) {
  114763. return visibilityFunction(_this);
  114764. }
  114765. else {
  114766. // flex? box? should this be configurable easier than the visibilityFunction?
  114767. _this.parent.style.display = 'flex';
  114768. // support old browsers with no flex:
  114769. if (_this.parent.style.display !== 'flex') {
  114770. _this.parent.style.display = '';
  114771. }
  114772. return _this;
  114773. }
  114774. }).then(function () {
  114775. _this.isShown = true;
  114776. _this._isShowing = false;
  114777. _this.onStateChange.notifyObservers(_this);
  114778. return _this;
  114779. });
  114780. };
  114781. /**
  114782. * Hide the template using the provided visibilityFunction, or natively using display: none.
  114783. * The provided function returns a promise that should be fullfilled when the element is hidden.
  114784. * Since it is a promise async operations are more than possible.
  114785. * See the default viewer for an opacity example.
  114786. * @param visibilityFunction The function to execute to show the template.
  114787. */
  114788. Template.prototype.hide = function (visibilityFunction) {
  114789. var _this = this;
  114790. if (this._isShowing)
  114791. return Promise.resolve(this);
  114792. return Promise.resolve().then(function () {
  114793. _this._isHiding = true;
  114794. if (visibilityFunction) {
  114795. return visibilityFunction(_this);
  114796. }
  114797. else {
  114798. // flex? box? should this be configurable easier than the visibilityFunction?
  114799. _this.parent.style.display = 'none';
  114800. return _this;
  114801. }
  114802. }).then(function () {
  114803. _this.isShown = false;
  114804. _this._isHiding = false;
  114805. _this.onStateChange.notifyObservers(_this);
  114806. return _this;
  114807. });
  114808. };
  114809. /**
  114810. * Dispose this template
  114811. */
  114812. Template.prototype.dispose = function () {
  114813. this.onAppended.clear();
  114814. this.onEventTriggered.clear();
  114815. this.onLoaded.clear();
  114816. this.onStateChange.clear();
  114817. this.isLoaded = false;
  114818. // remove from parent
  114819. try {
  114820. this.parent.removeChild(this._fragment);
  114821. }
  114822. catch (e) {
  114823. //noop
  114824. }
  114825. this.loadRequests.forEach(function (request) {
  114826. request.abort();
  114827. });
  114828. if (this._registeredEvents) {
  114829. this._registeredEvents.forEach(function (evt) {
  114830. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114831. });
  114832. }
  114833. delete this._fragment;
  114834. };
  114835. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  114836. var _this = this;
  114837. if (!templateConfig) {
  114838. return Promise.reject('No templateConfig provided');
  114839. }
  114840. else if (templateConfig.html) {
  114841. return Promise.resolve(templateConfig.html);
  114842. }
  114843. else {
  114844. var location_1 = this._getTemplateLocation(templateConfig);
  114845. if (helper_1.isUrl(location_1)) {
  114846. return new Promise(function (resolve, reject) {
  114847. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  114848. resolve(data);
  114849. }, undefined, undefined, false, function (request, error) {
  114850. reject(error);
  114851. });
  114852. _this.loadRequests.push(fileRequest);
  114853. });
  114854. }
  114855. else {
  114856. location_1 = location_1.replace('#', '');
  114857. var element = document.getElementById(location_1);
  114858. if (element) {
  114859. return Promise.resolve(element.innerHTML);
  114860. }
  114861. else {
  114862. return Promise.reject('Template ID not found');
  114863. }
  114864. }
  114865. }
  114866. };
  114867. Template.prototype._registerEvents = function () {
  114868. var _this = this;
  114869. this._registeredEvents = this._registeredEvents || [];
  114870. if (this._registeredEvents.length) {
  114871. // first remove the registered events
  114872. this._registeredEvents.forEach(function (evt) {
  114873. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114874. });
  114875. }
  114876. if (this._configuration.events) {
  114877. var _loop_1 = function (eventName) {
  114878. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  114879. var functionToFire_1 = function (selector, event) {
  114880. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  114881. };
  114882. // if boolean, set the parent as the event listener
  114883. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  114884. var selector = this_1.parent.id;
  114885. if (selector) {
  114886. selector = '#' + selector;
  114887. }
  114888. else {
  114889. selector = this_1.parent.tagName;
  114890. }
  114891. var binding = functionToFire_1.bind(this_1, selector);
  114892. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  114893. this_1._registeredEvents.push({
  114894. htmlElement: this_1.parent,
  114895. eventName: eventName,
  114896. function: binding
  114897. });
  114898. }
  114899. else if (typeof this_1._configuration.events[eventName] === 'object') {
  114900. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  114901. // strict null checl is working incorrectly, must override:
  114902. var event_1 = this_1._configuration.events[eventName] || {};
  114903. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  114904. var htmlElement = _this.parent.querySelector(selector);
  114905. if (!htmlElement) {
  114906. // backcompat, fallback to id
  114907. if (selector && selector.indexOf('#') !== 0) {
  114908. selector = '#' + selector;
  114909. }
  114910. try {
  114911. htmlElement = _this.parent.querySelector(selector);
  114912. }
  114913. catch (e) { }
  114914. }
  114915. if (htmlElement) {
  114916. var binding = functionToFire_1.bind(_this, selector);
  114917. htmlElement.addEventListener(eventName, binding, false);
  114918. _this._registeredEvents.push({
  114919. htmlElement: htmlElement,
  114920. eventName: eventName,
  114921. function: binding
  114922. });
  114923. }
  114924. });
  114925. }
  114926. }
  114927. };
  114928. var this_1 = this;
  114929. for (var eventName in this._configuration.events) {
  114930. _loop_1(eventName);
  114931. }
  114932. }
  114933. };
  114934. Template.prototype._getTemplateLocation = function (templateConfig) {
  114935. if (!templateConfig || typeof templateConfig === 'string') {
  114936. return templateConfig;
  114937. }
  114938. else {
  114939. return templateConfig.location;
  114940. }
  114941. };
  114942. return Template;
  114943. }());
  114944. exports.Template = Template;
  114945. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZ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Q0FBQyxDQUFDLENBQUM7cUJBQ047aUJBQ0o7WUFDTCxDQUFDOztZQWhERCxLQUFLLElBQUksU0FBUyxJQUFJLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTTt3QkFBdkMsU0FBUzthQWdEakI7U0FDSjtJQUNMLENBQUM7SUFFTyx1Q0FBb0IsR0FBNUIsVUFBNkIsY0FBYztRQUN2QyxJQUFJLENBQUMsY0FBYyxJQUFJLE9BQU8sY0FBYyxLQUFLLFFBQVEsRUFBRTtZQUN2RCxPQUFPLGNBQWMsQ0FBQztTQUN6QjthQUFNO1lBQ0gsT0FBTyxjQUFjLENBQUMsUUFBUSxDQUFDO1NBQ2xDO0lBQ0wsQ0FBQztJQUNMLGVBQUM7QUFBRCxDQUFDLEFBclhELElBcVhDO0FBclhZLDRCQUFRIn0=
  114946. /***/ }),
  114947. /* 62 */
  114948. /***/ (function(module, exports, __webpack_require__) {
  114949. /**!
  114950. @license
  114951. handlebars v4.0.11
  114952. Copyright (C) 2011-2017 by Yehuda Katz
  114953. Permission is hereby granted, free of charge, to any person obtaining a copy
  114954. of this software and associated documentation files (the "Software"), to deal
  114955. in the Software without restriction, including without limitation the rights
  114956. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  114957. copies of the Software, and to permit persons to whom the Software is
  114958. furnished to do so, subject to the following conditions:
  114959. The above copyright notice and this permission notice shall be included in
  114960. all copies or substantial portions of the Software.
  114961. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  114962. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  114963. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  114964. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  114965. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  114966. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  114967. THE SOFTWARE.
  114968. */
  114969. (function webpackUniversalModuleDefinition(root, factory) {
  114970. if(true)
  114971. module.exports = factory();
  114972. else if(typeof define === 'function' && define.amd)
  114973. define([], factory);
  114974. else if(typeof exports === 'object')
  114975. exports["Handlebars"] = factory();
  114976. else
  114977. root["Handlebars"] = factory();
  114978. })(this, function() {
  114979. return /******/ (function(modules) { // webpackBootstrap
  114980. /******/ // The module cache
  114981. /******/ var installedModules = {};
  114982. /******/ // The require function
  114983. /******/ function __webpack_require__(moduleId) {
  114984. /******/ // Check if module is in cache
  114985. /******/ if(installedModules[moduleId])
  114986. /******/ return installedModules[moduleId].exports;
  114987. /******/ // Create a new module (and put it into the cache)
  114988. /******/ var module = installedModules[moduleId] = {
  114989. /******/ exports: {},
  114990. /******/ id: moduleId,
  114991. /******/ loaded: false
  114992. /******/ };
  114993. /******/ // Execute the module function
  114994. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  114995. /******/ // Flag the module as loaded
  114996. /******/ module.loaded = true;
  114997. /******/ // Return the exports of the module
  114998. /******/ return module.exports;
  114999. /******/ }
  115000. /******/ // expose the modules object (__webpack_modules__)
  115001. /******/ __webpack_require__.m = modules;
  115002. /******/ // expose the module cache
  115003. /******/ __webpack_require__.c = installedModules;
  115004. /******/ // __webpack_public_path__
  115005. /******/ __webpack_require__.p = "";
  115006. /******/ // Load entry module and return exports
  115007. /******/ return __webpack_require__(0);
  115008. /******/ })
  115009. /************************************************************************/
  115010. /******/ ([
  115011. /* 0 */
  115012. /***/ (function(module, exports, __webpack_require__) {
  115013. 'use strict';
  115014. var _interopRequireDefault = __webpack_require__(1)['default'];
  115015. exports.__esModule = true;
  115016. var _handlebarsRuntime = __webpack_require__(2);
  115017. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  115018. // Compiler imports
  115019. var _handlebarsCompilerAst = __webpack_require__(35);
  115020. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  115021. var _handlebarsCompilerBase = __webpack_require__(36);
  115022. var _handlebarsCompilerCompiler = __webpack_require__(41);
  115023. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  115024. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  115025. var _handlebarsCompilerVisitor = __webpack_require__(39);
  115026. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  115027. var _handlebarsNoConflict = __webpack_require__(34);
  115028. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  115029. var _create = _handlebarsRuntime2['default'].create;
  115030. function create() {
  115031. var hb = _create();
  115032. hb.compile = function (input, options) {
  115033. return _handlebarsCompilerCompiler.compile(input, options, hb);
  115034. };
  115035. hb.precompile = function (input, options) {
  115036. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  115037. };
  115038. hb.AST = _handlebarsCompilerAst2['default'];
  115039. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  115040. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  115041. hb.Parser = _handlebarsCompilerBase.parser;
  115042. hb.parse = _handlebarsCompilerBase.parse;
  115043. return hb;
  115044. }
  115045. var inst = create();
  115046. inst.create = create;
  115047. _handlebarsNoConflict2['default'](inst);
  115048. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  115049. inst['default'] = inst;
  115050. exports['default'] = inst;
  115051. module.exports = exports['default'];
  115052. /***/ }),
  115053. /* 1 */
  115054. /***/ (function(module, exports) {
  115055. "use strict";
  115056. exports["default"] = function (obj) {
  115057. return obj && obj.__esModule ? obj : {
  115058. "default": obj
  115059. };
  115060. };
  115061. exports.__esModule = true;
  115062. /***/ }),
  115063. /* 2 */
  115064. /***/ (function(module, exports, __webpack_require__) {
  115065. 'use strict';
  115066. var _interopRequireWildcard = __webpack_require__(3)['default'];
  115067. var _interopRequireDefault = __webpack_require__(1)['default'];
  115068. exports.__esModule = true;
  115069. var _handlebarsBase = __webpack_require__(4);
  115070. var base = _interopRequireWildcard(_handlebarsBase);
  115071. // Each of these augment the Handlebars object. No need to setup here.
  115072. // (This is done to easily share code between commonjs and browse envs)
  115073. var _handlebarsSafeString = __webpack_require__(21);
  115074. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  115075. var _handlebarsException = __webpack_require__(6);
  115076. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  115077. var _handlebarsUtils = __webpack_require__(5);
  115078. var Utils = _interopRequireWildcard(_handlebarsUtils);
  115079. var _handlebarsRuntime = __webpack_require__(22);
  115080. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  115081. var _handlebarsNoConflict = __webpack_require__(34);
  115082. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  115083. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  115084. function create() {
  115085. var hb = new base.HandlebarsEnvironment();
  115086. Utils.extend(hb, base);
  115087. hb.SafeString = _handlebarsSafeString2['default'];
  115088. hb.Exception = _handlebarsException2['default'];
  115089. hb.Utils = Utils;
  115090. hb.escapeExpression = Utils.escapeExpression;
  115091. hb.VM = runtime;
  115092. hb.template = function (spec) {
  115093. return runtime.template(spec, hb);
  115094. };
  115095. return hb;
  115096. }
  115097. var inst = create();
  115098. inst.create = create;
  115099. _handlebarsNoConflict2['default'](inst);
  115100. inst['default'] = inst;
  115101. exports['default'] = inst;
  115102. module.exports = exports['default'];
  115103. /***/ }),
  115104. /* 3 */
  115105. /***/ (function(module, exports) {
  115106. "use strict";
  115107. exports["default"] = function (obj) {
  115108. if (obj && obj.__esModule) {
  115109. return obj;
  115110. } else {
  115111. var newObj = {};
  115112. if (obj != null) {
  115113. for (var key in obj) {
  115114. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  115115. }
  115116. }
  115117. newObj["default"] = obj;
  115118. return newObj;
  115119. }
  115120. };
  115121. exports.__esModule = true;
  115122. /***/ }),
  115123. /* 4 */
  115124. /***/ (function(module, exports, __webpack_require__) {
  115125. 'use strict';
  115126. var _interopRequireDefault = __webpack_require__(1)['default'];
  115127. exports.__esModule = true;
  115128. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  115129. var _utils = __webpack_require__(5);
  115130. var _exception = __webpack_require__(6);
  115131. var _exception2 = _interopRequireDefault(_exception);
  115132. var _helpers = __webpack_require__(10);
  115133. var _decorators = __webpack_require__(18);
  115134. var _logger = __webpack_require__(20);
  115135. var _logger2 = _interopRequireDefault(_logger);
  115136. var VERSION = '4.0.11';
  115137. exports.VERSION = VERSION;
  115138. var COMPILER_REVISION = 7;
  115139. exports.COMPILER_REVISION = COMPILER_REVISION;
  115140. var REVISION_CHANGES = {
  115141. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  115142. 2: '== 1.0.0-rc.3',
  115143. 3: '== 1.0.0-rc.4',
  115144. 4: '== 1.x.x',
  115145. 5: '== 2.0.0-alpha.x',
  115146. 6: '>= 2.0.0-beta.1',
  115147. 7: '>= 4.0.0'
  115148. };
  115149. exports.REVISION_CHANGES = REVISION_CHANGES;
  115150. var objectType = '[object Object]';
  115151. function HandlebarsEnvironment(helpers, partials, decorators) {
  115152. this.helpers = helpers || {};
  115153. this.partials = partials || {};
  115154. this.decorators = decorators || {};
  115155. _helpers.registerDefaultHelpers(this);
  115156. _decorators.registerDefaultDecorators(this);
  115157. }
  115158. HandlebarsEnvironment.prototype = {
  115159. constructor: HandlebarsEnvironment,
  115160. logger: _logger2['default'],
  115161. log: _logger2['default'].log,
  115162. registerHelper: function registerHelper(name, fn) {
  115163. if (_utils.toString.call(name) === objectType) {
  115164. if (fn) {
  115165. throw new _exception2['default']('Arg not supported with multiple helpers');
  115166. }
  115167. _utils.extend(this.helpers, name);
  115168. } else {
  115169. this.helpers[name] = fn;
  115170. }
  115171. },
  115172. unregisterHelper: function unregisterHelper(name) {
  115173. delete this.helpers[name];
  115174. },
  115175. registerPartial: function registerPartial(name, partial) {
  115176. if (_utils.toString.call(name) === objectType) {
  115177. _utils.extend(this.partials, name);
  115178. } else {
  115179. if (typeof partial === 'undefined') {
  115180. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  115181. }
  115182. this.partials[name] = partial;
  115183. }
  115184. },
  115185. unregisterPartial: function unregisterPartial(name) {
  115186. delete this.partials[name];
  115187. },
  115188. registerDecorator: function registerDecorator(name, fn) {
  115189. if (_utils.toString.call(name) === objectType) {
  115190. if (fn) {
  115191. throw new _exception2['default']('Arg not supported with multiple decorators');
  115192. }
  115193. _utils.extend(this.decorators, name);
  115194. } else {
  115195. this.decorators[name] = fn;
  115196. }
  115197. },
  115198. unregisterDecorator: function unregisterDecorator(name) {
  115199. delete this.decorators[name];
  115200. }
  115201. };
  115202. var log = _logger2['default'].log;
  115203. exports.log = log;
  115204. exports.createFrame = _utils.createFrame;
  115205. exports.logger = _logger2['default'];
  115206. /***/ }),
  115207. /* 5 */
  115208. /***/ (function(module, exports) {
  115209. 'use strict';
  115210. exports.__esModule = true;
  115211. exports.extend = extend;
  115212. exports.indexOf = indexOf;
  115213. exports.escapeExpression = escapeExpression;
  115214. exports.isEmpty = isEmpty;
  115215. exports.createFrame = createFrame;
  115216. exports.blockParams = blockParams;
  115217. exports.appendContextPath = appendContextPath;
  115218. var escape = {
  115219. '&': '&amp;',
  115220. '<': '&lt;',
  115221. '>': '&gt;',
  115222. '"': '&quot;',
  115223. "'": '&#x27;',
  115224. '`': '&#x60;',
  115225. '=': '&#x3D;'
  115226. };
  115227. var badChars = /[&<>"'`=]/g,
  115228. possible = /[&<>"'`=]/;
  115229. function escapeChar(chr) {
  115230. return escape[chr];
  115231. }
  115232. function extend(obj /* , ...source */) {
  115233. for (var i = 1; i < arguments.length; i++) {
  115234. for (var key in arguments[i]) {
  115235. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  115236. obj[key] = arguments[i][key];
  115237. }
  115238. }
  115239. }
  115240. return obj;
  115241. }
  115242. var toString = Object.prototype.toString;
  115243. exports.toString = toString;
  115244. // Sourced from lodash
  115245. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  115246. /* eslint-disable func-style */
  115247. var isFunction = function isFunction(value) {
  115248. return typeof value === 'function';
  115249. };
  115250. // fallback for older versions of Chrome and Safari
  115251. /* istanbul ignore next */
  115252. if (isFunction(/x/)) {
  115253. exports.isFunction = isFunction = function (value) {
  115254. return typeof value === 'function' && toString.call(value) === '[object Function]';
  115255. };
  115256. }
  115257. exports.isFunction = isFunction;
  115258. /* eslint-enable func-style */
  115259. /* istanbul ignore next */
  115260. var isArray = Array.isArray || function (value) {
  115261. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  115262. };
  115263. exports.isArray = isArray;
  115264. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  115265. function indexOf(array, value) {
  115266. for (var i = 0, len = array.length; i < len; i++) {
  115267. if (array[i] === value) {
  115268. return i;
  115269. }
  115270. }
  115271. return -1;
  115272. }
  115273. function escapeExpression(string) {
  115274. if (typeof string !== 'string') {
  115275. // don't escape SafeStrings, since they're already safe
  115276. if (string && string.toHTML) {
  115277. return string.toHTML();
  115278. } else if (string == null) {
  115279. return '';
  115280. } else if (!string) {
  115281. return string + '';
  115282. }
  115283. // Force a string conversion as this will be done by the append regardless and
  115284. // the regex test will do this transparently behind the scenes, causing issues if
  115285. // an object's to string has escaped characters in it.
  115286. string = '' + string;
  115287. }
  115288. if (!possible.test(string)) {
  115289. return string;
  115290. }
  115291. return string.replace(badChars, escapeChar);
  115292. }
  115293. function isEmpty(value) {
  115294. if (!value && value !== 0) {
  115295. return true;
  115296. } else if (isArray(value) && value.length === 0) {
  115297. return true;
  115298. } else {
  115299. return false;
  115300. }
  115301. }
  115302. function createFrame(object) {
  115303. var frame = extend({}, object);
  115304. frame._parent = object;
  115305. return frame;
  115306. }
  115307. function blockParams(params, ids) {
  115308. params.path = ids;
  115309. return params;
  115310. }
  115311. function appendContextPath(contextPath, id) {
  115312. return (contextPath ? contextPath + '.' : '') + id;
  115313. }
  115314. /***/ }),
  115315. /* 6 */
  115316. /***/ (function(module, exports, __webpack_require__) {
  115317. 'use strict';
  115318. var _Object$defineProperty = __webpack_require__(7)['default'];
  115319. exports.__esModule = true;
  115320. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  115321. function Exception(message, node) {
  115322. var loc = node && node.loc,
  115323. line = undefined,
  115324. column = undefined;
  115325. if (loc) {
  115326. line = loc.start.line;
  115327. column = loc.start.column;
  115328. message += ' - ' + line + ':' + column;
  115329. }
  115330. var tmp = Error.prototype.constructor.call(this, message);
  115331. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  115332. for (var idx = 0; idx < errorProps.length; idx++) {
  115333. this[errorProps[idx]] = tmp[errorProps[idx]];
  115334. }
  115335. /* istanbul ignore else */
  115336. if (Error.captureStackTrace) {
  115337. Error.captureStackTrace(this, Exception);
  115338. }
  115339. try {
  115340. if (loc) {
  115341. this.lineNumber = line;
  115342. // Work around issue under safari where we can't directly set the column value
  115343. /* istanbul ignore next */
  115344. if (_Object$defineProperty) {
  115345. Object.defineProperty(this, 'column', {
  115346. value: column,
  115347. enumerable: true
  115348. });
  115349. } else {
  115350. this.column = column;
  115351. }
  115352. }
  115353. } catch (nop) {
  115354. /* Ignore if the browser is very particular */
  115355. }
  115356. }
  115357. Exception.prototype = new Error();
  115358. exports['default'] = Exception;
  115359. module.exports = exports['default'];
  115360. /***/ }),
  115361. /* 7 */
  115362. /***/ (function(module, exports, __webpack_require__) {
  115363. module.exports = { "default": __webpack_require__(8), __esModule: true };
  115364. /***/ }),
  115365. /* 8 */
  115366. /***/ (function(module, exports, __webpack_require__) {
  115367. var $ = __webpack_require__(9);
  115368. module.exports = function defineProperty(it, key, desc){
  115369. return $.setDesc(it, key, desc);
  115370. };
  115371. /***/ }),
  115372. /* 9 */
  115373. /***/ (function(module, exports) {
  115374. var $Object = Object;
  115375. module.exports = {
  115376. create: $Object.create,
  115377. getProto: $Object.getPrototypeOf,
  115378. isEnum: {}.propertyIsEnumerable,
  115379. getDesc: $Object.getOwnPropertyDescriptor,
  115380. setDesc: $Object.defineProperty,
  115381. setDescs: $Object.defineProperties,
  115382. getKeys: $Object.keys,
  115383. getNames: $Object.getOwnPropertyNames,
  115384. getSymbols: $Object.getOwnPropertySymbols,
  115385. each: [].forEach
  115386. };
  115387. /***/ }),
  115388. /* 10 */
  115389. /***/ (function(module, exports, __webpack_require__) {
  115390. 'use strict';
  115391. var _interopRequireDefault = __webpack_require__(1)['default'];
  115392. exports.__esModule = true;
  115393. exports.registerDefaultHelpers = registerDefaultHelpers;
  115394. var _helpersBlockHelperMissing = __webpack_require__(11);
  115395. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  115396. var _helpersEach = __webpack_require__(12);
  115397. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  115398. var _helpersHelperMissing = __webpack_require__(13);
  115399. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  115400. var _helpersIf = __webpack_require__(14);
  115401. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  115402. var _helpersLog = __webpack_require__(15);
  115403. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  115404. var _helpersLookup = __webpack_require__(16);
  115405. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  115406. var _helpersWith = __webpack_require__(17);
  115407. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  115408. function registerDefaultHelpers(instance) {
  115409. _helpersBlockHelperMissing2['default'](instance);
  115410. _helpersEach2['default'](instance);
  115411. _helpersHelperMissing2['default'](instance);
  115412. _helpersIf2['default'](instance);
  115413. _helpersLog2['default'](instance);
  115414. _helpersLookup2['default'](instance);
  115415. _helpersWith2['default'](instance);
  115416. }
  115417. /***/ }),
  115418. /* 11 */
  115419. /***/ (function(module, exports, __webpack_require__) {
  115420. 'use strict';
  115421. exports.__esModule = true;
  115422. var _utils = __webpack_require__(5);
  115423. exports['default'] = function (instance) {
  115424. instance.registerHelper('blockHelperMissing', function (context, options) {
  115425. var inverse = options.inverse,
  115426. fn = options.fn;
  115427. if (context === true) {
  115428. return fn(this);
  115429. } else if (context === false || context == null) {
  115430. return inverse(this);
  115431. } else if (_utils.isArray(context)) {
  115432. if (context.length > 0) {
  115433. if (options.ids) {
  115434. options.ids = [options.name];
  115435. }
  115436. return instance.helpers.each(context, options);
  115437. } else {
  115438. return inverse(this);
  115439. }
  115440. } else {
  115441. if (options.data && options.ids) {
  115442. var data = _utils.createFrame(options.data);
  115443. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  115444. options = { data: data };
  115445. }
  115446. return fn(context, options);
  115447. }
  115448. });
  115449. };
  115450. module.exports = exports['default'];
  115451. /***/ }),
  115452. /* 12 */
  115453. /***/ (function(module, exports, __webpack_require__) {
  115454. 'use strict';
  115455. var _interopRequireDefault = __webpack_require__(1)['default'];
  115456. exports.__esModule = true;
  115457. var _utils = __webpack_require__(5);
  115458. var _exception = __webpack_require__(6);
  115459. var _exception2 = _interopRequireDefault(_exception);
  115460. exports['default'] = function (instance) {
  115461. instance.registerHelper('each', function (context, options) {
  115462. if (!options) {
  115463. throw new _exception2['default']('Must pass iterator to #each');
  115464. }
  115465. var fn = options.fn,
  115466. inverse = options.inverse,
  115467. i = 0,
  115468. ret = '',
  115469. data = undefined,
  115470. contextPath = undefined;
  115471. if (options.data && options.ids) {
  115472. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  115473. }
  115474. if (_utils.isFunction(context)) {
  115475. context = context.call(this);
  115476. }
  115477. if (options.data) {
  115478. data = _utils.createFrame(options.data);
  115479. }
  115480. function execIteration(field, index, last) {
  115481. if (data) {
  115482. data.key = field;
  115483. data.index = index;
  115484. data.first = index === 0;
  115485. data.last = !!last;
  115486. if (contextPath) {
  115487. data.contextPath = contextPath + field;
  115488. }
  115489. }
  115490. ret = ret + fn(context[field], {
  115491. data: data,
  115492. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  115493. });
  115494. }
  115495. if (context && typeof context === 'object') {
  115496. if (_utils.isArray(context)) {
  115497. for (var j = context.length; i < j; i++) {
  115498. if (i in context) {
  115499. execIteration(i, i, i === context.length - 1);
  115500. }
  115501. }
  115502. } else {
  115503. var priorKey = undefined;
  115504. for (var key in context) {
  115505. if (context.hasOwnProperty(key)) {
  115506. // We're running the iterations one step out of sync so we can detect
  115507. // the last iteration without have to scan the object twice and create
  115508. // an itermediate keys array.
  115509. if (priorKey !== undefined) {
  115510. execIteration(priorKey, i - 1);
  115511. }
  115512. priorKey = key;
  115513. i++;
  115514. }
  115515. }
  115516. if (priorKey !== undefined) {
  115517. execIteration(priorKey, i - 1, true);
  115518. }
  115519. }
  115520. }
  115521. if (i === 0) {
  115522. ret = inverse(this);
  115523. }
  115524. return ret;
  115525. });
  115526. };
  115527. module.exports = exports['default'];
  115528. /***/ }),
  115529. /* 13 */
  115530. /***/ (function(module, exports, __webpack_require__) {
  115531. 'use strict';
  115532. var _interopRequireDefault = __webpack_require__(1)['default'];
  115533. exports.__esModule = true;
  115534. var _exception = __webpack_require__(6);
  115535. var _exception2 = _interopRequireDefault(_exception);
  115536. exports['default'] = function (instance) {
  115537. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  115538. if (arguments.length === 1) {
  115539. // A missing field in a {{foo}} construct.
  115540. return undefined;
  115541. } else {
  115542. // Someone is actually trying to call something, blow up.
  115543. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  115544. }
  115545. });
  115546. };
  115547. module.exports = exports['default'];
  115548. /***/ }),
  115549. /* 14 */
  115550. /***/ (function(module, exports, __webpack_require__) {
  115551. 'use strict';
  115552. exports.__esModule = true;
  115553. var _utils = __webpack_require__(5);
  115554. exports['default'] = function (instance) {
  115555. instance.registerHelper('if', function (conditional, options) {
  115556. if (_utils.isFunction(conditional)) {
  115557. conditional = conditional.call(this);
  115558. }
  115559. // Default behavior is to render the positive path if the value is truthy and not empty.
  115560. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  115561. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  115562. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  115563. return options.inverse(this);
  115564. } else {
  115565. return options.fn(this);
  115566. }
  115567. });
  115568. instance.registerHelper('unless', function (conditional, options) {
  115569. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  115570. });
  115571. };
  115572. module.exports = exports['default'];
  115573. /***/ }),
  115574. /* 15 */
  115575. /***/ (function(module, exports) {
  115576. 'use strict';
  115577. exports.__esModule = true;
  115578. exports['default'] = function (instance) {
  115579. instance.registerHelper('log', function () /* message, options */{
  115580. var args = [undefined],
  115581. options = arguments[arguments.length - 1];
  115582. for (var i = 0; i < arguments.length - 1; i++) {
  115583. args.push(arguments[i]);
  115584. }
  115585. var level = 1;
  115586. if (options.hash.level != null) {
  115587. level = options.hash.level;
  115588. } else if (options.data && options.data.level != null) {
  115589. level = options.data.level;
  115590. }
  115591. args[0] = level;
  115592. instance.log.apply(instance, args);
  115593. });
  115594. };
  115595. module.exports = exports['default'];
  115596. /***/ }),
  115597. /* 16 */
  115598. /***/ (function(module, exports) {
  115599. 'use strict';
  115600. exports.__esModule = true;
  115601. exports['default'] = function (instance) {
  115602. instance.registerHelper('lookup', function (obj, field) {
  115603. return obj && obj[field];
  115604. });
  115605. };
  115606. module.exports = exports['default'];
  115607. /***/ }),
  115608. /* 17 */
  115609. /***/ (function(module, exports, __webpack_require__) {
  115610. 'use strict';
  115611. exports.__esModule = true;
  115612. var _utils = __webpack_require__(5);
  115613. exports['default'] = function (instance) {
  115614. instance.registerHelper('with', function (context, options) {
  115615. if (_utils.isFunction(context)) {
  115616. context = context.call(this);
  115617. }
  115618. var fn = options.fn;
  115619. if (!_utils.isEmpty(context)) {
  115620. var data = options.data;
  115621. if (options.data && options.ids) {
  115622. data = _utils.createFrame(options.data);
  115623. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  115624. }
  115625. return fn(context, {
  115626. data: data,
  115627. blockParams: _utils.blockParams([context], [data && data.contextPath])
  115628. });
  115629. } else {
  115630. return options.inverse(this);
  115631. }
  115632. });
  115633. };
  115634. module.exports = exports['default'];
  115635. /***/ }),
  115636. /* 18 */
  115637. /***/ (function(module, exports, __webpack_require__) {
  115638. 'use strict';
  115639. var _interopRequireDefault = __webpack_require__(1)['default'];
  115640. exports.__esModule = true;
  115641. exports.registerDefaultDecorators = registerDefaultDecorators;
  115642. var _decoratorsInline = __webpack_require__(19);
  115643. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  115644. function registerDefaultDecorators(instance) {
  115645. _decoratorsInline2['default'](instance);
  115646. }
  115647. /***/ }),
  115648. /* 19 */
  115649. /***/ (function(module, exports, __webpack_require__) {
  115650. 'use strict';
  115651. exports.__esModule = true;
  115652. var _utils = __webpack_require__(5);
  115653. exports['default'] = function (instance) {
  115654. instance.registerDecorator('inline', function (fn, props, container, options) {
  115655. var ret = fn;
  115656. if (!props.partials) {
  115657. props.partials = {};
  115658. ret = function (context, options) {
  115659. // Create a new partials stack frame prior to exec.
  115660. var original = container.partials;
  115661. container.partials = _utils.extend({}, original, props.partials);
  115662. var ret = fn(context, options);
  115663. container.partials = original;
  115664. return ret;
  115665. };
  115666. }
  115667. props.partials[options.args[0]] = options.fn;
  115668. return ret;
  115669. });
  115670. };
  115671. module.exports = exports['default'];
  115672. /***/ }),
  115673. /* 20 */
  115674. /***/ (function(module, exports, __webpack_require__) {
  115675. 'use strict';
  115676. exports.__esModule = true;
  115677. var _utils = __webpack_require__(5);
  115678. var logger = {
  115679. methodMap: ['debug', 'info', 'warn', 'error'],
  115680. level: 'info',
  115681. // Maps a given level value to the `methodMap` indexes above.
  115682. lookupLevel: function lookupLevel(level) {
  115683. if (typeof level === 'string') {
  115684. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  115685. if (levelMap >= 0) {
  115686. level = levelMap;
  115687. } else {
  115688. level = parseInt(level, 10);
  115689. }
  115690. }
  115691. return level;
  115692. },
  115693. // Can be overridden in the host environment
  115694. log: function log(level) {
  115695. level = logger.lookupLevel(level);
  115696. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  115697. var method = logger.methodMap[level];
  115698. if (!console[method]) {
  115699. // eslint-disable-line no-console
  115700. method = 'log';
  115701. }
  115702. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  115703. message[_key - 1] = arguments[_key];
  115704. }
  115705. console[method].apply(console, message); // eslint-disable-line no-console
  115706. }
  115707. }
  115708. };
  115709. exports['default'] = logger;
  115710. module.exports = exports['default'];
  115711. /***/ }),
  115712. /* 21 */
  115713. /***/ (function(module, exports) {
  115714. // Build out our basic SafeString type
  115715. 'use strict';
  115716. exports.__esModule = true;
  115717. function SafeString(string) {
  115718. this.string = string;
  115719. }
  115720. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  115721. return '' + this.string;
  115722. };
  115723. exports['default'] = SafeString;
  115724. module.exports = exports['default'];
  115725. /***/ }),
  115726. /* 22 */
  115727. /***/ (function(module, exports, __webpack_require__) {
  115728. 'use strict';
  115729. var _Object$seal = __webpack_require__(23)['default'];
  115730. var _interopRequireWildcard = __webpack_require__(3)['default'];
  115731. var _interopRequireDefault = __webpack_require__(1)['default'];
  115732. exports.__esModule = true;
  115733. exports.checkRevision = checkRevision;
  115734. exports.template = template;
  115735. exports.wrapProgram = wrapProgram;
  115736. exports.resolvePartial = resolvePartial;
  115737. exports.invokePartial = invokePartial;
  115738. exports.noop = noop;
  115739. var _utils = __webpack_require__(5);
  115740. var Utils = _interopRequireWildcard(_utils);
  115741. var _exception = __webpack_require__(6);
  115742. var _exception2 = _interopRequireDefault(_exception);
  115743. var _base = __webpack_require__(4);
  115744. function checkRevision(compilerInfo) {
  115745. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  115746. currentRevision = _base.COMPILER_REVISION;
  115747. if (compilerRevision !== currentRevision) {
  115748. if (compilerRevision < currentRevision) {
  115749. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  115750. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  115751. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  115752. } else {
  115753. // Use the embedded version info since the runtime doesn't know about this revision yet
  115754. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  115755. }
  115756. }
  115757. }
  115758. function template(templateSpec, env) {
  115759. /* istanbul ignore next */
  115760. if (!env) {
  115761. throw new _exception2['default']('No environment passed to template');
  115762. }
  115763. if (!templateSpec || !templateSpec.main) {
  115764. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  115765. }
  115766. templateSpec.main.decorator = templateSpec.main_d;
  115767. // Note: Using env.VM references rather than local var references throughout this section to allow
  115768. // for external users to override these as psuedo-supported APIs.
  115769. env.VM.checkRevision(templateSpec.compiler);
  115770. function invokePartialWrapper(partial, context, options) {
  115771. if (options.hash) {
  115772. context = Utils.extend({}, context, options.hash);
  115773. if (options.ids) {
  115774. options.ids[0] = true;
  115775. }
  115776. }
  115777. partial = env.VM.resolvePartial.call(this, partial, context, options);
  115778. var result = env.VM.invokePartial.call(this, partial, context, options);
  115779. if (result == null && env.compile) {
  115780. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  115781. result = options.partials[options.name](context, options);
  115782. }
  115783. if (result != null) {
  115784. if (options.indent) {
  115785. var lines = result.split('\n');
  115786. for (var i = 0, l = lines.length; i < l; i++) {
  115787. if (!lines[i] && i + 1 === l) {
  115788. break;
  115789. }
  115790. lines[i] = options.indent + lines[i];
  115791. }
  115792. result = lines.join('\n');
  115793. }
  115794. return result;
  115795. } else {
  115796. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  115797. }
  115798. }
  115799. // Just add water
  115800. var container = {
  115801. strict: function strict(obj, name) {
  115802. if (!(name in obj)) {
  115803. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  115804. }
  115805. return obj[name];
  115806. },
  115807. lookup: function lookup(depths, name) {
  115808. var len = depths.length;
  115809. for (var i = 0; i < len; i++) {
  115810. if (depths[i] && depths[i][name] != null) {
  115811. return depths[i][name];
  115812. }
  115813. }
  115814. },
  115815. lambda: function lambda(current, context) {
  115816. return typeof current === 'function' ? current.call(context) : current;
  115817. },
  115818. escapeExpression: Utils.escapeExpression,
  115819. invokePartial: invokePartialWrapper,
  115820. fn: function fn(i) {
  115821. var ret = templateSpec[i];
  115822. ret.decorator = templateSpec[i + '_d'];
  115823. return ret;
  115824. },
  115825. programs: [],
  115826. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  115827. var programWrapper = this.programs[i],
  115828. fn = this.fn(i);
  115829. if (data || depths || blockParams || declaredBlockParams) {
  115830. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  115831. } else if (!programWrapper) {
  115832. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  115833. }
  115834. return programWrapper;
  115835. },
  115836. data: function data(value, depth) {
  115837. while (value && depth--) {
  115838. value = value._parent;
  115839. }
  115840. return value;
  115841. },
  115842. merge: function merge(param, common) {
  115843. var obj = param || common;
  115844. if (param && common && param !== common) {
  115845. obj = Utils.extend({}, common, param);
  115846. }
  115847. return obj;
  115848. },
  115849. // An empty object to use as replacement for null-contexts
  115850. nullContext: _Object$seal({}),
  115851. noop: env.VM.noop,
  115852. compilerInfo: templateSpec.compiler
  115853. };
  115854. function ret(context) {
  115855. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115856. var data = options.data;
  115857. ret._setup(options);
  115858. if (!options.partial && templateSpec.useData) {
  115859. data = initData(context, data);
  115860. }
  115861. var depths = undefined,
  115862. blockParams = templateSpec.useBlockParams ? [] : undefined;
  115863. if (templateSpec.useDepths) {
  115864. if (options.depths) {
  115865. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  115866. } else {
  115867. depths = [context];
  115868. }
  115869. }
  115870. function main(context /*, options*/) {
  115871. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  115872. }
  115873. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  115874. return main(context, options);
  115875. }
  115876. ret.isTop = true;
  115877. ret._setup = function (options) {
  115878. if (!options.partial) {
  115879. container.helpers = container.merge(options.helpers, env.helpers);
  115880. if (templateSpec.usePartial) {
  115881. container.partials = container.merge(options.partials, env.partials);
  115882. }
  115883. if (templateSpec.usePartial || templateSpec.useDecorators) {
  115884. container.decorators = container.merge(options.decorators, env.decorators);
  115885. }
  115886. } else {
  115887. container.helpers = options.helpers;
  115888. container.partials = options.partials;
  115889. container.decorators = options.decorators;
  115890. }
  115891. };
  115892. ret._child = function (i, data, blockParams, depths) {
  115893. if (templateSpec.useBlockParams && !blockParams) {
  115894. throw new _exception2['default']('must pass block params');
  115895. }
  115896. if (templateSpec.useDepths && !depths) {
  115897. throw new _exception2['default']('must pass parent depths');
  115898. }
  115899. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  115900. };
  115901. return ret;
  115902. }
  115903. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  115904. function prog(context) {
  115905. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115906. var currentDepths = depths;
  115907. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  115908. currentDepths = [context].concat(depths);
  115909. }
  115910. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  115911. }
  115912. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  115913. prog.program = i;
  115914. prog.depth = depths ? depths.length : 0;
  115915. prog.blockParams = declaredBlockParams || 0;
  115916. return prog;
  115917. }
  115918. function resolvePartial(partial, context, options) {
  115919. if (!partial) {
  115920. if (options.name === '@partial-block') {
  115921. partial = options.data['partial-block'];
  115922. } else {
  115923. partial = options.partials[options.name];
  115924. }
  115925. } else if (!partial.call && !options.name) {
  115926. // This is a dynamic partial that returned a string
  115927. options.name = partial;
  115928. partial = options.partials[partial];
  115929. }
  115930. return partial;
  115931. }
  115932. function invokePartial(partial, context, options) {
  115933. // Use the current closure context to save the partial-block if this partial
  115934. var currentPartialBlock = options.data && options.data['partial-block'];
  115935. options.partial = true;
  115936. if (options.ids) {
  115937. options.data.contextPath = options.ids[0] || options.data.contextPath;
  115938. }
  115939. var partialBlock = undefined;
  115940. if (options.fn && options.fn !== noop) {
  115941. (function () {
  115942. options.data = _base.createFrame(options.data);
  115943. // Wrapper function to get access to currentPartialBlock from the closure
  115944. var fn = options.fn;
  115945. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  115946. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115947. // Restore the partial-block from the closure for the execution of the block
  115948. // i.e. the part inside the block of the partial call.
  115949. options.data = _base.createFrame(options.data);
  115950. options.data['partial-block'] = currentPartialBlock;
  115951. return fn(context, options);
  115952. };
  115953. if (fn.partials) {
  115954. options.partials = Utils.extend({}, options.partials, fn.partials);
  115955. }
  115956. })();
  115957. }
  115958. if (partial === undefined && partialBlock) {
  115959. partial = partialBlock;
  115960. }
  115961. if (partial === undefined) {
  115962. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  115963. } else if (partial instanceof Function) {
  115964. return partial(context, options);
  115965. }
  115966. }
  115967. function noop() {
  115968. return '';
  115969. }
  115970. function initData(context, data) {
  115971. if (!data || !('root' in data)) {
  115972. data = data ? _base.createFrame(data) : {};
  115973. data.root = context;
  115974. }
  115975. return data;
  115976. }
  115977. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  115978. if (fn.decorator) {
  115979. var props = {};
  115980. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  115981. Utils.extend(prog, props);
  115982. }
  115983. return prog;
  115984. }
  115985. /***/ }),
  115986. /* 23 */
  115987. /***/ (function(module, exports, __webpack_require__) {
  115988. module.exports = { "default": __webpack_require__(24), __esModule: true };
  115989. /***/ }),
  115990. /* 24 */
  115991. /***/ (function(module, exports, __webpack_require__) {
  115992. __webpack_require__(25);
  115993. module.exports = __webpack_require__(30).Object.seal;
  115994. /***/ }),
  115995. /* 25 */
  115996. /***/ (function(module, exports, __webpack_require__) {
  115997. // 19.1.2.17 Object.seal(O)
  115998. var isObject = __webpack_require__(26);
  115999. __webpack_require__(27)('seal', function($seal){
  116000. return function seal(it){
  116001. return $seal && isObject(it) ? $seal(it) : it;
  116002. };
  116003. });
  116004. /***/ }),
  116005. /* 26 */
  116006. /***/ (function(module, exports) {
  116007. module.exports = function(it){
  116008. return typeof it === 'object' ? it !== null : typeof it === 'function';
  116009. };
  116010. /***/ }),
  116011. /* 27 */
  116012. /***/ (function(module, exports, __webpack_require__) {
  116013. // most Object methods by ES6 should accept primitives
  116014. var $export = __webpack_require__(28)
  116015. , core = __webpack_require__(30)
  116016. , fails = __webpack_require__(33);
  116017. module.exports = function(KEY, exec){
  116018. var fn = (core.Object || {})[KEY] || Object[KEY]
  116019. , exp = {};
  116020. exp[KEY] = exec(fn);
  116021. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  116022. };
  116023. /***/ }),
  116024. /* 28 */
  116025. /***/ (function(module, exports, __webpack_require__) {
  116026. var global = __webpack_require__(29)
  116027. , core = __webpack_require__(30)
  116028. , ctx = __webpack_require__(31)
  116029. , PROTOTYPE = 'prototype';
  116030. var $export = function(type, name, source){
  116031. var IS_FORCED = type & $export.F
  116032. , IS_GLOBAL = type & $export.G
  116033. , IS_STATIC = type & $export.S
  116034. , IS_PROTO = type & $export.P
  116035. , IS_BIND = type & $export.B
  116036. , IS_WRAP = type & $export.W
  116037. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  116038. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  116039. , key, own, out;
  116040. if(IS_GLOBAL)source = name;
  116041. for(key in source){
  116042. // contains in native
  116043. own = !IS_FORCED && target && key in target;
  116044. if(own && key in exports)continue;
  116045. // export native or passed
  116046. out = own ? target[key] : source[key];
  116047. // prevent global pollution for namespaces
  116048. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  116049. // bind timers to global for call from export context
  116050. : IS_BIND && own ? ctx(out, global)
  116051. // wrap global constructors for prevent change them in library
  116052. : IS_WRAP && target[key] == out ? (function(C){
  116053. var F = function(param){
  116054. return this instanceof C ? new C(param) : C(param);
  116055. };
  116056. F[PROTOTYPE] = C[PROTOTYPE];
  116057. return F;
  116058. // make static versions for prototype methods
  116059. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  116060. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  116061. }
  116062. };
  116063. // type bitmap
  116064. $export.F = 1; // forced
  116065. $export.G = 2; // global
  116066. $export.S = 4; // static
  116067. $export.P = 8; // proto
  116068. $export.B = 16; // bind
  116069. $export.W = 32; // wrap
  116070. module.exports = $export;
  116071. /***/ }),
  116072. /* 29 */
  116073. /***/ (function(module, exports) {
  116074. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  116075. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  116076. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  116077. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  116078. /***/ }),
  116079. /* 30 */
  116080. /***/ (function(module, exports) {
  116081. var core = module.exports = {version: '1.2.6'};
  116082. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  116083. /***/ }),
  116084. /* 31 */
  116085. /***/ (function(module, exports, __webpack_require__) {
  116086. // optional / simple context binding
  116087. var aFunction = __webpack_require__(32);
  116088. module.exports = function(fn, that, length){
  116089. aFunction(fn);
  116090. if(that === undefined)return fn;
  116091. switch(length){
  116092. case 1: return function(a){
  116093. return fn.call(that, a);
  116094. };
  116095. case 2: return function(a, b){
  116096. return fn.call(that, a, b);
  116097. };
  116098. case 3: return function(a, b, c){
  116099. return fn.call(that, a, b, c);
  116100. };
  116101. }
  116102. return function(/* ...args */){
  116103. return fn.apply(that, arguments);
  116104. };
  116105. };
  116106. /***/ }),
  116107. /* 32 */
  116108. /***/ (function(module, exports) {
  116109. module.exports = function(it){
  116110. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  116111. return it;
  116112. };
  116113. /***/ }),
  116114. /* 33 */
  116115. /***/ (function(module, exports) {
  116116. module.exports = function(exec){
  116117. try {
  116118. return !!exec();
  116119. } catch(e){
  116120. return true;
  116121. }
  116122. };
  116123. /***/ }),
  116124. /* 34 */
  116125. /***/ (function(module, exports) {
  116126. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  116127. 'use strict';
  116128. exports.__esModule = true;
  116129. exports['default'] = function (Handlebars) {
  116130. /* istanbul ignore next */
  116131. var root = typeof global !== 'undefined' ? global : window,
  116132. $Handlebars = root.Handlebars;
  116133. /* istanbul ignore next */
  116134. Handlebars.noConflict = function () {
  116135. if (root.Handlebars === Handlebars) {
  116136. root.Handlebars = $Handlebars;
  116137. }
  116138. return Handlebars;
  116139. };
  116140. };
  116141. module.exports = exports['default'];
  116142. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  116143. /***/ }),
  116144. /* 35 */
  116145. /***/ (function(module, exports) {
  116146. 'use strict';
  116147. exports.__esModule = true;
  116148. var AST = {
  116149. // Public API used to evaluate derived attributes regarding AST nodes
  116150. helpers: {
  116151. // a mustache is definitely a helper if:
  116152. // * it is an eligible helper, and
  116153. // * it has at least one parameter or hash segment
  116154. helperExpression: function helperExpression(node) {
  116155. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  116156. },
  116157. scopedId: function scopedId(path) {
  116158. return (/^\.|this\b/.test(path.original)
  116159. );
  116160. },
  116161. // an ID is simple if it only has one part, and that part is not
  116162. // `..` or `this`.
  116163. simpleId: function simpleId(path) {
  116164. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  116165. }
  116166. }
  116167. };
  116168. // Must be exported as an object rather than the root of the module as the jison lexer
  116169. // must modify the object to operate properly.
  116170. exports['default'] = AST;
  116171. module.exports = exports['default'];
  116172. /***/ }),
  116173. /* 36 */
  116174. /***/ (function(module, exports, __webpack_require__) {
  116175. 'use strict';
  116176. var _interopRequireDefault = __webpack_require__(1)['default'];
  116177. var _interopRequireWildcard = __webpack_require__(3)['default'];
  116178. exports.__esModule = true;
  116179. exports.parse = parse;
  116180. var _parser = __webpack_require__(37);
  116181. var _parser2 = _interopRequireDefault(_parser);
  116182. var _whitespaceControl = __webpack_require__(38);
  116183. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  116184. var _helpers = __webpack_require__(40);
  116185. var Helpers = _interopRequireWildcard(_helpers);
  116186. var _utils = __webpack_require__(5);
  116187. exports.parser = _parser2['default'];
  116188. var yy = {};
  116189. _utils.extend(yy, Helpers);
  116190. function parse(input, options) {
  116191. // Just return if an already-compiled AST was passed in.
  116192. if (input.type === 'Program') {
  116193. return input;
  116194. }
  116195. _parser2['default'].yy = yy;
  116196. // Altering the shared object here, but this is ok as parser is a sync operation
  116197. yy.locInfo = function (locInfo) {
  116198. return new yy.SourceLocation(options && options.srcName, locInfo);
  116199. };
  116200. var strip = new _whitespaceControl2['default'](options);
  116201. return strip.accept(_parser2['default'].parse(input));
  116202. }
  116203. /***/ }),
  116204. /* 37 */
  116205. /***/ (function(module, exports) {
  116206. // File ignored in coverage tests via setting in .istanbul.yml
  116207. /* Jison generated parser */
  116208. "use strict";
  116209. exports.__esModule = true;
  116210. var handlebars = (function () {
  116211. var parser = { trace: function trace() {},
  116212. yy: {},
  116213. 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 },
  116214. 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" },
  116215. 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]],
  116216. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  116217. /**/) {
  116218. var $0 = $$.length - 1;
  116219. switch (yystate) {
  116220. case 1:
  116221. return $$[$0 - 1];
  116222. break;
  116223. case 2:
  116224. this.$ = yy.prepareProgram($$[$0]);
  116225. break;
  116226. case 3:
  116227. this.$ = $$[$0];
  116228. break;
  116229. case 4:
  116230. this.$ = $$[$0];
  116231. break;
  116232. case 5:
  116233. this.$ = $$[$0];
  116234. break;
  116235. case 6:
  116236. this.$ = $$[$0];
  116237. break;
  116238. case 7:
  116239. this.$ = $$[$0];
  116240. break;
  116241. case 8:
  116242. this.$ = $$[$0];
  116243. break;
  116244. case 9:
  116245. this.$ = {
  116246. type: 'CommentStatement',
  116247. value: yy.stripComment($$[$0]),
  116248. strip: yy.stripFlags($$[$0], $$[$0]),
  116249. loc: yy.locInfo(this._$)
  116250. };
  116251. break;
  116252. case 10:
  116253. this.$ = {
  116254. type: 'ContentStatement',
  116255. original: $$[$0],
  116256. value: $$[$0],
  116257. loc: yy.locInfo(this._$)
  116258. };
  116259. break;
  116260. case 11:
  116261. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  116262. break;
  116263. case 12:
  116264. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  116265. break;
  116266. case 13:
  116267. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  116268. break;
  116269. case 14:
  116270. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  116271. break;
  116272. case 15:
  116273. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  116274. break;
  116275. case 16:
  116276. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  116277. break;
  116278. case 17:
  116279. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  116280. break;
  116281. case 18:
  116282. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  116283. break;
  116284. case 19:
  116285. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  116286. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  116287. program.chained = true;
  116288. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  116289. break;
  116290. case 20:
  116291. this.$ = $$[$0];
  116292. break;
  116293. case 21:
  116294. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  116295. break;
  116296. case 22:
  116297. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  116298. break;
  116299. case 23:
  116300. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  116301. break;
  116302. case 24:
  116303. this.$ = {
  116304. type: 'PartialStatement',
  116305. name: $$[$0 - 3],
  116306. params: $$[$0 - 2],
  116307. hash: $$[$0 - 1],
  116308. indent: '',
  116309. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  116310. loc: yy.locInfo(this._$)
  116311. };
  116312. break;
  116313. case 25:
  116314. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  116315. break;
  116316. case 26:
  116317. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  116318. break;
  116319. case 27:
  116320. this.$ = $$[$0];
  116321. break;
  116322. case 28:
  116323. this.$ = $$[$0];
  116324. break;
  116325. case 29:
  116326. this.$ = {
  116327. type: 'SubExpression',
  116328. path: $$[$0 - 3],
  116329. params: $$[$0 - 2],
  116330. hash: $$[$0 - 1],
  116331. loc: yy.locInfo(this._$)
  116332. };
  116333. break;
  116334. case 30:
  116335. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  116336. break;
  116337. case 31:
  116338. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  116339. break;
  116340. case 32:
  116341. this.$ = yy.id($$[$0 - 1]);
  116342. break;
  116343. case 33:
  116344. this.$ = $$[$0];
  116345. break;
  116346. case 34:
  116347. this.$ = $$[$0];
  116348. break;
  116349. case 35:
  116350. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  116351. break;
  116352. case 36:
  116353. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  116354. break;
  116355. case 37:
  116356. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  116357. break;
  116358. case 38:
  116359. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  116360. break;
  116361. case 39:
  116362. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  116363. break;
  116364. case 40:
  116365. this.$ = $$[$0];
  116366. break;
  116367. case 41:
  116368. this.$ = $$[$0];
  116369. break;
  116370. case 42:
  116371. this.$ = yy.preparePath(true, $$[$0], this._$);
  116372. break;
  116373. case 43:
  116374. this.$ = yy.preparePath(false, $$[$0], this._$);
  116375. break;
  116376. case 44:
  116377. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  116378. break;
  116379. case 45:
  116380. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  116381. break;
  116382. case 46:
  116383. this.$ = [];
  116384. break;
  116385. case 47:
  116386. $$[$0 - 1].push($$[$0]);
  116387. break;
  116388. case 48:
  116389. this.$ = [$$[$0]];
  116390. break;
  116391. case 49:
  116392. $$[$0 - 1].push($$[$0]);
  116393. break;
  116394. case 50:
  116395. this.$ = [];
  116396. break;
  116397. case 51:
  116398. $$[$0 - 1].push($$[$0]);
  116399. break;
  116400. case 58:
  116401. this.$ = [];
  116402. break;
  116403. case 59:
  116404. $$[$0 - 1].push($$[$0]);
  116405. break;
  116406. case 64:
  116407. this.$ = [];
  116408. break;
  116409. case 65:
  116410. $$[$0 - 1].push($$[$0]);
  116411. break;
  116412. case 70:
  116413. this.$ = [];
  116414. break;
  116415. case 71:
  116416. $$[$0 - 1].push($$[$0]);
  116417. break;
  116418. case 78:
  116419. this.$ = [];
  116420. break;
  116421. case 79:
  116422. $$[$0 - 1].push($$[$0]);
  116423. break;
  116424. case 82:
  116425. this.$ = [];
  116426. break;
  116427. case 83:
  116428. $$[$0 - 1].push($$[$0]);
  116429. break;
  116430. case 86:
  116431. this.$ = [];
  116432. break;
  116433. case 87:
  116434. $$[$0 - 1].push($$[$0]);
  116435. break;
  116436. case 90:
  116437. this.$ = [];
  116438. break;
  116439. case 91:
  116440. $$[$0 - 1].push($$[$0]);
  116441. break;
  116442. case 94:
  116443. this.$ = [];
  116444. break;
  116445. case 95:
  116446. $$[$0 - 1].push($$[$0]);
  116447. break;
  116448. case 98:
  116449. this.$ = [$$[$0]];
  116450. break;
  116451. case 99:
  116452. $$[$0 - 1].push($$[$0]);
  116453. break;
  116454. case 100:
  116455. this.$ = [$$[$0]];
  116456. break;
  116457. case 101:
  116458. $$[$0 - 1].push($$[$0]);
  116459. break;
  116460. }
  116461. },
  116462. table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
  116463. 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] },
  116464. parseError: function parseError(str, hash) {
  116465. throw new Error(str);
  116466. },
  116467. parse: function parse(input) {
  116468. var self = this,
  116469. stack = [0],
  116470. vstack = [null],
  116471. lstack = [],
  116472. table = this.table,
  116473. yytext = "",
  116474. yylineno = 0,
  116475. yyleng = 0,
  116476. recovering = 0,
  116477. TERROR = 2,
  116478. EOF = 1;
  116479. this.lexer.setInput(input);
  116480. this.lexer.yy = this.yy;
  116481. this.yy.lexer = this.lexer;
  116482. this.yy.parser = this;
  116483. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  116484. var yyloc = this.lexer.yylloc;
  116485. lstack.push(yyloc);
  116486. var ranges = this.lexer.options && this.lexer.options.ranges;
  116487. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  116488. function popStack(n) {
  116489. stack.length = stack.length - 2 * n;
  116490. vstack.length = vstack.length - n;
  116491. lstack.length = lstack.length - n;
  116492. }
  116493. function lex() {
  116494. var token;
  116495. token = self.lexer.lex() || 1;
  116496. if (typeof token !== "number") {
  116497. token = self.symbols_[token] || token;
  116498. }
  116499. return token;
  116500. }
  116501. var symbol,
  116502. preErrorSymbol,
  116503. state,
  116504. action,
  116505. a,
  116506. r,
  116507. yyval = {},
  116508. p,
  116509. len,
  116510. newState,
  116511. expected;
  116512. while (true) {
  116513. state = stack[stack.length - 1];
  116514. if (this.defaultActions[state]) {
  116515. action = this.defaultActions[state];
  116516. } else {
  116517. if (symbol === null || typeof symbol == "undefined") {
  116518. symbol = lex();
  116519. }
  116520. action = table[state] && table[state][symbol];
  116521. }
  116522. if (typeof action === "undefined" || !action.length || !action[0]) {
  116523. var errStr = "";
  116524. if (!recovering) {
  116525. expected = [];
  116526. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  116527. expected.push("'" + this.terminals_[p] + "'");
  116528. }
  116529. if (this.lexer.showPosition) {
  116530. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  116531. } else {
  116532. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  116533. }
  116534. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  116535. }
  116536. }
  116537. if (action[0] instanceof Array && action.length > 1) {
  116538. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  116539. }
  116540. switch (action[0]) {
  116541. case 1:
  116542. stack.push(symbol);
  116543. vstack.push(this.lexer.yytext);
  116544. lstack.push(this.lexer.yylloc);
  116545. stack.push(action[1]);
  116546. symbol = null;
  116547. if (!preErrorSymbol) {
  116548. yyleng = this.lexer.yyleng;
  116549. yytext = this.lexer.yytext;
  116550. yylineno = this.lexer.yylineno;
  116551. yyloc = this.lexer.yylloc;
  116552. if (recovering > 0) recovering--;
  116553. } else {
  116554. symbol = preErrorSymbol;
  116555. preErrorSymbol = null;
  116556. }
  116557. break;
  116558. case 2:
  116559. len = this.productions_[action[1]][1];
  116560. yyval.$ = vstack[vstack.length - len];
  116561. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  116562. if (ranges) {
  116563. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  116564. }
  116565. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  116566. if (typeof r !== "undefined") {
  116567. return r;
  116568. }
  116569. if (len) {
  116570. stack = stack.slice(0, -1 * len * 2);
  116571. vstack = vstack.slice(0, -1 * len);
  116572. lstack = lstack.slice(0, -1 * len);
  116573. }
  116574. stack.push(this.productions_[action[1]][0]);
  116575. vstack.push(yyval.$);
  116576. lstack.push(yyval._$);
  116577. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  116578. stack.push(newState);
  116579. break;
  116580. case 3:
  116581. return true;
  116582. }
  116583. }
  116584. return true;
  116585. }
  116586. };
  116587. /* Jison generated lexer */
  116588. var lexer = (function () {
  116589. var lexer = { EOF: 1,
  116590. parseError: function parseError(str, hash) {
  116591. if (this.yy.parser) {
  116592. this.yy.parser.parseError(str, hash);
  116593. } else {
  116594. throw new Error(str);
  116595. }
  116596. },
  116597. setInput: function setInput(input) {
  116598. this._input = input;
  116599. this._more = this._less = this.done = false;
  116600. this.yylineno = this.yyleng = 0;
  116601. this.yytext = this.matched = this.match = '';
  116602. this.conditionStack = ['INITIAL'];
  116603. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  116604. if (this.options.ranges) this.yylloc.range = [0, 0];
  116605. this.offset = 0;
  116606. return this;
  116607. },
  116608. input: function input() {
  116609. var ch = this._input[0];
  116610. this.yytext += ch;
  116611. this.yyleng++;
  116612. this.offset++;
  116613. this.match += ch;
  116614. this.matched += ch;
  116615. var lines = ch.match(/(?:\r\n?|\n).*/g);
  116616. if (lines) {
  116617. this.yylineno++;
  116618. this.yylloc.last_line++;
  116619. } else {
  116620. this.yylloc.last_column++;
  116621. }
  116622. if (this.options.ranges) this.yylloc.range[1]++;
  116623. this._input = this._input.slice(1);
  116624. return ch;
  116625. },
  116626. unput: function unput(ch) {
  116627. var len = ch.length;
  116628. var lines = ch.split(/(?:\r\n?|\n)/g);
  116629. this._input = ch + this._input;
  116630. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  116631. //this.yyleng -= len;
  116632. this.offset -= len;
  116633. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  116634. this.match = this.match.substr(0, this.match.length - 1);
  116635. this.matched = this.matched.substr(0, this.matched.length - 1);
  116636. if (lines.length - 1) this.yylineno -= lines.length - 1;
  116637. var r = this.yylloc.range;
  116638. this.yylloc = { first_line: this.yylloc.first_line,
  116639. last_line: this.yylineno + 1,
  116640. first_column: this.yylloc.first_column,
  116641. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  116642. };
  116643. if (this.options.ranges) {
  116644. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  116645. }
  116646. return this;
  116647. },
  116648. more: function more() {
  116649. this._more = true;
  116650. return this;
  116651. },
  116652. less: function less(n) {
  116653. this.unput(this.match.slice(n));
  116654. },
  116655. pastInput: function pastInput() {
  116656. var past = this.matched.substr(0, this.matched.length - this.match.length);
  116657. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  116658. },
  116659. upcomingInput: function upcomingInput() {
  116660. var next = this.match;
  116661. if (next.length < 20) {
  116662. next += this._input.substr(0, 20 - next.length);
  116663. }
  116664. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  116665. },
  116666. showPosition: function showPosition() {
  116667. var pre = this.pastInput();
  116668. var c = new Array(pre.length + 1).join("-");
  116669. return pre + this.upcomingInput() + "\n" + c + "^";
  116670. },
  116671. next: function next() {
  116672. if (this.done) {
  116673. return this.EOF;
  116674. }
  116675. if (!this._input) this.done = true;
  116676. var token, match, tempMatch, index, col, lines;
  116677. if (!this._more) {
  116678. this.yytext = '';
  116679. this.match = '';
  116680. }
  116681. var rules = this._currentRules();
  116682. for (var i = 0; i < rules.length; i++) {
  116683. tempMatch = this._input.match(this.rules[rules[i]]);
  116684. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  116685. match = tempMatch;
  116686. index = i;
  116687. if (!this.options.flex) break;
  116688. }
  116689. }
  116690. if (match) {
  116691. lines = match[0].match(/(?:\r\n?|\n).*/g);
  116692. if (lines) this.yylineno += lines.length;
  116693. this.yylloc = { first_line: this.yylloc.last_line,
  116694. last_line: this.yylineno + 1,
  116695. first_column: this.yylloc.last_column,
  116696. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  116697. this.yytext += match[0];
  116698. this.match += match[0];
  116699. this.matches = match;
  116700. this.yyleng = this.yytext.length;
  116701. if (this.options.ranges) {
  116702. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  116703. }
  116704. this._more = false;
  116705. this._input = this._input.slice(match[0].length);
  116706. this.matched += match[0];
  116707. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  116708. if (this.done && this._input) this.done = false;
  116709. if (token) return token;else return;
  116710. }
  116711. if (this._input === "") {
  116712. return this.EOF;
  116713. } else {
  116714. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  116715. }
  116716. },
  116717. lex: function lex() {
  116718. var r = this.next();
  116719. if (typeof r !== 'undefined') {
  116720. return r;
  116721. } else {
  116722. return this.lex();
  116723. }
  116724. },
  116725. begin: function begin(condition) {
  116726. this.conditionStack.push(condition);
  116727. },
  116728. popState: function popState() {
  116729. return this.conditionStack.pop();
  116730. },
  116731. _currentRules: function _currentRules() {
  116732. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  116733. },
  116734. topState: function topState() {
  116735. return this.conditionStack[this.conditionStack.length - 2];
  116736. },
  116737. pushState: function begin(condition) {
  116738. this.begin(condition);
  116739. } };
  116740. lexer.options = {};
  116741. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  116742. /**/) {
  116743. function strip(start, end) {
  116744. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  116745. }
  116746. var YYSTATE = YY_START;
  116747. switch ($avoiding_name_collisions) {
  116748. case 0:
  116749. if (yy_.yytext.slice(-2) === "\\\\") {
  116750. strip(0, 1);
  116751. this.begin("mu");
  116752. } else if (yy_.yytext.slice(-1) === "\\") {
  116753. strip(0, 1);
  116754. this.begin("emu");
  116755. } else {
  116756. this.begin("mu");
  116757. }
  116758. if (yy_.yytext) return 15;
  116759. break;
  116760. case 1:
  116761. return 15;
  116762. break;
  116763. case 2:
  116764. this.popState();
  116765. return 15;
  116766. break;
  116767. case 3:
  116768. this.begin('raw');return 15;
  116769. break;
  116770. case 4:
  116771. this.popState();
  116772. // Should be using `this.topState()` below, but it currently
  116773. // returns the second top instead of the first top. Opened an
  116774. // issue about it at https://github.com/zaach/jison/issues/291
  116775. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  116776. return 15;
  116777. } else {
  116778. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  116779. return 'END_RAW_BLOCK';
  116780. }
  116781. break;
  116782. case 5:
  116783. return 15;
  116784. break;
  116785. case 6:
  116786. this.popState();
  116787. return 14;
  116788. break;
  116789. case 7:
  116790. return 65;
  116791. break;
  116792. case 8:
  116793. return 68;
  116794. break;
  116795. case 9:
  116796. return 19;
  116797. break;
  116798. case 10:
  116799. this.popState();
  116800. this.begin('raw');
  116801. return 23;
  116802. break;
  116803. case 11:
  116804. return 55;
  116805. break;
  116806. case 12:
  116807. return 60;
  116808. break;
  116809. case 13:
  116810. return 29;
  116811. break;
  116812. case 14:
  116813. return 47;
  116814. break;
  116815. case 15:
  116816. this.popState();return 44;
  116817. break;
  116818. case 16:
  116819. this.popState();return 44;
  116820. break;
  116821. case 17:
  116822. return 34;
  116823. break;
  116824. case 18:
  116825. return 39;
  116826. break;
  116827. case 19:
  116828. return 51;
  116829. break;
  116830. case 20:
  116831. return 48;
  116832. break;
  116833. case 21:
  116834. this.unput(yy_.yytext);
  116835. this.popState();
  116836. this.begin('com');
  116837. break;
  116838. case 22:
  116839. this.popState();
  116840. return 14;
  116841. break;
  116842. case 23:
  116843. return 48;
  116844. break;
  116845. case 24:
  116846. return 73;
  116847. break;
  116848. case 25:
  116849. return 72;
  116850. break;
  116851. case 26:
  116852. return 72;
  116853. break;
  116854. case 27:
  116855. return 87;
  116856. break;
  116857. case 28:
  116858. // ignore whitespace
  116859. break;
  116860. case 29:
  116861. this.popState();return 54;
  116862. break;
  116863. case 30:
  116864. this.popState();return 33;
  116865. break;
  116866. case 31:
  116867. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  116868. break;
  116869. case 32:
  116870. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  116871. break;
  116872. case 33:
  116873. return 85;
  116874. break;
  116875. case 34:
  116876. return 82;
  116877. break;
  116878. case 35:
  116879. return 82;
  116880. break;
  116881. case 36:
  116882. return 83;
  116883. break;
  116884. case 37:
  116885. return 84;
  116886. break;
  116887. case 38:
  116888. return 81;
  116889. break;
  116890. case 39:
  116891. return 75;
  116892. break;
  116893. case 40:
  116894. return 77;
  116895. break;
  116896. case 41:
  116897. return 72;
  116898. break;
  116899. case 42:
  116900. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  116901. break;
  116902. case 43:
  116903. return 'INVALID';
  116904. break;
  116905. case 44:
  116906. return 5;
  116907. break;
  116908. }
  116909. };
  116910. lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  116911. lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  116912. return lexer;
  116913. })();
  116914. parser.lexer = lexer;
  116915. function Parser() {
  116916. this.yy = {};
  116917. }Parser.prototype = parser;parser.Parser = Parser;
  116918. return new Parser();
  116919. })();exports["default"] = handlebars;
  116920. module.exports = exports["default"];
  116921. /***/ }),
  116922. /* 38 */
  116923. /***/ (function(module, exports, __webpack_require__) {
  116924. 'use strict';
  116925. var _interopRequireDefault = __webpack_require__(1)['default'];
  116926. exports.__esModule = true;
  116927. var _visitor = __webpack_require__(39);
  116928. var _visitor2 = _interopRequireDefault(_visitor);
  116929. function WhitespaceControl() {
  116930. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  116931. this.options = options;
  116932. }
  116933. WhitespaceControl.prototype = new _visitor2['default']();
  116934. WhitespaceControl.prototype.Program = function (program) {
  116935. var doStandalone = !this.options.ignoreStandalone;
  116936. var isRoot = !this.isRootSeen;
  116937. this.isRootSeen = true;
  116938. var body = program.body;
  116939. for (var i = 0, l = body.length; i < l; i++) {
  116940. var current = body[i],
  116941. strip = this.accept(current);
  116942. if (!strip) {
  116943. continue;
  116944. }
  116945. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  116946. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  116947. openStandalone = strip.openStandalone && _isPrevWhitespace,
  116948. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  116949. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  116950. if (strip.close) {
  116951. omitRight(body, i, true);
  116952. }
  116953. if (strip.open) {
  116954. omitLeft(body, i, true);
  116955. }
  116956. if (doStandalone && inlineStandalone) {
  116957. omitRight(body, i);
  116958. if (omitLeft(body, i)) {
  116959. // If we are on a standalone node, save the indent info for partials
  116960. if (current.type === 'PartialStatement') {
  116961. // Pull out the whitespace from the final line
  116962. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  116963. }
  116964. }
  116965. }
  116966. if (doStandalone && openStandalone) {
  116967. omitRight((current.program || current.inverse).body);
  116968. // Strip out the previous content node if it's whitespace only
  116969. omitLeft(body, i);
  116970. }
  116971. if (doStandalone && closeStandalone) {
  116972. // Always strip the next node
  116973. omitRight(body, i);
  116974. omitLeft((current.inverse || current.program).body);
  116975. }
  116976. }
  116977. return program;
  116978. };
  116979. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  116980. this.accept(block.program);
  116981. this.accept(block.inverse);
  116982. // Find the inverse program that is involed with whitespace stripping.
  116983. var program = block.program || block.inverse,
  116984. inverse = block.program && block.inverse,
  116985. firstInverse = inverse,
  116986. lastInverse = inverse;
  116987. if (inverse && inverse.chained) {
  116988. firstInverse = inverse.body[0].program;
  116989. // Walk the inverse chain to find the last inverse that is actually in the chain.
  116990. while (lastInverse.chained) {
  116991. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  116992. }
  116993. }
  116994. var strip = {
  116995. open: block.openStrip.open,
  116996. close: block.closeStrip.close,
  116997. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  116998. // so our parent can determine if we actually are standalone
  116999. openStandalone: isNextWhitespace(program.body),
  117000. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  117001. };
  117002. if (block.openStrip.close) {
  117003. omitRight(program.body, null, true);
  117004. }
  117005. if (inverse) {
  117006. var inverseStrip = block.inverseStrip;
  117007. if (inverseStrip.open) {
  117008. omitLeft(program.body, null, true);
  117009. }
  117010. if (inverseStrip.close) {
  117011. omitRight(firstInverse.body, null, true);
  117012. }
  117013. if (block.closeStrip.open) {
  117014. omitLeft(lastInverse.body, null, true);
  117015. }
  117016. // Find standalone else statments
  117017. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  117018. omitLeft(program.body);
  117019. omitRight(firstInverse.body);
  117020. }
  117021. } else if (block.closeStrip.open) {
  117022. omitLeft(program.body, null, true);
  117023. }
  117024. return strip;
  117025. };
  117026. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  117027. return mustache.strip;
  117028. };
  117029. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  117030. /* istanbul ignore next */
  117031. var strip = node.strip || {};
  117032. return {
  117033. inlineStandalone: true,
  117034. open: strip.open,
  117035. close: strip.close
  117036. };
  117037. };
  117038. function isPrevWhitespace(body, i, isRoot) {
  117039. if (i === undefined) {
  117040. i = body.length;
  117041. }
  117042. // Nodes that end with newlines are considered whitespace (but are special
  117043. // cased for strip operations)
  117044. var prev = body[i - 1],
  117045. sibling = body[i - 2];
  117046. if (!prev) {
  117047. return isRoot;
  117048. }
  117049. if (prev.type === 'ContentStatement') {
  117050. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  117051. }
  117052. }
  117053. function isNextWhitespace(body, i, isRoot) {
  117054. if (i === undefined) {
  117055. i = -1;
  117056. }
  117057. var next = body[i + 1],
  117058. sibling = body[i + 2];
  117059. if (!next) {
  117060. return isRoot;
  117061. }
  117062. if (next.type === 'ContentStatement') {
  117063. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  117064. }
  117065. }
  117066. // Marks the node to the right of the position as omitted.
  117067. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  117068. //
  117069. // If i is undefined, then the first child will be marked as such.
  117070. //
  117071. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  117072. // content is met.
  117073. function omitRight(body, i, multiple) {
  117074. var current = body[i == null ? 0 : i + 1];
  117075. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  117076. return;
  117077. }
  117078. var original = current.value;
  117079. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  117080. current.rightStripped = current.value !== original;
  117081. }
  117082. // Marks the node to the left of the position as omitted.
  117083. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  117084. //
  117085. // If i is undefined then the last child will be marked as such.
  117086. //
  117087. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  117088. // content is met.
  117089. function omitLeft(body, i, multiple) {
  117090. var current = body[i == null ? body.length - 1 : i - 1];
  117091. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  117092. return;
  117093. }
  117094. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  117095. var original = current.value;
  117096. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  117097. current.leftStripped = current.value !== original;
  117098. return current.leftStripped;
  117099. }
  117100. exports['default'] = WhitespaceControl;
  117101. module.exports = exports['default'];
  117102. /***/ }),
  117103. /* 39 */
  117104. /***/ (function(module, exports, __webpack_require__) {
  117105. 'use strict';
  117106. var _interopRequireDefault = __webpack_require__(1)['default'];
  117107. exports.__esModule = true;
  117108. var _exception = __webpack_require__(6);
  117109. var _exception2 = _interopRequireDefault(_exception);
  117110. function Visitor() {
  117111. this.parents = [];
  117112. }
  117113. Visitor.prototype = {
  117114. constructor: Visitor,
  117115. mutating: false,
  117116. // Visits a given value. If mutating, will replace the value if necessary.
  117117. acceptKey: function acceptKey(node, name) {
  117118. var value = this.accept(node[name]);
  117119. if (this.mutating) {
  117120. // Hacky sanity check: This may have a few false positives for type for the helper
  117121. // methods but will generally do the right thing without a lot of overhead.
  117122. if (value && !Visitor.prototype[value.type]) {
  117123. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  117124. }
  117125. node[name] = value;
  117126. }
  117127. },
  117128. // Performs an accept operation with added sanity check to ensure
  117129. // required keys are not removed.
  117130. acceptRequired: function acceptRequired(node, name) {
  117131. this.acceptKey(node, name);
  117132. if (!node[name]) {
  117133. throw new _exception2['default'](node.type + ' requires ' + name);
  117134. }
  117135. },
  117136. // Traverses a given array. If mutating, empty respnses will be removed
  117137. // for child elements.
  117138. acceptArray: function acceptArray(array) {
  117139. for (var i = 0, l = array.length; i < l; i++) {
  117140. this.acceptKey(array, i);
  117141. if (!array[i]) {
  117142. array.splice(i, 1);
  117143. i--;
  117144. l--;
  117145. }
  117146. }
  117147. },
  117148. accept: function accept(object) {
  117149. if (!object) {
  117150. return;
  117151. }
  117152. /* istanbul ignore next: Sanity code */
  117153. if (!this[object.type]) {
  117154. throw new _exception2['default']('Unknown type: ' + object.type, object);
  117155. }
  117156. if (this.current) {
  117157. this.parents.unshift(this.current);
  117158. }
  117159. this.current = object;
  117160. var ret = this[object.type](object);
  117161. this.current = this.parents.shift();
  117162. if (!this.mutating || ret) {
  117163. return ret;
  117164. } else if (ret !== false) {
  117165. return object;
  117166. }
  117167. },
  117168. Program: function Program(program) {
  117169. this.acceptArray(program.body);
  117170. },
  117171. MustacheStatement: visitSubExpression,
  117172. Decorator: visitSubExpression,
  117173. BlockStatement: visitBlock,
  117174. DecoratorBlock: visitBlock,
  117175. PartialStatement: visitPartial,
  117176. PartialBlockStatement: function PartialBlockStatement(partial) {
  117177. visitPartial.call(this, partial);
  117178. this.acceptKey(partial, 'program');
  117179. },
  117180. ContentStatement: function ContentStatement() /* content */{},
  117181. CommentStatement: function CommentStatement() /* comment */{},
  117182. SubExpression: visitSubExpression,
  117183. PathExpression: function PathExpression() /* path */{},
  117184. StringLiteral: function StringLiteral() /* string */{},
  117185. NumberLiteral: function NumberLiteral() /* number */{},
  117186. BooleanLiteral: function BooleanLiteral() /* bool */{},
  117187. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  117188. NullLiteral: function NullLiteral() /* literal */{},
  117189. Hash: function Hash(hash) {
  117190. this.acceptArray(hash.pairs);
  117191. },
  117192. HashPair: function HashPair(pair) {
  117193. this.acceptRequired(pair, 'value');
  117194. }
  117195. };
  117196. function visitSubExpression(mustache) {
  117197. this.acceptRequired(mustache, 'path');
  117198. this.acceptArray(mustache.params);
  117199. this.acceptKey(mustache, 'hash');
  117200. }
  117201. function visitBlock(block) {
  117202. visitSubExpression.call(this, block);
  117203. this.acceptKey(block, 'program');
  117204. this.acceptKey(block, 'inverse');
  117205. }
  117206. function visitPartial(partial) {
  117207. this.acceptRequired(partial, 'name');
  117208. this.acceptArray(partial.params);
  117209. this.acceptKey(partial, 'hash');
  117210. }
  117211. exports['default'] = Visitor;
  117212. module.exports = exports['default'];
  117213. /***/ }),
  117214. /* 40 */
  117215. /***/ (function(module, exports, __webpack_require__) {
  117216. 'use strict';
  117217. var _interopRequireDefault = __webpack_require__(1)['default'];
  117218. exports.__esModule = true;
  117219. exports.SourceLocation = SourceLocation;
  117220. exports.id = id;
  117221. exports.stripFlags = stripFlags;
  117222. exports.stripComment = stripComment;
  117223. exports.preparePath = preparePath;
  117224. exports.prepareMustache = prepareMustache;
  117225. exports.prepareRawBlock = prepareRawBlock;
  117226. exports.prepareBlock = prepareBlock;
  117227. exports.prepareProgram = prepareProgram;
  117228. exports.preparePartialBlock = preparePartialBlock;
  117229. var _exception = __webpack_require__(6);
  117230. var _exception2 = _interopRequireDefault(_exception);
  117231. function validateClose(open, close) {
  117232. close = close.path ? close.path.original : close;
  117233. if (open.path.original !== close) {
  117234. var errorNode = { loc: open.path.loc };
  117235. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  117236. }
  117237. }
  117238. function SourceLocation(source, locInfo) {
  117239. this.source = source;
  117240. this.start = {
  117241. line: locInfo.first_line,
  117242. column: locInfo.first_column
  117243. };
  117244. this.end = {
  117245. line: locInfo.last_line,
  117246. column: locInfo.last_column
  117247. };
  117248. }
  117249. function id(token) {
  117250. if (/^\[.*\]$/.test(token)) {
  117251. return token.substr(1, token.length - 2);
  117252. } else {
  117253. return token;
  117254. }
  117255. }
  117256. function stripFlags(open, close) {
  117257. return {
  117258. open: open.charAt(2) === '~',
  117259. close: close.charAt(close.length - 3) === '~'
  117260. };
  117261. }
  117262. function stripComment(comment) {
  117263. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  117264. }
  117265. function preparePath(data, parts, loc) {
  117266. loc = this.locInfo(loc);
  117267. var original = data ? '@' : '',
  117268. dig = [],
  117269. depth = 0,
  117270. depthString = '';
  117271. for (var i = 0, l = parts.length; i < l; i++) {
  117272. var part = parts[i].part,
  117273. // If we have [] syntax then we do not treat path references as operators,
  117274. // i.e. foo.[this] resolves to approximately context.foo['this']
  117275. isLiteral = parts[i].original !== part;
  117276. original += (parts[i].separator || '') + part;
  117277. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  117278. if (dig.length > 0) {
  117279. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  117280. } else if (part === '..') {
  117281. depth++;
  117282. depthString += '../';
  117283. }
  117284. } else {
  117285. dig.push(part);
  117286. }
  117287. }
  117288. return {
  117289. type: 'PathExpression',
  117290. data: data,
  117291. depth: depth,
  117292. parts: dig,
  117293. original: original,
  117294. loc: loc
  117295. };
  117296. }
  117297. function prepareMustache(path, params, hash, open, strip, locInfo) {
  117298. // Must use charAt to support IE pre-10
  117299. var escapeFlag = open.charAt(3) || open.charAt(2),
  117300. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  117301. var decorator = /\*/.test(open);
  117302. return {
  117303. type: decorator ? 'Decorator' : 'MustacheStatement',
  117304. path: path,
  117305. params: params,
  117306. hash: hash,
  117307. escaped: escaped,
  117308. strip: strip,
  117309. loc: this.locInfo(locInfo)
  117310. };
  117311. }
  117312. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  117313. validateClose(openRawBlock, close);
  117314. locInfo = this.locInfo(locInfo);
  117315. var program = {
  117316. type: 'Program',
  117317. body: contents,
  117318. strip: {},
  117319. loc: locInfo
  117320. };
  117321. return {
  117322. type: 'BlockStatement',
  117323. path: openRawBlock.path,
  117324. params: openRawBlock.params,
  117325. hash: openRawBlock.hash,
  117326. program: program,
  117327. openStrip: {},
  117328. inverseStrip: {},
  117329. closeStrip: {},
  117330. loc: locInfo
  117331. };
  117332. }
  117333. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  117334. if (close && close.path) {
  117335. validateClose(openBlock, close);
  117336. }
  117337. var decorator = /\*/.test(openBlock.open);
  117338. program.blockParams = openBlock.blockParams;
  117339. var inverse = undefined,
  117340. inverseStrip = undefined;
  117341. if (inverseAndProgram) {
  117342. if (decorator) {
  117343. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  117344. }
  117345. if (inverseAndProgram.chain) {
  117346. inverseAndProgram.program.body[0].closeStrip = close.strip;
  117347. }
  117348. inverseStrip = inverseAndProgram.strip;
  117349. inverse = inverseAndProgram.program;
  117350. }
  117351. if (inverted) {
  117352. inverted = inverse;
  117353. inverse = program;
  117354. program = inverted;
  117355. }
  117356. return {
  117357. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  117358. path: openBlock.path,
  117359. params: openBlock.params,
  117360. hash: openBlock.hash,
  117361. program: program,
  117362. inverse: inverse,
  117363. openStrip: openBlock.strip,
  117364. inverseStrip: inverseStrip,
  117365. closeStrip: close && close.strip,
  117366. loc: this.locInfo(locInfo)
  117367. };
  117368. }
  117369. function prepareProgram(statements, loc) {
  117370. if (!loc && statements.length) {
  117371. var firstLoc = statements[0].loc,
  117372. lastLoc = statements[statements.length - 1].loc;
  117373. /* istanbul ignore else */
  117374. if (firstLoc && lastLoc) {
  117375. loc = {
  117376. source: firstLoc.source,
  117377. start: {
  117378. line: firstLoc.start.line,
  117379. column: firstLoc.start.column
  117380. },
  117381. end: {
  117382. line: lastLoc.end.line,
  117383. column: lastLoc.end.column
  117384. }
  117385. };
  117386. }
  117387. }
  117388. return {
  117389. type: 'Program',
  117390. body: statements,
  117391. strip: {},
  117392. loc: loc
  117393. };
  117394. }
  117395. function preparePartialBlock(open, program, close, locInfo) {
  117396. validateClose(open, close);
  117397. return {
  117398. type: 'PartialBlockStatement',
  117399. name: open.path,
  117400. params: open.params,
  117401. hash: open.hash,
  117402. program: program,
  117403. openStrip: open.strip,
  117404. closeStrip: close && close.strip,
  117405. loc: this.locInfo(locInfo)
  117406. };
  117407. }
  117408. /***/ }),
  117409. /* 41 */
  117410. /***/ (function(module, exports, __webpack_require__) {
  117411. /* eslint-disable new-cap */
  117412. 'use strict';
  117413. var _interopRequireDefault = __webpack_require__(1)['default'];
  117414. exports.__esModule = true;
  117415. exports.Compiler = Compiler;
  117416. exports.precompile = precompile;
  117417. exports.compile = compile;
  117418. var _exception = __webpack_require__(6);
  117419. var _exception2 = _interopRequireDefault(_exception);
  117420. var _utils = __webpack_require__(5);
  117421. var _ast = __webpack_require__(35);
  117422. var _ast2 = _interopRequireDefault(_ast);
  117423. var slice = [].slice;
  117424. function Compiler() {}
  117425. // the foundHelper register will disambiguate helper lookup from finding a
  117426. // function in a context. This is necessary for mustache compatibility, which
  117427. // requires that context functions in blocks are evaluated by blockHelperMissing,
  117428. // and then proceed as if the resulting value was provided to blockHelperMissing.
  117429. Compiler.prototype = {
  117430. compiler: Compiler,
  117431. equals: function equals(other) {
  117432. var len = this.opcodes.length;
  117433. if (other.opcodes.length !== len) {
  117434. return false;
  117435. }
  117436. for (var i = 0; i < len; i++) {
  117437. var opcode = this.opcodes[i],
  117438. otherOpcode = other.opcodes[i];
  117439. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  117440. return false;
  117441. }
  117442. }
  117443. // We know that length is the same between the two arrays because they are directly tied
  117444. // to the opcode behavior above.
  117445. len = this.children.length;
  117446. for (var i = 0; i < len; i++) {
  117447. if (!this.children[i].equals(other.children[i])) {
  117448. return false;
  117449. }
  117450. }
  117451. return true;
  117452. },
  117453. guid: 0,
  117454. compile: function compile(program, options) {
  117455. this.sourceNode = [];
  117456. this.opcodes = [];
  117457. this.children = [];
  117458. this.options = options;
  117459. this.stringParams = options.stringParams;
  117460. this.trackIds = options.trackIds;
  117461. options.blockParams = options.blockParams || [];
  117462. // These changes will propagate to the other compiler components
  117463. var knownHelpers = options.knownHelpers;
  117464. options.knownHelpers = {
  117465. 'helperMissing': true,
  117466. 'blockHelperMissing': true,
  117467. 'each': true,
  117468. 'if': true,
  117469. 'unless': true,
  117470. 'with': true,
  117471. 'log': true,
  117472. 'lookup': true
  117473. };
  117474. if (knownHelpers) {
  117475. for (var _name in knownHelpers) {
  117476. /* istanbul ignore else */
  117477. if (_name in knownHelpers) {
  117478. this.options.knownHelpers[_name] = knownHelpers[_name];
  117479. }
  117480. }
  117481. }
  117482. return this.accept(program);
  117483. },
  117484. compileProgram: function compileProgram(program) {
  117485. var childCompiler = new this.compiler(),
  117486. // eslint-disable-line new-cap
  117487. result = childCompiler.compile(program, this.options),
  117488. guid = this.guid++;
  117489. this.usePartial = this.usePartial || result.usePartial;
  117490. this.children[guid] = result;
  117491. this.useDepths = this.useDepths || result.useDepths;
  117492. return guid;
  117493. },
  117494. accept: function accept(node) {
  117495. /* istanbul ignore next: Sanity code */
  117496. if (!this[node.type]) {
  117497. throw new _exception2['default']('Unknown type: ' + node.type, node);
  117498. }
  117499. this.sourceNode.unshift(node);
  117500. var ret = this[node.type](node);
  117501. this.sourceNode.shift();
  117502. return ret;
  117503. },
  117504. Program: function Program(program) {
  117505. this.options.blockParams.unshift(program.blockParams);
  117506. var body = program.body,
  117507. bodyLength = body.length;
  117508. for (var i = 0; i < bodyLength; i++) {
  117509. this.accept(body[i]);
  117510. }
  117511. this.options.blockParams.shift();
  117512. this.isSimple = bodyLength === 1;
  117513. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  117514. return this;
  117515. },
  117516. BlockStatement: function BlockStatement(block) {
  117517. transformLiteralToPath(block);
  117518. var program = block.program,
  117519. inverse = block.inverse;
  117520. program = program && this.compileProgram(program);
  117521. inverse = inverse && this.compileProgram(inverse);
  117522. var type = this.classifySexpr(block);
  117523. if (type === 'helper') {
  117524. this.helperSexpr(block, program, inverse);
  117525. } else if (type === 'simple') {
  117526. this.simpleSexpr(block);
  117527. // now that the simple mustache is resolved, we need to
  117528. // evaluate it by executing `blockHelperMissing`
  117529. this.opcode('pushProgram', program);
  117530. this.opcode('pushProgram', inverse);
  117531. this.opcode('emptyHash');
  117532. this.opcode('blockValue', block.path.original);
  117533. } else {
  117534. this.ambiguousSexpr(block, program, inverse);
  117535. // now that the simple mustache is resolved, we need to
  117536. // evaluate it by executing `blockHelperMissing`
  117537. this.opcode('pushProgram', program);
  117538. this.opcode('pushProgram', inverse);
  117539. this.opcode('emptyHash');
  117540. this.opcode('ambiguousBlockValue');
  117541. }
  117542. this.opcode('append');
  117543. },
  117544. DecoratorBlock: function DecoratorBlock(decorator) {
  117545. var program = decorator.program && this.compileProgram(decorator.program);
  117546. var params = this.setupFullMustacheParams(decorator, program, undefined),
  117547. path = decorator.path;
  117548. this.useDecorators = true;
  117549. this.opcode('registerDecorator', params.length, path.original);
  117550. },
  117551. PartialStatement: function PartialStatement(partial) {
  117552. this.usePartial = true;
  117553. var program = partial.program;
  117554. if (program) {
  117555. program = this.compileProgram(partial.program);
  117556. }
  117557. var params = partial.params;
  117558. if (params.length > 1) {
  117559. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  117560. } else if (!params.length) {
  117561. if (this.options.explicitPartialContext) {
  117562. this.opcode('pushLiteral', 'undefined');
  117563. } else {
  117564. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  117565. }
  117566. }
  117567. var partialName = partial.name.original,
  117568. isDynamic = partial.name.type === 'SubExpression';
  117569. if (isDynamic) {
  117570. this.accept(partial.name);
  117571. }
  117572. this.setupFullMustacheParams(partial, program, undefined, true);
  117573. var indent = partial.indent || '';
  117574. if (this.options.preventIndent && indent) {
  117575. this.opcode('appendContent', indent);
  117576. indent = '';
  117577. }
  117578. this.opcode('invokePartial', isDynamic, partialName, indent);
  117579. this.opcode('append');
  117580. },
  117581. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  117582. this.PartialStatement(partialBlock);
  117583. },
  117584. MustacheStatement: function MustacheStatement(mustache) {
  117585. this.SubExpression(mustache);
  117586. if (mustache.escaped && !this.options.noEscape) {
  117587. this.opcode('appendEscaped');
  117588. } else {
  117589. this.opcode('append');
  117590. }
  117591. },
  117592. Decorator: function Decorator(decorator) {
  117593. this.DecoratorBlock(decorator);
  117594. },
  117595. ContentStatement: function ContentStatement(content) {
  117596. if (content.value) {
  117597. this.opcode('appendContent', content.value);
  117598. }
  117599. },
  117600. CommentStatement: function CommentStatement() {},
  117601. SubExpression: function SubExpression(sexpr) {
  117602. transformLiteralToPath(sexpr);
  117603. var type = this.classifySexpr(sexpr);
  117604. if (type === 'simple') {
  117605. this.simpleSexpr(sexpr);
  117606. } else if (type === 'helper') {
  117607. this.helperSexpr(sexpr);
  117608. } else {
  117609. this.ambiguousSexpr(sexpr);
  117610. }
  117611. },
  117612. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  117613. var path = sexpr.path,
  117614. name = path.parts[0],
  117615. isBlock = program != null || inverse != null;
  117616. this.opcode('getContext', path.depth);
  117617. this.opcode('pushProgram', program);
  117618. this.opcode('pushProgram', inverse);
  117619. path.strict = true;
  117620. this.accept(path);
  117621. this.opcode('invokeAmbiguous', name, isBlock);
  117622. },
  117623. simpleSexpr: function simpleSexpr(sexpr) {
  117624. var path = sexpr.path;
  117625. path.strict = true;
  117626. this.accept(path);
  117627. this.opcode('resolvePossibleLambda');
  117628. },
  117629. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  117630. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  117631. path = sexpr.path,
  117632. name = path.parts[0];
  117633. if (this.options.knownHelpers[name]) {
  117634. this.opcode('invokeKnownHelper', params.length, name);
  117635. } else if (this.options.knownHelpersOnly) {
  117636. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  117637. } else {
  117638. path.strict = true;
  117639. path.falsy = true;
  117640. this.accept(path);
  117641. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  117642. }
  117643. },
  117644. PathExpression: function PathExpression(path) {
  117645. this.addDepth(path.depth);
  117646. this.opcode('getContext', path.depth);
  117647. var name = path.parts[0],
  117648. scoped = _ast2['default'].helpers.scopedId(path),
  117649. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  117650. if (blockParamId) {
  117651. this.opcode('lookupBlockParam', blockParamId, path.parts);
  117652. } else if (!name) {
  117653. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  117654. this.opcode('pushContext');
  117655. } else if (path.data) {
  117656. this.options.data = true;
  117657. this.opcode('lookupData', path.depth, path.parts, path.strict);
  117658. } else {
  117659. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  117660. }
  117661. },
  117662. StringLiteral: function StringLiteral(string) {
  117663. this.opcode('pushString', string.value);
  117664. },
  117665. NumberLiteral: function NumberLiteral(number) {
  117666. this.opcode('pushLiteral', number.value);
  117667. },
  117668. BooleanLiteral: function BooleanLiteral(bool) {
  117669. this.opcode('pushLiteral', bool.value);
  117670. },
  117671. UndefinedLiteral: function UndefinedLiteral() {
  117672. this.opcode('pushLiteral', 'undefined');
  117673. },
  117674. NullLiteral: function NullLiteral() {
  117675. this.opcode('pushLiteral', 'null');
  117676. },
  117677. Hash: function Hash(hash) {
  117678. var pairs = hash.pairs,
  117679. i = 0,
  117680. l = pairs.length;
  117681. this.opcode('pushHash');
  117682. for (; i < l; i++) {
  117683. this.pushParam(pairs[i].value);
  117684. }
  117685. while (i--) {
  117686. this.opcode('assignToHash', pairs[i].key);
  117687. }
  117688. this.opcode('popHash');
  117689. },
  117690. // HELPERS
  117691. opcode: function opcode(name) {
  117692. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  117693. },
  117694. addDepth: function addDepth(depth) {
  117695. if (!depth) {
  117696. return;
  117697. }
  117698. this.useDepths = true;
  117699. },
  117700. classifySexpr: function classifySexpr(sexpr) {
  117701. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  117702. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  117703. // a mustache is an eligible helper if:
  117704. // * its id is simple (a single part, not `this` or `..`)
  117705. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  117706. // if a mustache is an eligible helper but not a definite
  117707. // helper, it is ambiguous, and will be resolved in a later
  117708. // pass or at runtime.
  117709. var isEligible = !isBlockParam && (isHelper || isSimple);
  117710. // if ambiguous, we can possibly resolve the ambiguity now
  117711. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  117712. if (isEligible && !isHelper) {
  117713. var _name2 = sexpr.path.parts[0],
  117714. options = this.options;
  117715. if (options.knownHelpers[_name2]) {
  117716. isHelper = true;
  117717. } else if (options.knownHelpersOnly) {
  117718. isEligible = false;
  117719. }
  117720. }
  117721. if (isHelper) {
  117722. return 'helper';
  117723. } else if (isEligible) {
  117724. return 'ambiguous';
  117725. } else {
  117726. return 'simple';
  117727. }
  117728. },
  117729. pushParams: function pushParams(params) {
  117730. for (var i = 0, l = params.length; i < l; i++) {
  117731. this.pushParam(params[i]);
  117732. }
  117733. },
  117734. pushParam: function pushParam(val) {
  117735. var value = val.value != null ? val.value : val.original || '';
  117736. if (this.stringParams) {
  117737. if (value.replace) {
  117738. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  117739. }
  117740. if (val.depth) {
  117741. this.addDepth(val.depth);
  117742. }
  117743. this.opcode('getContext', val.depth || 0);
  117744. this.opcode('pushStringParam', value, val.type);
  117745. if (val.type === 'SubExpression') {
  117746. // SubExpressions get evaluated and passed in
  117747. // in string params mode.
  117748. this.accept(val);
  117749. }
  117750. } else {
  117751. if (this.trackIds) {
  117752. var blockParamIndex = undefined;
  117753. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  117754. blockParamIndex = this.blockParamIndex(val.parts[0]);
  117755. }
  117756. if (blockParamIndex) {
  117757. var blockParamChild = val.parts.slice(1).join('.');
  117758. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  117759. } else {
  117760. value = val.original || value;
  117761. if (value.replace) {
  117762. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  117763. }
  117764. this.opcode('pushId', val.type, value);
  117765. }
  117766. }
  117767. this.accept(val);
  117768. }
  117769. },
  117770. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  117771. var params = sexpr.params;
  117772. this.pushParams(params);
  117773. this.opcode('pushProgram', program);
  117774. this.opcode('pushProgram', inverse);
  117775. if (sexpr.hash) {
  117776. this.accept(sexpr.hash);
  117777. } else {
  117778. this.opcode('emptyHash', omitEmpty);
  117779. }
  117780. return params;
  117781. },
  117782. blockParamIndex: function blockParamIndex(name) {
  117783. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  117784. var blockParams = this.options.blockParams[depth],
  117785. param = blockParams && _utils.indexOf(blockParams, name);
  117786. if (blockParams && param >= 0) {
  117787. return [depth, param];
  117788. }
  117789. }
  117790. }
  117791. };
  117792. function precompile(input, options, env) {
  117793. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117794. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  117795. }
  117796. options = options || {};
  117797. if (!('data' in options)) {
  117798. options.data = true;
  117799. }
  117800. if (options.compat) {
  117801. options.useDepths = true;
  117802. }
  117803. var ast = env.parse(input, options),
  117804. environment = new env.Compiler().compile(ast, options);
  117805. return new env.JavaScriptCompiler().compile(environment, options);
  117806. }
  117807. function compile(input, options, env) {
  117808. if (options === undefined) options = {};
  117809. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117810. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  117811. }
  117812. options = _utils.extend({}, options);
  117813. if (!('data' in options)) {
  117814. options.data = true;
  117815. }
  117816. if (options.compat) {
  117817. options.useDepths = true;
  117818. }
  117819. var compiled = undefined;
  117820. function compileInput() {
  117821. var ast = env.parse(input, options),
  117822. environment = new env.Compiler().compile(ast, options),
  117823. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  117824. return env.template(templateSpec);
  117825. }
  117826. // Template is only compiled on first use and cached after that point.
  117827. function ret(context, execOptions) {
  117828. if (!compiled) {
  117829. compiled = compileInput();
  117830. }
  117831. return compiled.call(this, context, execOptions);
  117832. }
  117833. ret._setup = function (setupOptions) {
  117834. if (!compiled) {
  117835. compiled = compileInput();
  117836. }
  117837. return compiled._setup(setupOptions);
  117838. };
  117839. ret._child = function (i, data, blockParams, depths) {
  117840. if (!compiled) {
  117841. compiled = compileInput();
  117842. }
  117843. return compiled._child(i, data, blockParams, depths);
  117844. };
  117845. return ret;
  117846. }
  117847. function argEquals(a, b) {
  117848. if (a === b) {
  117849. return true;
  117850. }
  117851. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  117852. for (var i = 0; i < a.length; i++) {
  117853. if (!argEquals(a[i], b[i])) {
  117854. return false;
  117855. }
  117856. }
  117857. return true;
  117858. }
  117859. }
  117860. function transformLiteralToPath(sexpr) {
  117861. if (!sexpr.path.parts) {
  117862. var literal = sexpr.path;
  117863. // Casting to string here to make false and 0 literal values play nicely with the rest
  117864. // of the system.
  117865. sexpr.path = {
  117866. type: 'PathExpression',
  117867. data: false,
  117868. depth: 0,
  117869. parts: [literal.original + ''],
  117870. original: literal.original + '',
  117871. loc: literal.loc
  117872. };
  117873. }
  117874. }
  117875. /***/ }),
  117876. /* 42 */
  117877. /***/ (function(module, exports, __webpack_require__) {
  117878. 'use strict';
  117879. var _interopRequireDefault = __webpack_require__(1)['default'];
  117880. exports.__esModule = true;
  117881. var _base = __webpack_require__(4);
  117882. var _exception = __webpack_require__(6);
  117883. var _exception2 = _interopRequireDefault(_exception);
  117884. var _utils = __webpack_require__(5);
  117885. var _codeGen = __webpack_require__(43);
  117886. var _codeGen2 = _interopRequireDefault(_codeGen);
  117887. function Literal(value) {
  117888. this.value = value;
  117889. }
  117890. function JavaScriptCompiler() {}
  117891. JavaScriptCompiler.prototype = {
  117892. // PUBLIC API: You can override these methods in a subclass to provide
  117893. // alternative compiled forms for name lookup and buffering semantics
  117894. nameLookup: function nameLookup(parent, name /* , type*/) {
  117895. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  117896. return [parent, '.', name];
  117897. } else {
  117898. return [parent, '[', JSON.stringify(name), ']'];
  117899. }
  117900. },
  117901. depthedLookup: function depthedLookup(name) {
  117902. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  117903. },
  117904. compilerInfo: function compilerInfo() {
  117905. var revision = _base.COMPILER_REVISION,
  117906. versions = _base.REVISION_CHANGES[revision];
  117907. return [revision, versions];
  117908. },
  117909. appendToBuffer: function appendToBuffer(source, location, explicit) {
  117910. // Force a source as this simplifies the merge logic.
  117911. if (!_utils.isArray(source)) {
  117912. source = [source];
  117913. }
  117914. source = this.source.wrap(source, location);
  117915. if (this.environment.isSimple) {
  117916. return ['return ', source, ';'];
  117917. } else if (explicit) {
  117918. // This is a case where the buffer operation occurs as a child of another
  117919. // construct, generally braces. We have to explicitly output these buffer
  117920. // operations to ensure that the emitted code goes in the correct location.
  117921. return ['buffer += ', source, ';'];
  117922. } else {
  117923. source.appendToBuffer = true;
  117924. return source;
  117925. }
  117926. },
  117927. initializeBuffer: function initializeBuffer() {
  117928. return this.quotedString('');
  117929. },
  117930. // END PUBLIC API
  117931. compile: function compile(environment, options, context, asObject) {
  117932. this.environment = environment;
  117933. this.options = options;
  117934. this.stringParams = this.options.stringParams;
  117935. this.trackIds = this.options.trackIds;
  117936. this.precompile = !asObject;
  117937. this.name = this.environment.name;
  117938. this.isChild = !!context;
  117939. this.context = context || {
  117940. decorators: [],
  117941. programs: [],
  117942. environments: []
  117943. };
  117944. this.preamble();
  117945. this.stackSlot = 0;
  117946. this.stackVars = [];
  117947. this.aliases = {};
  117948. this.registers = { list: [] };
  117949. this.hashes = [];
  117950. this.compileStack = [];
  117951. this.inlineStack = [];
  117952. this.blockParams = [];
  117953. this.compileChildren(environment, options);
  117954. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  117955. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  117956. var opcodes = environment.opcodes,
  117957. opcode = undefined,
  117958. firstLoc = undefined,
  117959. i = undefined,
  117960. l = undefined;
  117961. for (i = 0, l = opcodes.length; i < l; i++) {
  117962. opcode = opcodes[i];
  117963. this.source.currentLocation = opcode.loc;
  117964. firstLoc = firstLoc || opcode.loc;
  117965. this[opcode.opcode].apply(this, opcode.args);
  117966. }
  117967. // Flush any trailing content that might be pending.
  117968. this.source.currentLocation = firstLoc;
  117969. this.pushSource('');
  117970. /* istanbul ignore next */
  117971. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  117972. throw new _exception2['default']('Compile completed with content left on stack');
  117973. }
  117974. if (!this.decorators.isEmpty()) {
  117975. this.useDecorators = true;
  117976. this.decorators.prepend('var decorators = container.decorators;\n');
  117977. this.decorators.push('return fn;');
  117978. if (asObject) {
  117979. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  117980. } else {
  117981. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  117982. this.decorators.push('}\n');
  117983. this.decorators = this.decorators.merge();
  117984. }
  117985. } else {
  117986. this.decorators = undefined;
  117987. }
  117988. var fn = this.createFunctionContext(asObject);
  117989. if (!this.isChild) {
  117990. var ret = {
  117991. compiler: this.compilerInfo(),
  117992. main: fn
  117993. };
  117994. if (this.decorators) {
  117995. ret.main_d = this.decorators; // eslint-disable-line camelcase
  117996. ret.useDecorators = true;
  117997. }
  117998. var _context = this.context;
  117999. var programs = _context.programs;
  118000. var decorators = _context.decorators;
  118001. for (i = 0, l = programs.length; i < l; i++) {
  118002. if (programs[i]) {
  118003. ret[i] = programs[i];
  118004. if (decorators[i]) {
  118005. ret[i + '_d'] = decorators[i];
  118006. ret.useDecorators = true;
  118007. }
  118008. }
  118009. }
  118010. if (this.environment.usePartial) {
  118011. ret.usePartial = true;
  118012. }
  118013. if (this.options.data) {
  118014. ret.useData = true;
  118015. }
  118016. if (this.useDepths) {
  118017. ret.useDepths = true;
  118018. }
  118019. if (this.useBlockParams) {
  118020. ret.useBlockParams = true;
  118021. }
  118022. if (this.options.compat) {
  118023. ret.compat = true;
  118024. }
  118025. if (!asObject) {
  118026. ret.compiler = JSON.stringify(ret.compiler);
  118027. this.source.currentLocation = { start: { line: 1, column: 0 } };
  118028. ret = this.objectLiteral(ret);
  118029. if (options.srcName) {
  118030. ret = ret.toStringWithSourceMap({ file: options.destName });
  118031. ret.map = ret.map && ret.map.toString();
  118032. } else {
  118033. ret = ret.toString();
  118034. }
  118035. } else {
  118036. ret.compilerOptions = this.options;
  118037. }
  118038. return ret;
  118039. } else {
  118040. return fn;
  118041. }
  118042. },
  118043. preamble: function preamble() {
  118044. // track the last context pushed into place to allow skipping the
  118045. // getContext opcode when it would be a noop
  118046. this.lastContext = 0;
  118047. this.source = new _codeGen2['default'](this.options.srcName);
  118048. this.decorators = new _codeGen2['default'](this.options.srcName);
  118049. },
  118050. createFunctionContext: function createFunctionContext(asObject) {
  118051. var varDeclarations = '';
  118052. var locals = this.stackVars.concat(this.registers.list);
  118053. if (locals.length > 0) {
  118054. varDeclarations += ', ' + locals.join(', ');
  118055. }
  118056. // Generate minimizer alias mappings
  118057. //
  118058. // When using true SourceNodes, this will update all references to the given alias
  118059. // as the source nodes are reused in situ. For the non-source node compilation mode,
  118060. // aliases will not be used, but this case is already being run on the client and
  118061. // we aren't concern about minimizing the template size.
  118062. var aliasCount = 0;
  118063. for (var alias in this.aliases) {
  118064. // eslint-disable-line guard-for-in
  118065. var node = this.aliases[alias];
  118066. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  118067. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  118068. node.children[0] = 'alias' + aliasCount;
  118069. }
  118070. }
  118071. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  118072. if (this.useBlockParams || this.useDepths) {
  118073. params.push('blockParams');
  118074. }
  118075. if (this.useDepths) {
  118076. params.push('depths');
  118077. }
  118078. // Perform a second pass over the output to merge content when possible
  118079. var source = this.mergeSource(varDeclarations);
  118080. if (asObject) {
  118081. params.push(source);
  118082. return Function.apply(this, params);
  118083. } else {
  118084. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  118085. }
  118086. },
  118087. mergeSource: function mergeSource(varDeclarations) {
  118088. var isSimple = this.environment.isSimple,
  118089. appendOnly = !this.forceBuffer,
  118090. appendFirst = undefined,
  118091. sourceSeen = undefined,
  118092. bufferStart = undefined,
  118093. bufferEnd = undefined;
  118094. this.source.each(function (line) {
  118095. if (line.appendToBuffer) {
  118096. if (bufferStart) {
  118097. line.prepend(' + ');
  118098. } else {
  118099. bufferStart = line;
  118100. }
  118101. bufferEnd = line;
  118102. } else {
  118103. if (bufferStart) {
  118104. if (!sourceSeen) {
  118105. appendFirst = true;
  118106. } else {
  118107. bufferStart.prepend('buffer += ');
  118108. }
  118109. bufferEnd.add(';');
  118110. bufferStart = bufferEnd = undefined;
  118111. }
  118112. sourceSeen = true;
  118113. if (!isSimple) {
  118114. appendOnly = false;
  118115. }
  118116. }
  118117. });
  118118. if (appendOnly) {
  118119. if (bufferStart) {
  118120. bufferStart.prepend('return ');
  118121. bufferEnd.add(';');
  118122. } else if (!sourceSeen) {
  118123. this.source.push('return "";');
  118124. }
  118125. } else {
  118126. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  118127. if (bufferStart) {
  118128. bufferStart.prepend('return buffer + ');
  118129. bufferEnd.add(';');
  118130. } else {
  118131. this.source.push('return buffer;');
  118132. }
  118133. }
  118134. if (varDeclarations) {
  118135. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  118136. }
  118137. return this.source.merge();
  118138. },
  118139. // [blockValue]
  118140. //
  118141. // On stack, before: hash, inverse, program, value
  118142. // On stack, after: return value of blockHelperMissing
  118143. //
  118144. // The purpose of this opcode is to take a block of the form
  118145. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  118146. // replace it on the stack with the result of properly
  118147. // invoking blockHelperMissing.
  118148. blockValue: function blockValue(name) {
  118149. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  118150. params = [this.contextName(0)];
  118151. this.setupHelperArgs(name, 0, params);
  118152. var blockName = this.popStack();
  118153. params.splice(1, 0, blockName);
  118154. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  118155. },
  118156. // [ambiguousBlockValue]
  118157. //
  118158. // On stack, before: hash, inverse, program, value
  118159. // Compiler value, before: lastHelper=value of last found helper, if any
  118160. // On stack, after, if no lastHelper: same as [blockValue]
  118161. // On stack, after, if lastHelper: value
  118162. ambiguousBlockValue: function ambiguousBlockValue() {
  118163. // We're being a bit cheeky and reusing the options value from the prior exec
  118164. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  118165. params = [this.contextName(0)];
  118166. this.setupHelperArgs('', 0, params, true);
  118167. this.flushInline();
  118168. var current = this.topStack();
  118169. params.splice(1, 0, current);
  118170. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  118171. },
  118172. // [appendContent]
  118173. //
  118174. // On stack, before: ...
  118175. // On stack, after: ...
  118176. //
  118177. // Appends the string value of `content` to the current buffer
  118178. appendContent: function appendContent(content) {
  118179. if (this.pendingContent) {
  118180. content = this.pendingContent + content;
  118181. } else {
  118182. this.pendingLocation = this.source.currentLocation;
  118183. }
  118184. this.pendingContent = content;
  118185. },
  118186. // [append]
  118187. //
  118188. // On stack, before: value, ...
  118189. // On stack, after: ...
  118190. //
  118191. // Coerces `value` to a String and appends it to the current buffer.
  118192. //
  118193. // If `value` is truthy, or 0, it is coerced into a string and appended
  118194. // Otherwise, the empty string is appended
  118195. append: function append() {
  118196. if (this.isInline()) {
  118197. this.replaceStack(function (current) {
  118198. return [' != null ? ', current, ' : ""'];
  118199. });
  118200. this.pushSource(this.appendToBuffer(this.popStack()));
  118201. } else {
  118202. var local = this.popStack();
  118203. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  118204. if (this.environment.isSimple) {
  118205. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  118206. }
  118207. }
  118208. },
  118209. // [appendEscaped]
  118210. //
  118211. // On stack, before: value, ...
  118212. // On stack, after: ...
  118213. //
  118214. // Escape `value` and append it to the buffer
  118215. appendEscaped: function appendEscaped() {
  118216. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  118217. },
  118218. // [getContext]
  118219. //
  118220. // On stack, before: ...
  118221. // On stack, after: ...
  118222. // Compiler value, after: lastContext=depth
  118223. //
  118224. // Set the value of the `lastContext` compiler value to the depth
  118225. getContext: function getContext(depth) {
  118226. this.lastContext = depth;
  118227. },
  118228. // [pushContext]
  118229. //
  118230. // On stack, before: ...
  118231. // On stack, after: currentContext, ...
  118232. //
  118233. // Pushes the value of the current context onto the stack.
  118234. pushContext: function pushContext() {
  118235. this.pushStackLiteral(this.contextName(this.lastContext));
  118236. },
  118237. // [lookupOnContext]
  118238. //
  118239. // On stack, before: ...
  118240. // On stack, after: currentContext[name], ...
  118241. //
  118242. // Looks up the value of `name` on the current context and pushes
  118243. // it onto the stack.
  118244. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  118245. var i = 0;
  118246. if (!scoped && this.options.compat && !this.lastContext) {
  118247. // The depthed query is expected to handle the undefined logic for the root level that
  118248. // is implemented below, so we evaluate that directly in compat mode
  118249. this.push(this.depthedLookup(parts[i++]));
  118250. } else {
  118251. this.pushContext();
  118252. }
  118253. this.resolvePath('context', parts, i, falsy, strict);
  118254. },
  118255. // [lookupBlockParam]
  118256. //
  118257. // On stack, before: ...
  118258. // On stack, after: blockParam[name], ...
  118259. //
  118260. // Looks up the value of `parts` on the given block param and pushes
  118261. // it onto the stack.
  118262. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  118263. this.useBlockParams = true;
  118264. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  118265. this.resolvePath('context', parts, 1);
  118266. },
  118267. // [lookupData]
  118268. //
  118269. // On stack, before: ...
  118270. // On stack, after: data, ...
  118271. //
  118272. // Push the data lookup operator
  118273. lookupData: function lookupData(depth, parts, strict) {
  118274. if (!depth) {
  118275. this.pushStackLiteral('data');
  118276. } else {
  118277. this.pushStackLiteral('container.data(data, ' + depth + ')');
  118278. }
  118279. this.resolvePath('data', parts, 0, true, strict);
  118280. },
  118281. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  118282. // istanbul ignore next
  118283. var _this = this;
  118284. if (this.options.strict || this.options.assumeObjects) {
  118285. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  118286. return;
  118287. }
  118288. var len = parts.length;
  118289. for (; i < len; i++) {
  118290. /* eslint-disable no-loop-func */
  118291. this.replaceStack(function (current) {
  118292. var lookup = _this.nameLookup(current, parts[i], type);
  118293. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  118294. // needs to have the special handling for these values.
  118295. if (!falsy) {
  118296. return [' != null ? ', lookup, ' : ', current];
  118297. } else {
  118298. // Otherwise we can use generic falsy handling
  118299. return [' && ', lookup];
  118300. }
  118301. });
  118302. /* eslint-enable no-loop-func */
  118303. }
  118304. },
  118305. // [resolvePossibleLambda]
  118306. //
  118307. // On stack, before: value, ...
  118308. // On stack, after: resolved value, ...
  118309. //
  118310. // If the `value` is a lambda, replace it on the stack by
  118311. // the return value of the lambda
  118312. resolvePossibleLambda: function resolvePossibleLambda() {
  118313. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  118314. },
  118315. // [pushStringParam]
  118316. //
  118317. // On stack, before: ...
  118318. // On stack, after: string, currentContext, ...
  118319. //
  118320. // This opcode is designed for use in string mode, which
  118321. // provides the string value of a parameter along with its
  118322. // depth rather than resolving it immediately.
  118323. pushStringParam: function pushStringParam(string, type) {
  118324. this.pushContext();
  118325. this.pushString(type);
  118326. // If it's a subexpression, the string result
  118327. // will be pushed after this opcode.
  118328. if (type !== 'SubExpression') {
  118329. if (typeof string === 'string') {
  118330. this.pushString(string);
  118331. } else {
  118332. this.pushStackLiteral(string);
  118333. }
  118334. }
  118335. },
  118336. emptyHash: function emptyHash(omitEmpty) {
  118337. if (this.trackIds) {
  118338. this.push('{}'); // hashIds
  118339. }
  118340. if (this.stringParams) {
  118341. this.push('{}'); // hashContexts
  118342. this.push('{}'); // hashTypes
  118343. }
  118344. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  118345. },
  118346. pushHash: function pushHash() {
  118347. if (this.hash) {
  118348. this.hashes.push(this.hash);
  118349. }
  118350. this.hash = { values: [], types: [], contexts: [], ids: [] };
  118351. },
  118352. popHash: function popHash() {
  118353. var hash = this.hash;
  118354. this.hash = this.hashes.pop();
  118355. if (this.trackIds) {
  118356. this.push(this.objectLiteral(hash.ids));
  118357. }
  118358. if (this.stringParams) {
  118359. this.push(this.objectLiteral(hash.contexts));
  118360. this.push(this.objectLiteral(hash.types));
  118361. }
  118362. this.push(this.objectLiteral(hash.values));
  118363. },
  118364. // [pushString]
  118365. //
  118366. // On stack, before: ...
  118367. // On stack, after: quotedString(string), ...
  118368. //
  118369. // Push a quoted version of `string` onto the stack
  118370. pushString: function pushString(string) {
  118371. this.pushStackLiteral(this.quotedString(string));
  118372. },
  118373. // [pushLiteral]
  118374. //
  118375. // On stack, before: ...
  118376. // On stack, after: value, ...
  118377. //
  118378. // Pushes a value onto the stack. This operation prevents
  118379. // the compiler from creating a temporary variable to hold
  118380. // it.
  118381. pushLiteral: function pushLiteral(value) {
  118382. this.pushStackLiteral(value);
  118383. },
  118384. // [pushProgram]
  118385. //
  118386. // On stack, before: ...
  118387. // On stack, after: program(guid), ...
  118388. //
  118389. // Push a program expression onto the stack. This takes
  118390. // a compile-time guid and converts it into a runtime-accessible
  118391. // expression.
  118392. pushProgram: function pushProgram(guid) {
  118393. if (guid != null) {
  118394. this.pushStackLiteral(this.programExpression(guid));
  118395. } else {
  118396. this.pushStackLiteral(null);
  118397. }
  118398. },
  118399. // [registerDecorator]
  118400. //
  118401. // On stack, before: hash, program, params..., ...
  118402. // On stack, after: ...
  118403. //
  118404. // Pops off the decorator's parameters, invokes the decorator,
  118405. // and inserts the decorator into the decorators list.
  118406. registerDecorator: function registerDecorator(paramSize, name) {
  118407. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  118408. options = this.setupHelperArgs(name, paramSize);
  118409. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  118410. },
  118411. // [invokeHelper]
  118412. //
  118413. // On stack, before: hash, inverse, program, params..., ...
  118414. // On stack, after: result of helper invocation
  118415. //
  118416. // Pops off the helper's parameters, invokes the helper,
  118417. // and pushes the helper's return value onto the stack.
  118418. //
  118419. // If the helper is not found, `helperMissing` is called.
  118420. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  118421. var nonHelper = this.popStack(),
  118422. helper = this.setupHelper(paramSize, name),
  118423. simple = isSimple ? [helper.name, ' || '] : '';
  118424. var lookup = ['('].concat(simple, nonHelper);
  118425. if (!this.options.strict) {
  118426. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  118427. }
  118428. lookup.push(')');
  118429. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  118430. },
  118431. // [invokeKnownHelper]
  118432. //
  118433. // On stack, before: hash, inverse, program, params..., ...
  118434. // On stack, after: result of helper invocation
  118435. //
  118436. // This operation is used when the helper is known to exist,
  118437. // so a `helperMissing` fallback is not required.
  118438. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  118439. var helper = this.setupHelper(paramSize, name);
  118440. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  118441. },
  118442. // [invokeAmbiguous]
  118443. //
  118444. // On stack, before: hash, inverse, program, params..., ...
  118445. // On stack, after: result of disambiguation
  118446. //
  118447. // This operation is used when an expression like `{{foo}}`
  118448. // is provided, but we don't know at compile-time whether it
  118449. // is a helper or a path.
  118450. //
  118451. // This operation emits more code than the other options,
  118452. // and can be avoided by passing the `knownHelpers` and
  118453. // `knownHelpersOnly` flags at compile-time.
  118454. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  118455. this.useRegister('helper');
  118456. var nonHelper = this.popStack();
  118457. this.emptyHash();
  118458. var helper = this.setupHelper(0, name, helperCall);
  118459. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  118460. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  118461. if (!this.options.strict) {
  118462. lookup[0] = '(helper = ';
  118463. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  118464. }
  118465. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  118466. },
  118467. // [invokePartial]
  118468. //
  118469. // On stack, before: context, ...
  118470. // On stack after: result of partial invocation
  118471. //
  118472. // This operation pops off a context, invokes a partial with that context,
  118473. // and pushes the result of the invocation back.
  118474. invokePartial: function invokePartial(isDynamic, name, indent) {
  118475. var params = [],
  118476. options = this.setupParams(name, 1, params);
  118477. if (isDynamic) {
  118478. name = this.popStack();
  118479. delete options.name;
  118480. }
  118481. if (indent) {
  118482. options.indent = JSON.stringify(indent);
  118483. }
  118484. options.helpers = 'helpers';
  118485. options.partials = 'partials';
  118486. options.decorators = 'container.decorators';
  118487. if (!isDynamic) {
  118488. params.unshift(this.nameLookup('partials', name, 'partial'));
  118489. } else {
  118490. params.unshift(name);
  118491. }
  118492. if (this.options.compat) {
  118493. options.depths = 'depths';
  118494. }
  118495. options = this.objectLiteral(options);
  118496. params.push(options);
  118497. this.push(this.source.functionCall('container.invokePartial', '', params));
  118498. },
  118499. // [assignToHash]
  118500. //
  118501. // On stack, before: value, ..., hash, ...
  118502. // On stack, after: ..., hash, ...
  118503. //
  118504. // Pops a value off the stack and assigns it to the current hash
  118505. assignToHash: function assignToHash(key) {
  118506. var value = this.popStack(),
  118507. context = undefined,
  118508. type = undefined,
  118509. id = undefined;
  118510. if (this.trackIds) {
  118511. id = this.popStack();
  118512. }
  118513. if (this.stringParams) {
  118514. type = this.popStack();
  118515. context = this.popStack();
  118516. }
  118517. var hash = this.hash;
  118518. if (context) {
  118519. hash.contexts[key] = context;
  118520. }
  118521. if (type) {
  118522. hash.types[key] = type;
  118523. }
  118524. if (id) {
  118525. hash.ids[key] = id;
  118526. }
  118527. hash.values[key] = value;
  118528. },
  118529. pushId: function pushId(type, name, child) {
  118530. if (type === 'BlockParam') {
  118531. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  118532. } else if (type === 'PathExpression') {
  118533. this.pushString(name);
  118534. } else if (type === 'SubExpression') {
  118535. this.pushStackLiteral('true');
  118536. } else {
  118537. this.pushStackLiteral('null');
  118538. }
  118539. },
  118540. // HELPERS
  118541. compiler: JavaScriptCompiler,
  118542. compileChildren: function compileChildren(environment, options) {
  118543. var children = environment.children,
  118544. child = undefined,
  118545. compiler = undefined;
  118546. for (var i = 0, l = children.length; i < l; i++) {
  118547. child = children[i];
  118548. compiler = new this.compiler(); // eslint-disable-line new-cap
  118549. var existing = this.matchExistingProgram(child);
  118550. if (existing == null) {
  118551. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  118552. var index = this.context.programs.length;
  118553. child.index = index;
  118554. child.name = 'program' + index;
  118555. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  118556. this.context.decorators[index] = compiler.decorators;
  118557. this.context.environments[index] = child;
  118558. this.useDepths = this.useDepths || compiler.useDepths;
  118559. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  118560. child.useDepths = this.useDepths;
  118561. child.useBlockParams = this.useBlockParams;
  118562. } else {
  118563. child.index = existing.index;
  118564. child.name = 'program' + existing.index;
  118565. this.useDepths = this.useDepths || existing.useDepths;
  118566. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  118567. }
  118568. }
  118569. },
  118570. matchExistingProgram: function matchExistingProgram(child) {
  118571. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  118572. var environment = this.context.environments[i];
  118573. if (environment && environment.equals(child)) {
  118574. return environment;
  118575. }
  118576. }
  118577. },
  118578. programExpression: function programExpression(guid) {
  118579. var child = this.environment.children[guid],
  118580. programParams = [child.index, 'data', child.blockParams];
  118581. if (this.useBlockParams || this.useDepths) {
  118582. programParams.push('blockParams');
  118583. }
  118584. if (this.useDepths) {
  118585. programParams.push('depths');
  118586. }
  118587. return 'container.program(' + programParams.join(', ') + ')';
  118588. },
  118589. useRegister: function useRegister(name) {
  118590. if (!this.registers[name]) {
  118591. this.registers[name] = true;
  118592. this.registers.list.push(name);
  118593. }
  118594. },
  118595. push: function push(expr) {
  118596. if (!(expr instanceof Literal)) {
  118597. expr = this.source.wrap(expr);
  118598. }
  118599. this.inlineStack.push(expr);
  118600. return expr;
  118601. },
  118602. pushStackLiteral: function pushStackLiteral(item) {
  118603. this.push(new Literal(item));
  118604. },
  118605. pushSource: function pushSource(source) {
  118606. if (this.pendingContent) {
  118607. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  118608. this.pendingContent = undefined;
  118609. }
  118610. if (source) {
  118611. this.source.push(source);
  118612. }
  118613. },
  118614. replaceStack: function replaceStack(callback) {
  118615. var prefix = ['('],
  118616. stack = undefined,
  118617. createdStack = undefined,
  118618. usedLiteral = undefined;
  118619. /* istanbul ignore next */
  118620. if (!this.isInline()) {
  118621. throw new _exception2['default']('replaceStack on non-inline');
  118622. }
  118623. // We want to merge the inline statement into the replacement statement via ','
  118624. var top = this.popStack(true);
  118625. if (top instanceof Literal) {
  118626. // Literals do not need to be inlined
  118627. stack = [top.value];
  118628. prefix = ['(', stack];
  118629. usedLiteral = true;
  118630. } else {
  118631. // Get or create the current stack name for use by the inline
  118632. createdStack = true;
  118633. var _name = this.incrStack();
  118634. prefix = ['((', this.push(_name), ' = ', top, ')'];
  118635. stack = this.topStack();
  118636. }
  118637. var item = callback.call(this, stack);
  118638. if (!usedLiteral) {
  118639. this.popStack();
  118640. }
  118641. if (createdStack) {
  118642. this.stackSlot--;
  118643. }
  118644. this.push(prefix.concat(item, ')'));
  118645. },
  118646. incrStack: function incrStack() {
  118647. this.stackSlot++;
  118648. if (this.stackSlot > this.stackVars.length) {
  118649. this.stackVars.push('stack' + this.stackSlot);
  118650. }
  118651. return this.topStackName();
  118652. },
  118653. topStackName: function topStackName() {
  118654. return 'stack' + this.stackSlot;
  118655. },
  118656. flushInline: function flushInline() {
  118657. var inlineStack = this.inlineStack;
  118658. this.inlineStack = [];
  118659. for (var i = 0, len = inlineStack.length; i < len; i++) {
  118660. var entry = inlineStack[i];
  118661. /* istanbul ignore if */
  118662. if (entry instanceof Literal) {
  118663. this.compileStack.push(entry);
  118664. } else {
  118665. var stack = this.incrStack();
  118666. this.pushSource([stack, ' = ', entry, ';']);
  118667. this.compileStack.push(stack);
  118668. }
  118669. }
  118670. },
  118671. isInline: function isInline() {
  118672. return this.inlineStack.length;
  118673. },
  118674. popStack: function popStack(wrapped) {
  118675. var inline = this.isInline(),
  118676. item = (inline ? this.inlineStack : this.compileStack).pop();
  118677. if (!wrapped && item instanceof Literal) {
  118678. return item.value;
  118679. } else {
  118680. if (!inline) {
  118681. /* istanbul ignore next */
  118682. if (!this.stackSlot) {
  118683. throw new _exception2['default']('Invalid stack pop');
  118684. }
  118685. this.stackSlot--;
  118686. }
  118687. return item;
  118688. }
  118689. },
  118690. topStack: function topStack() {
  118691. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  118692. item = stack[stack.length - 1];
  118693. /* istanbul ignore if */
  118694. if (item instanceof Literal) {
  118695. return item.value;
  118696. } else {
  118697. return item;
  118698. }
  118699. },
  118700. contextName: function contextName(context) {
  118701. if (this.useDepths && context) {
  118702. return 'depths[' + context + ']';
  118703. } else {
  118704. return 'depth' + context;
  118705. }
  118706. },
  118707. quotedString: function quotedString(str) {
  118708. return this.source.quotedString(str);
  118709. },
  118710. objectLiteral: function objectLiteral(obj) {
  118711. return this.source.objectLiteral(obj);
  118712. },
  118713. aliasable: function aliasable(name) {
  118714. var ret = this.aliases[name];
  118715. if (ret) {
  118716. ret.referenceCount++;
  118717. return ret;
  118718. }
  118719. ret = this.aliases[name] = this.source.wrap(name);
  118720. ret.aliasable = true;
  118721. ret.referenceCount = 1;
  118722. return ret;
  118723. },
  118724. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  118725. var params = [],
  118726. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  118727. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  118728. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  118729. return {
  118730. params: params,
  118731. paramsInit: paramsInit,
  118732. name: foundHelper,
  118733. callParams: [callContext].concat(params)
  118734. };
  118735. },
  118736. setupParams: function setupParams(helper, paramSize, params) {
  118737. var options = {},
  118738. contexts = [],
  118739. types = [],
  118740. ids = [],
  118741. objectArgs = !params,
  118742. param = undefined;
  118743. if (objectArgs) {
  118744. params = [];
  118745. }
  118746. options.name = this.quotedString(helper);
  118747. options.hash = this.popStack();
  118748. if (this.trackIds) {
  118749. options.hashIds = this.popStack();
  118750. }
  118751. if (this.stringParams) {
  118752. options.hashTypes = this.popStack();
  118753. options.hashContexts = this.popStack();
  118754. }
  118755. var inverse = this.popStack(),
  118756. program = this.popStack();
  118757. // Avoid setting fn and inverse if neither are set. This allows
  118758. // helpers to do a check for `if (options.fn)`
  118759. if (program || inverse) {
  118760. options.fn = program || 'container.noop';
  118761. options.inverse = inverse || 'container.noop';
  118762. }
  118763. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  118764. // so we need to pop them off the stack in reverse order
  118765. var i = paramSize;
  118766. while (i--) {
  118767. param = this.popStack();
  118768. params[i] = param;
  118769. if (this.trackIds) {
  118770. ids[i] = this.popStack();
  118771. }
  118772. if (this.stringParams) {
  118773. types[i] = this.popStack();
  118774. contexts[i] = this.popStack();
  118775. }
  118776. }
  118777. if (objectArgs) {
  118778. options.args = this.source.generateArray(params);
  118779. }
  118780. if (this.trackIds) {
  118781. options.ids = this.source.generateArray(ids);
  118782. }
  118783. if (this.stringParams) {
  118784. options.types = this.source.generateArray(types);
  118785. options.contexts = this.source.generateArray(contexts);
  118786. }
  118787. if (this.options.data) {
  118788. options.data = 'data';
  118789. }
  118790. if (this.useBlockParams) {
  118791. options.blockParams = 'blockParams';
  118792. }
  118793. return options;
  118794. },
  118795. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  118796. var options = this.setupParams(helper, paramSize, params);
  118797. options = this.objectLiteral(options);
  118798. if (useRegister) {
  118799. this.useRegister('options');
  118800. params.push('options');
  118801. return ['options=', options];
  118802. } else if (params) {
  118803. params.push(options);
  118804. return '';
  118805. } else {
  118806. return options;
  118807. }
  118808. }
  118809. };
  118810. (function () {
  118811. var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' ');
  118812. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  118813. for (var i = 0, l = reservedWords.length; i < l; i++) {
  118814. compilerWords[reservedWords[i]] = true;
  118815. }
  118816. })();
  118817. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  118818. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  118819. };
  118820. function strictLookup(requireTerminal, compiler, parts, type) {
  118821. var stack = compiler.popStack(),
  118822. i = 0,
  118823. len = parts.length;
  118824. if (requireTerminal) {
  118825. len--;
  118826. }
  118827. for (; i < len; i++) {
  118828. stack = compiler.nameLookup(stack, parts[i], type);
  118829. }
  118830. if (requireTerminal) {
  118831. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  118832. } else {
  118833. return stack;
  118834. }
  118835. }
  118836. exports['default'] = JavaScriptCompiler;
  118837. module.exports = exports['default'];
  118838. /***/ }),
  118839. /* 43 */
  118840. /***/ (function(module, exports, __webpack_require__) {
  118841. /* global define */
  118842. 'use strict';
  118843. exports.__esModule = true;
  118844. var _utils = __webpack_require__(5);
  118845. var SourceNode = undefined;
  118846. try {
  118847. /* istanbul ignore next */
  118848. if (false) {
  118849. // We don't support this in AMD environments. For these environments, we asusme that
  118850. // they are running on the browser and thus have no need for the source-map library.
  118851. var SourceMap = require('source-map');
  118852. SourceNode = SourceMap.SourceNode;
  118853. }
  118854. } catch (err) {}
  118855. /* NOP */
  118856. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  118857. if (!SourceNode) {
  118858. SourceNode = function (line, column, srcFile, chunks) {
  118859. this.src = '';
  118860. if (chunks) {
  118861. this.add(chunks);
  118862. }
  118863. };
  118864. /* istanbul ignore next */
  118865. SourceNode.prototype = {
  118866. add: function add(chunks) {
  118867. if (_utils.isArray(chunks)) {
  118868. chunks = chunks.join('');
  118869. }
  118870. this.src += chunks;
  118871. },
  118872. prepend: function prepend(chunks) {
  118873. if (_utils.isArray(chunks)) {
  118874. chunks = chunks.join('');
  118875. }
  118876. this.src = chunks + this.src;
  118877. },
  118878. toStringWithSourceMap: function toStringWithSourceMap() {
  118879. return { code: this.toString() };
  118880. },
  118881. toString: function toString() {
  118882. return this.src;
  118883. }
  118884. };
  118885. }
  118886. function castChunk(chunk, codeGen, loc) {
  118887. if (_utils.isArray(chunk)) {
  118888. var ret = [];
  118889. for (var i = 0, len = chunk.length; i < len; i++) {
  118890. ret.push(codeGen.wrap(chunk[i], loc));
  118891. }
  118892. return ret;
  118893. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  118894. // Handle primitives that the SourceNode will throw up on
  118895. return chunk + '';
  118896. }
  118897. return chunk;
  118898. }
  118899. function CodeGen(srcFile) {
  118900. this.srcFile = srcFile;
  118901. this.source = [];
  118902. }
  118903. CodeGen.prototype = {
  118904. isEmpty: function isEmpty() {
  118905. return !this.source.length;
  118906. },
  118907. prepend: function prepend(source, loc) {
  118908. this.source.unshift(this.wrap(source, loc));
  118909. },
  118910. push: function push(source, loc) {
  118911. this.source.push(this.wrap(source, loc));
  118912. },
  118913. merge: function merge() {
  118914. var source = this.empty();
  118915. this.each(function (line) {
  118916. source.add([' ', line, '\n']);
  118917. });
  118918. return source;
  118919. },
  118920. each: function each(iter) {
  118921. for (var i = 0, len = this.source.length; i < len; i++) {
  118922. iter(this.source[i]);
  118923. }
  118924. },
  118925. empty: function empty() {
  118926. var loc = this.currentLocation || { start: {} };
  118927. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  118928. },
  118929. wrap: function wrap(chunk) {
  118930. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  118931. if (chunk instanceof SourceNode) {
  118932. return chunk;
  118933. }
  118934. chunk = castChunk(chunk, this, loc);
  118935. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  118936. },
  118937. functionCall: function functionCall(fn, type, params) {
  118938. params = this.generateList(params);
  118939. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  118940. },
  118941. quotedString: function quotedString(str) {
  118942. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  118943. .replace(/\u2029/g, '\\u2029') + '"';
  118944. },
  118945. objectLiteral: function objectLiteral(obj) {
  118946. var pairs = [];
  118947. for (var key in obj) {
  118948. if (obj.hasOwnProperty(key)) {
  118949. var value = castChunk(obj[key], this);
  118950. if (value !== 'undefined') {
  118951. pairs.push([this.quotedString(key), ':', value]);
  118952. }
  118953. }
  118954. }
  118955. var ret = this.generateList(pairs);
  118956. ret.prepend('{');
  118957. ret.add('}');
  118958. return ret;
  118959. },
  118960. generateList: function generateList(entries) {
  118961. var ret = this.empty();
  118962. for (var i = 0, len = entries.length; i < len; i++) {
  118963. if (i) {
  118964. ret.add(',');
  118965. }
  118966. ret.add(castChunk(entries[i], this));
  118967. }
  118968. return ret;
  118969. },
  118970. generateArray: function generateArray(entries) {
  118971. var ret = this.generateList(entries);
  118972. ret.prepend('[');
  118973. ret.add(']');
  118974. return ret;
  118975. }
  118976. };
  118977. exports['default'] = CodeGen;
  118978. module.exports = exports['default'];
  118979. /***/ })
  118980. /******/ ])
  118981. });
  118982. ;
  118983. /***/ }),
  118984. /* 63 */
  118985. /***/ (function(module, exports, __webpack_require__) {
  118986. "use strict";
  118987. Object.defineProperty(exports, "__esModule", { value: true });
  118988. /**
  118989. * The EventManager is in charge of registering user interctions with the viewer.
  118990. * It is used in the TemplateManager
  118991. */
  118992. var EventManager = /** @class */ (function () {
  118993. function EventManager(_templateManager) {
  118994. var _this = this;
  118995. this._templateManager = _templateManager;
  118996. this._callbacksContainer = {};
  118997. this._templateManager.onEventTriggered.add(function (eventData) {
  118998. _this._eventTriggered(eventData);
  118999. });
  119000. }
  119001. /**
  119002. * Register a new callback to a specific template.
  119003. * The best example for the usage can be found in the DefaultViewer
  119004. *
  119005. * @param templateName the templateName to register the event to
  119006. * @param callback The callback to be executed
  119007. * @param eventType the type of event to register
  119008. * @param selector an optional selector. if not defined the parent object in the template will be selected
  119009. */
  119010. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  119011. if (!this._callbacksContainer[templateName]) {
  119012. this._callbacksContainer[templateName] = [];
  119013. }
  119014. this._callbacksContainer[templateName].push({
  119015. eventType: eventType,
  119016. callback: callback,
  119017. selector: selector
  119018. });
  119019. };
  119020. /**
  119021. * This will remove a registered event from the defined template.
  119022. * Each one of the variables apart from the template name are optional, but one must be provided.
  119023. *
  119024. * @param templateName the templateName
  119025. * @param callback the callback to remove (optional)
  119026. * @param eventType the event type to remove (optional)
  119027. * @param selector the selector from which to remove the event (optional)
  119028. */
  119029. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  119030. var callbackDefs = this._callbacksContainer[templateName] || [];
  119031. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  119032. };
  119033. EventManager.prototype._eventTriggered = function (data) {
  119034. var templateName = data.template.name;
  119035. var eventType = data.event.type;
  119036. var selector = data.selector;
  119037. var callbackDefs = this._callbacksContainer[templateName] || [];
  119038. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  119039. callbackDef.callback(data);
  119040. });
  119041. };
  119042. /**
  119043. * Dispose the event manager
  119044. */
  119045. EventManager.prototype.dispose = function () {
  119046. this._callbacksContainer = {};
  119047. };
  119048. return EventManager;
  119049. }());
  119050. exports.EventManager = EventManager;
  119051. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVB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FdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQztJQUNqTixDQUFDO0lBRU8sc0NBQWUsR0FBdkIsVUFBd0IsSUFBbUI7UUFDdkMsSUFBSSxZQUFZLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUM7UUFDdEMsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUM7UUFDaEMsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  119052. /***/ }),
  119053. /* 64 */
  119054. /***/ (function(module, exports, __webpack_require__) {
  119055. /*!
  119056. * PEP v0.4.3 | https://github.com/jquery/PEP
  119057. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  119058. */
  119059. (function (global, factory) {
  119060. true ? module.exports = factory() :
  119061. typeof define === 'function' && define.amd ? define(factory) :
  119062. (global.PointerEventsPolyfill = factory());
  119063. }(this, function () { 'use strict';
  119064. /**
  119065. * This is the constructor for new PointerEvents.
  119066. *
  119067. * New Pointer Events must be given a type, and an optional dictionary of
  119068. * initialization properties.
  119069. *
  119070. * Due to certain platform requirements, events returned from the constructor
  119071. * identify as MouseEvents.
  119072. *
  119073. * @constructor
  119074. * @param {String} inType The type of the event to create.
  119075. * @param {Object} [inDict] An optional dictionary of initial event properties.
  119076. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  119077. */
  119078. var MOUSE_PROPS = [
  119079. 'bubbles',
  119080. 'cancelable',
  119081. 'view',
  119082. 'detail',
  119083. 'screenX',
  119084. 'screenY',
  119085. 'clientX',
  119086. 'clientY',
  119087. 'ctrlKey',
  119088. 'altKey',
  119089. 'shiftKey',
  119090. 'metaKey',
  119091. 'button',
  119092. 'relatedTarget',
  119093. 'pageX',
  119094. 'pageY'
  119095. ];
  119096. var MOUSE_DEFAULTS = [
  119097. false,
  119098. false,
  119099. null,
  119100. null,
  119101. 0,
  119102. 0,
  119103. 0,
  119104. 0,
  119105. false,
  119106. false,
  119107. false,
  119108. false,
  119109. 0,
  119110. null,
  119111. 0,
  119112. 0
  119113. ];
  119114. function PointerEvent(inType, inDict) {
  119115. inDict = inDict || Object.create(null);
  119116. var e = document.createEvent('Event');
  119117. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  119118. // define inherited MouseEvent properties
  119119. // skip bubbles and cancelable since they're set above in initEvent()
  119120. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  119121. p = MOUSE_PROPS[i];
  119122. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  119123. }
  119124. e.buttons = inDict.buttons || 0;
  119125. // Spec requires that pointers without pressure specified use 0.5 for down
  119126. // state and 0 for up state.
  119127. var pressure = 0;
  119128. if (inDict.pressure && e.buttons) {
  119129. pressure = inDict.pressure;
  119130. } else {
  119131. pressure = e.buttons ? 0.5 : 0;
  119132. }
  119133. // add x/y properties aliased to clientX/Y
  119134. e.x = e.clientX;
  119135. e.y = e.clientY;
  119136. // define the properties of the PointerEvent interface
  119137. e.pointerId = inDict.pointerId || 0;
  119138. e.width = inDict.width || 0;
  119139. e.height = inDict.height || 0;
  119140. e.pressure = pressure;
  119141. e.tiltX = inDict.tiltX || 0;
  119142. e.tiltY = inDict.tiltY || 0;
  119143. e.twist = inDict.twist || 0;
  119144. e.tangentialPressure = inDict.tangentialPressure || 0;
  119145. e.pointerType = inDict.pointerType || '';
  119146. e.hwTimestamp = inDict.hwTimestamp || 0;
  119147. e.isPrimary = inDict.isPrimary || false;
  119148. return e;
  119149. }
  119150. /**
  119151. * This module implements a map of pointer states
  119152. */
  119153. var USE_MAP = window.Map && window.Map.prototype.forEach;
  119154. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  119155. function SparseArrayMap() {
  119156. this.array = [];
  119157. this.size = 0;
  119158. }
  119159. SparseArrayMap.prototype = {
  119160. set: function(k, v) {
  119161. if (v === undefined) {
  119162. return this.delete(k);
  119163. }
  119164. if (!this.has(k)) {
  119165. this.size++;
  119166. }
  119167. this.array[k] = v;
  119168. },
  119169. has: function(k) {
  119170. return this.array[k] !== undefined;
  119171. },
  119172. delete: function(k) {
  119173. if (this.has(k)) {
  119174. delete this.array[k];
  119175. this.size--;
  119176. }
  119177. },
  119178. get: function(k) {
  119179. return this.array[k];
  119180. },
  119181. clear: function() {
  119182. this.array.length = 0;
  119183. this.size = 0;
  119184. },
  119185. // return value, key, map
  119186. forEach: function(callback, thisArg) {
  119187. return this.array.forEach(function(v, k) {
  119188. callback.call(thisArg, v, k, this);
  119189. }, this);
  119190. }
  119191. };
  119192. var CLONE_PROPS = [
  119193. // MouseEvent
  119194. 'bubbles',
  119195. 'cancelable',
  119196. 'view',
  119197. 'detail',
  119198. 'screenX',
  119199. 'screenY',
  119200. 'clientX',
  119201. 'clientY',
  119202. 'ctrlKey',
  119203. 'altKey',
  119204. 'shiftKey',
  119205. 'metaKey',
  119206. 'button',
  119207. 'relatedTarget',
  119208. // DOM Level 3
  119209. 'buttons',
  119210. // PointerEvent
  119211. 'pointerId',
  119212. 'width',
  119213. 'height',
  119214. 'pressure',
  119215. 'tiltX',
  119216. 'tiltY',
  119217. 'pointerType',
  119218. 'hwTimestamp',
  119219. 'isPrimary',
  119220. // event instance
  119221. 'type',
  119222. 'target',
  119223. 'currentTarget',
  119224. 'which',
  119225. 'pageX',
  119226. 'pageY',
  119227. 'timeStamp'
  119228. ];
  119229. var CLONE_DEFAULTS = [
  119230. // MouseEvent
  119231. false,
  119232. false,
  119233. null,
  119234. null,
  119235. 0,
  119236. 0,
  119237. 0,
  119238. 0,
  119239. false,
  119240. false,
  119241. false,
  119242. false,
  119243. 0,
  119244. null,
  119245. // DOM Level 3
  119246. 0,
  119247. // PointerEvent
  119248. 0,
  119249. 0,
  119250. 0,
  119251. 0,
  119252. 0,
  119253. 0,
  119254. '',
  119255. 0,
  119256. false,
  119257. // event instance
  119258. '',
  119259. null,
  119260. null,
  119261. 0,
  119262. 0,
  119263. 0,
  119264. 0
  119265. ];
  119266. var BOUNDARY_EVENTS = {
  119267. 'pointerover': 1,
  119268. 'pointerout': 1,
  119269. 'pointerenter': 1,
  119270. 'pointerleave': 1
  119271. };
  119272. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  119273. /**
  119274. * This module is for normalizing events. Mouse and Touch events will be
  119275. * collected here, and fire PointerEvents that have the same semantics, no
  119276. * matter the source.
  119277. * Events fired:
  119278. * - pointerdown: a pointing is added
  119279. * - pointerup: a pointer is removed
  119280. * - pointermove: a pointer is moved
  119281. * - pointerover: a pointer crosses into an element
  119282. * - pointerout: a pointer leaves an element
  119283. * - pointercancel: a pointer will no longer generate events
  119284. */
  119285. var dispatcher = {
  119286. pointermap: new PointerMap(),
  119287. eventMap: Object.create(null),
  119288. captureInfo: Object.create(null),
  119289. // Scope objects for native events.
  119290. // This exists for ease of testing.
  119291. eventSources: Object.create(null),
  119292. eventSourceList: [],
  119293. /**
  119294. * Add a new event source that will generate pointer events.
  119295. *
  119296. * `inSource` must contain an array of event names named `events`, and
  119297. * functions with the names specified in the `events` array.
  119298. * @param {string} name A name for the event source
  119299. * @param {Object} source A new source of platform events.
  119300. */
  119301. registerSource: function(name, source) {
  119302. var s = source;
  119303. var newEvents = s.events;
  119304. if (newEvents) {
  119305. newEvents.forEach(function(e) {
  119306. if (s[e]) {
  119307. this.eventMap[e] = s[e].bind(s);
  119308. }
  119309. }, this);
  119310. this.eventSources[name] = s;
  119311. this.eventSourceList.push(s);
  119312. }
  119313. },
  119314. register: function(element) {
  119315. var l = this.eventSourceList.length;
  119316. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  119317. // call eventsource register
  119318. es.register.call(es, element);
  119319. }
  119320. },
  119321. unregister: function(element) {
  119322. var l = this.eventSourceList.length;
  119323. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  119324. // call eventsource register
  119325. es.unregister.call(es, element);
  119326. }
  119327. },
  119328. contains: /*scope.external.contains || */function(container, contained) {
  119329. try {
  119330. return container.contains(contained);
  119331. } catch (ex) {
  119332. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  119333. return false;
  119334. }
  119335. },
  119336. // EVENTS
  119337. down: function(inEvent) {
  119338. inEvent.bubbles = true;
  119339. this.fireEvent('pointerdown', inEvent);
  119340. },
  119341. move: function(inEvent) {
  119342. inEvent.bubbles = true;
  119343. this.fireEvent('pointermove', inEvent);
  119344. },
  119345. up: function(inEvent) {
  119346. inEvent.bubbles = true;
  119347. this.fireEvent('pointerup', inEvent);
  119348. },
  119349. enter: function(inEvent) {
  119350. inEvent.bubbles = false;
  119351. this.fireEvent('pointerenter', inEvent);
  119352. },
  119353. leave: function(inEvent) {
  119354. inEvent.bubbles = false;
  119355. this.fireEvent('pointerleave', inEvent);
  119356. },
  119357. over: function(inEvent) {
  119358. inEvent.bubbles = true;
  119359. this.fireEvent('pointerover', inEvent);
  119360. },
  119361. out: function(inEvent) {
  119362. inEvent.bubbles = true;
  119363. this.fireEvent('pointerout', inEvent);
  119364. },
  119365. cancel: function(inEvent) {
  119366. inEvent.bubbles = true;
  119367. this.fireEvent('pointercancel', inEvent);
  119368. },
  119369. leaveOut: function(event) {
  119370. this.out(event);
  119371. this.propagate(event, this.leave, false);
  119372. },
  119373. enterOver: function(event) {
  119374. this.over(event);
  119375. this.propagate(event, this.enter, true);
  119376. },
  119377. // LISTENER LOGIC
  119378. eventHandler: function(inEvent) {
  119379. // This is used to prevent multiple dispatch of pointerevents from
  119380. // platform events. This can happen when two elements in different scopes
  119381. // are set up to create pointer events, which is relevant to Shadow DOM.
  119382. if (inEvent._handledByPE) {
  119383. return;
  119384. }
  119385. var type = inEvent.type;
  119386. var fn = this.eventMap && this.eventMap[type];
  119387. if (fn) {
  119388. fn(inEvent);
  119389. }
  119390. inEvent._handledByPE = true;
  119391. },
  119392. // set up event listeners
  119393. listen: function(target, events) {
  119394. events.forEach(function(e) {
  119395. this.addEvent(target, e);
  119396. }, this);
  119397. },
  119398. // remove event listeners
  119399. unlisten: function(target, events) {
  119400. events.forEach(function(e) {
  119401. this.removeEvent(target, e);
  119402. }, this);
  119403. },
  119404. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  119405. target.addEventListener(eventName, this.boundHandler);
  119406. },
  119407. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  119408. target.removeEventListener(eventName, this.boundHandler);
  119409. },
  119410. // EVENT CREATION AND TRACKING
  119411. /**
  119412. * Creates a new Event of type `inType`, based on the information in
  119413. * `inEvent`.
  119414. *
  119415. * @param {string} inType A string representing the type of event to create
  119416. * @param {Event} inEvent A platform event with a target
  119417. * @return {Event} A PointerEvent of type `inType`
  119418. */
  119419. makeEvent: function(inType, inEvent) {
  119420. // relatedTarget must be null if pointer is captured
  119421. if (this.captureInfo[inEvent.pointerId]) {
  119422. inEvent.relatedTarget = null;
  119423. }
  119424. var e = new PointerEvent(inType, inEvent);
  119425. if (inEvent.preventDefault) {
  119426. e.preventDefault = inEvent.preventDefault;
  119427. }
  119428. e._target = e._target || inEvent.target;
  119429. return e;
  119430. },
  119431. // make and dispatch an event in one call
  119432. fireEvent: function(inType, inEvent) {
  119433. var e = this.makeEvent(inType, inEvent);
  119434. return this.dispatchEvent(e);
  119435. },
  119436. /**
  119437. * Returns a snapshot of inEvent, with writable properties.
  119438. *
  119439. * @param {Event} inEvent An event that contains properties to copy.
  119440. * @return {Object} An object containing shallow copies of `inEvent`'s
  119441. * properties.
  119442. */
  119443. cloneEvent: function(inEvent) {
  119444. var eventCopy = Object.create(null);
  119445. var p;
  119446. for (var i = 0; i < CLONE_PROPS.length; i++) {
  119447. p = CLONE_PROPS[i];
  119448. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  119449. // Work around SVGInstanceElement shadow tree
  119450. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  119451. // This is the behavior implemented by Firefox.
  119452. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  119453. if (eventCopy[p] instanceof SVGElementInstance) {
  119454. eventCopy[p] = eventCopy[p].correspondingUseElement;
  119455. }
  119456. }
  119457. }
  119458. // keep the semantics of preventDefault
  119459. if (inEvent.preventDefault) {
  119460. eventCopy.preventDefault = function() {
  119461. inEvent.preventDefault();
  119462. };
  119463. }
  119464. return eventCopy;
  119465. },
  119466. getTarget: function(inEvent) {
  119467. var capture = this.captureInfo[inEvent.pointerId];
  119468. if (!capture) {
  119469. return inEvent._target;
  119470. }
  119471. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  119472. return capture;
  119473. }
  119474. },
  119475. propagate: function(event, fn, propagateDown) {
  119476. var target = event.target;
  119477. var targets = [];
  119478. // Order of conditions due to document.contains() missing in IE.
  119479. while (target !== document && !target.contains(event.relatedTarget)) {
  119480. targets.push(target);
  119481. target = target.parentNode;
  119482. // Touch: Do not propagate if node is detached.
  119483. if (!target) {
  119484. return;
  119485. }
  119486. }
  119487. if (propagateDown) {
  119488. targets.reverse();
  119489. }
  119490. targets.forEach(function(target) {
  119491. event.target = target;
  119492. fn.call(this, event);
  119493. }, this);
  119494. },
  119495. setCapture: function(inPointerId, inTarget, skipDispatch) {
  119496. if (this.captureInfo[inPointerId]) {
  119497. this.releaseCapture(inPointerId, skipDispatch);
  119498. }
  119499. this.captureInfo[inPointerId] = inTarget;
  119500. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  119501. document.addEventListener('pointerup', this.implicitRelease);
  119502. document.addEventListener('pointercancel', this.implicitRelease);
  119503. var e = new PointerEvent('gotpointercapture');
  119504. e.pointerId = inPointerId;
  119505. e._target = inTarget;
  119506. if (!skipDispatch) {
  119507. this.asyncDispatchEvent(e);
  119508. }
  119509. },
  119510. releaseCapture: function(inPointerId, skipDispatch) {
  119511. var t = this.captureInfo[inPointerId];
  119512. if (!t) {
  119513. return;
  119514. }
  119515. this.captureInfo[inPointerId] = undefined;
  119516. document.removeEventListener('pointerup', this.implicitRelease);
  119517. document.removeEventListener('pointercancel', this.implicitRelease);
  119518. var e = new PointerEvent('lostpointercapture');
  119519. e.pointerId = inPointerId;
  119520. e._target = t;
  119521. if (!skipDispatch) {
  119522. this.asyncDispatchEvent(e);
  119523. }
  119524. },
  119525. /**
  119526. * Dispatches the event to its target.
  119527. *
  119528. * @param {Event} inEvent The event to be dispatched.
  119529. * @return {Boolean} True if an event handler returns true, false otherwise.
  119530. */
  119531. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  119532. var t = this.getTarget(inEvent);
  119533. if (t) {
  119534. return t.dispatchEvent(inEvent);
  119535. }
  119536. },
  119537. asyncDispatchEvent: function(inEvent) {
  119538. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  119539. }
  119540. };
  119541. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  119542. var targeting = {
  119543. shadow: function(inEl) {
  119544. if (inEl) {
  119545. return inEl.shadowRoot || inEl.webkitShadowRoot;
  119546. }
  119547. },
  119548. canTarget: function(shadow) {
  119549. return shadow && Boolean(shadow.elementFromPoint);
  119550. },
  119551. targetingShadow: function(inEl) {
  119552. var s = this.shadow(inEl);
  119553. if (this.canTarget(s)) {
  119554. return s;
  119555. }
  119556. },
  119557. olderShadow: function(shadow) {
  119558. var os = shadow.olderShadowRoot;
  119559. if (!os) {
  119560. var se = shadow.querySelector('shadow');
  119561. if (se) {
  119562. os = se.olderShadowRoot;
  119563. }
  119564. }
  119565. return os;
  119566. },
  119567. allShadows: function(element) {
  119568. var shadows = [];
  119569. var s = this.shadow(element);
  119570. while (s) {
  119571. shadows.push(s);
  119572. s = this.olderShadow(s);
  119573. }
  119574. return shadows;
  119575. },
  119576. searchRoot: function(inRoot, x, y) {
  119577. if (inRoot) {
  119578. var t = inRoot.elementFromPoint(x, y);
  119579. var st, sr;
  119580. // is element a shadow host?
  119581. sr = this.targetingShadow(t);
  119582. while (sr) {
  119583. // find the the element inside the shadow root
  119584. st = sr.elementFromPoint(x, y);
  119585. if (!st) {
  119586. // check for older shadows
  119587. sr = this.olderShadow(sr);
  119588. } else {
  119589. // shadowed element may contain a shadow root
  119590. var ssr = this.targetingShadow(st);
  119591. return this.searchRoot(ssr, x, y) || st;
  119592. }
  119593. }
  119594. // light dom element is the target
  119595. return t;
  119596. }
  119597. },
  119598. owner: function(element) {
  119599. var s = element;
  119600. // walk up until you hit the shadow root or document
  119601. while (s.parentNode) {
  119602. s = s.parentNode;
  119603. }
  119604. // the owner element is expected to be a Document or ShadowRoot
  119605. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  119606. s = document;
  119607. }
  119608. return s;
  119609. },
  119610. findTarget: function(inEvent) {
  119611. var x = inEvent.clientX;
  119612. var y = inEvent.clientY;
  119613. // if the listener is in the shadow root, it is much faster to start there
  119614. var s = this.owner(inEvent.target);
  119615. // if x, y is not in this root, fall back to document search
  119616. if (!s.elementFromPoint(x, y)) {
  119617. s = document;
  119618. }
  119619. return this.searchRoot(s, x, y);
  119620. }
  119621. };
  119622. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  119623. var map = Array.prototype.map.call.bind(Array.prototype.map);
  119624. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  119625. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  119626. var MO = window.MutationObserver || window.WebKitMutationObserver;
  119627. var SELECTOR = '[touch-action]';
  119628. var OBSERVER_INIT = {
  119629. subtree: true,
  119630. childList: true,
  119631. attributes: true,
  119632. attributeOldValue: true,
  119633. attributeFilter: ['touch-action']
  119634. };
  119635. function Installer(add, remove, changed, binder) {
  119636. this.addCallback = add.bind(binder);
  119637. this.removeCallback = remove.bind(binder);
  119638. this.changedCallback = changed.bind(binder);
  119639. if (MO) {
  119640. this.observer = new MO(this.mutationWatcher.bind(this));
  119641. }
  119642. }
  119643. Installer.prototype = {
  119644. watchSubtree: function(target) {
  119645. // Only watch scopes that can target find, as these are top-level.
  119646. // Otherwise we can see duplicate additions and removals that add noise.
  119647. //
  119648. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  119649. // a removal without an insertion when a node is redistributed among
  119650. // shadows. Since it all ends up correct in the document, watching only
  119651. // the document will yield the correct mutations to watch.
  119652. if (this.observer && targeting.canTarget(target)) {
  119653. this.observer.observe(target, OBSERVER_INIT);
  119654. }
  119655. },
  119656. enableOnSubtree: function(target) {
  119657. this.watchSubtree(target);
  119658. if (target === document && document.readyState !== 'complete') {
  119659. this.installOnLoad();
  119660. } else {
  119661. this.installNewSubtree(target);
  119662. }
  119663. },
  119664. installNewSubtree: function(target) {
  119665. forEach(this.findElements(target), this.addElement, this);
  119666. },
  119667. findElements: function(target) {
  119668. if (target.querySelectorAll) {
  119669. return target.querySelectorAll(SELECTOR);
  119670. }
  119671. return [];
  119672. },
  119673. removeElement: function(el) {
  119674. this.removeCallback(el);
  119675. },
  119676. addElement: function(el) {
  119677. this.addCallback(el);
  119678. },
  119679. elementChanged: function(el, oldValue) {
  119680. this.changedCallback(el, oldValue);
  119681. },
  119682. concatLists: function(accum, list) {
  119683. return accum.concat(toArray(list));
  119684. },
  119685. // register all touch-action = none nodes on document load
  119686. installOnLoad: function() {
  119687. document.addEventListener('readystatechange', function() {
  119688. if (document.readyState === 'complete') {
  119689. this.installNewSubtree(document);
  119690. }
  119691. }.bind(this));
  119692. },
  119693. isElement: function(n) {
  119694. return n.nodeType === Node.ELEMENT_NODE;
  119695. },
  119696. flattenMutationTree: function(inNodes) {
  119697. // find children with touch-action
  119698. var tree = map(inNodes, this.findElements, this);
  119699. // make sure the added nodes are accounted for
  119700. tree.push(filter(inNodes, this.isElement));
  119701. // flatten the list
  119702. return tree.reduce(this.concatLists, []);
  119703. },
  119704. mutationWatcher: function(mutations) {
  119705. mutations.forEach(this.mutationHandler, this);
  119706. },
  119707. mutationHandler: function(m) {
  119708. if (m.type === 'childList') {
  119709. var added = this.flattenMutationTree(m.addedNodes);
  119710. added.forEach(this.addElement, this);
  119711. var removed = this.flattenMutationTree(m.removedNodes);
  119712. removed.forEach(this.removeElement, this);
  119713. } else if (m.type === 'attributes') {
  119714. this.elementChanged(m.target, m.oldValue);
  119715. }
  119716. }
  119717. };
  119718. function shadowSelector(v) {
  119719. return 'body /shadow-deep/ ' + selector(v);
  119720. }
  119721. function selector(v) {
  119722. return '[touch-action="' + v + '"]';
  119723. }
  119724. function rule(v) {
  119725. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  119726. }
  119727. var attrib2css = [
  119728. 'none',
  119729. 'auto',
  119730. 'pan-x',
  119731. 'pan-y',
  119732. {
  119733. rule: 'pan-x pan-y',
  119734. selectors: [
  119735. 'pan-x pan-y',
  119736. 'pan-y pan-x'
  119737. ]
  119738. }
  119739. ];
  119740. var styles = '';
  119741. // only install stylesheet if the browser has touch action support
  119742. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  119743. // only add shadow selectors if shadowdom is supported
  119744. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  119745. function applyAttributeStyles() {
  119746. if (hasNativePE) {
  119747. attrib2css.forEach(function(r) {
  119748. if (String(r) === r) {
  119749. styles += selector(r) + rule(r) + '\n';
  119750. if (hasShadowRoot) {
  119751. styles += shadowSelector(r) + rule(r) + '\n';
  119752. }
  119753. } else {
  119754. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  119755. if (hasShadowRoot) {
  119756. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  119757. }
  119758. }
  119759. });
  119760. var el = document.createElement('style');
  119761. el.textContent = styles;
  119762. document.head.appendChild(el);
  119763. }
  119764. }
  119765. var pointermap = dispatcher.pointermap;
  119766. // radius around touchend that swallows mouse events
  119767. var DEDUP_DIST = 25;
  119768. // left, middle, right, back, forward
  119769. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  119770. var HAS_BUTTONS = false;
  119771. try {
  119772. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  119773. } catch (e) {}
  119774. // handler block for native mouse events
  119775. var mouseEvents = {
  119776. POINTER_ID: 1,
  119777. POINTER_TYPE: 'mouse',
  119778. events: [
  119779. 'mousedown',
  119780. 'mousemove',
  119781. 'mouseup',
  119782. 'mouseover',
  119783. 'mouseout'
  119784. ],
  119785. register: function(target) {
  119786. dispatcher.listen(target, this.events);
  119787. },
  119788. unregister: function(target) {
  119789. dispatcher.unlisten(target, this.events);
  119790. },
  119791. lastTouches: [],
  119792. // collide with the global mouse listener
  119793. isEventSimulatedFromTouch: function(inEvent) {
  119794. var lts = this.lastTouches;
  119795. var x = inEvent.clientX;
  119796. var y = inEvent.clientY;
  119797. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  119798. // simulated mouse events will be swallowed near a primary touchend
  119799. var dx = Math.abs(x - t.x);
  119800. var dy = Math.abs(y - t.y);
  119801. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  119802. return true;
  119803. }
  119804. }
  119805. },
  119806. prepareEvent: function(inEvent) {
  119807. var e = dispatcher.cloneEvent(inEvent);
  119808. // forward mouse preventDefault
  119809. var pd = e.preventDefault;
  119810. e.preventDefault = function() {
  119811. inEvent.preventDefault();
  119812. pd();
  119813. };
  119814. e.pointerId = this.POINTER_ID;
  119815. e.isPrimary = true;
  119816. e.pointerType = this.POINTER_TYPE;
  119817. return e;
  119818. },
  119819. prepareButtonsForMove: function(e, inEvent) {
  119820. var p = pointermap.get(this.POINTER_ID);
  119821. // Update buttons state after possible out-of-document mouseup.
  119822. if (inEvent.which === 0 || !p) {
  119823. e.buttons = 0;
  119824. } else {
  119825. e.buttons = p.buttons;
  119826. }
  119827. inEvent.buttons = e.buttons;
  119828. },
  119829. mousedown: function(inEvent) {
  119830. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119831. var p = pointermap.get(this.POINTER_ID);
  119832. var e = this.prepareEvent(inEvent);
  119833. if (!HAS_BUTTONS) {
  119834. e.buttons = BUTTON_TO_BUTTONS[e.button];
  119835. if (p) { e.buttons |= p.buttons; }
  119836. inEvent.buttons = e.buttons;
  119837. }
  119838. pointermap.set(this.POINTER_ID, inEvent);
  119839. if (!p || p.buttons === 0) {
  119840. dispatcher.down(e);
  119841. } else {
  119842. dispatcher.move(e);
  119843. }
  119844. }
  119845. },
  119846. mousemove: function(inEvent) {
  119847. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119848. var e = this.prepareEvent(inEvent);
  119849. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119850. e.button = -1;
  119851. pointermap.set(this.POINTER_ID, inEvent);
  119852. dispatcher.move(e);
  119853. }
  119854. },
  119855. mouseup: function(inEvent) {
  119856. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119857. var p = pointermap.get(this.POINTER_ID);
  119858. var e = this.prepareEvent(inEvent);
  119859. if (!HAS_BUTTONS) {
  119860. var up = BUTTON_TO_BUTTONS[e.button];
  119861. // Produces wrong state of buttons in Browsers without `buttons` support
  119862. // when a mouse button that was pressed outside the document is released
  119863. // inside and other buttons are still pressed down.
  119864. e.buttons = p ? p.buttons & ~up : 0;
  119865. inEvent.buttons = e.buttons;
  119866. }
  119867. pointermap.set(this.POINTER_ID, inEvent);
  119868. // Support: Firefox <=44 only
  119869. // FF Ubuntu includes the lifted button in the `buttons` property on
  119870. // mouseup.
  119871. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  119872. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  119873. if (e.buttons === 0) {
  119874. dispatcher.up(e);
  119875. } else {
  119876. dispatcher.move(e);
  119877. }
  119878. }
  119879. },
  119880. mouseover: function(inEvent) {
  119881. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119882. var e = this.prepareEvent(inEvent);
  119883. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119884. e.button = -1;
  119885. pointermap.set(this.POINTER_ID, inEvent);
  119886. dispatcher.enterOver(e);
  119887. }
  119888. },
  119889. mouseout: function(inEvent) {
  119890. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119891. var e = this.prepareEvent(inEvent);
  119892. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119893. e.button = -1;
  119894. dispatcher.leaveOut(e);
  119895. }
  119896. },
  119897. cancel: function(inEvent) {
  119898. var e = this.prepareEvent(inEvent);
  119899. dispatcher.cancel(e);
  119900. this.deactivateMouse();
  119901. },
  119902. deactivateMouse: function() {
  119903. pointermap.delete(this.POINTER_ID);
  119904. }
  119905. };
  119906. var captureInfo = dispatcher.captureInfo;
  119907. var findTarget = targeting.findTarget.bind(targeting);
  119908. var allShadows = targeting.allShadows.bind(targeting);
  119909. var pointermap$1 = dispatcher.pointermap;
  119910. // This should be long enough to ignore compat mouse events made by touch
  119911. var DEDUP_TIMEOUT = 2500;
  119912. var CLICK_COUNT_TIMEOUT = 200;
  119913. var ATTRIB = 'touch-action';
  119914. var INSTALLER;
  119915. // handler block for native touch events
  119916. var touchEvents = {
  119917. events: [
  119918. 'touchstart',
  119919. 'touchmove',
  119920. 'touchend',
  119921. 'touchcancel'
  119922. ],
  119923. register: function(target) {
  119924. INSTALLER.enableOnSubtree(target);
  119925. },
  119926. unregister: function() {
  119927. // TODO(dfreedman): is it worth it to disconnect the MO?
  119928. },
  119929. elementAdded: function(el) {
  119930. var a = el.getAttribute(ATTRIB);
  119931. var st = this.touchActionToScrollType(a);
  119932. if (st) {
  119933. el._scrollType = st;
  119934. dispatcher.listen(el, this.events);
  119935. // set touch-action on shadows as well
  119936. allShadows(el).forEach(function(s) {
  119937. s._scrollType = st;
  119938. dispatcher.listen(s, this.events);
  119939. }, this);
  119940. }
  119941. },
  119942. elementRemoved: function(el) {
  119943. el._scrollType = undefined;
  119944. dispatcher.unlisten(el, this.events);
  119945. // remove touch-action from shadow
  119946. allShadows(el).forEach(function(s) {
  119947. s._scrollType = undefined;
  119948. dispatcher.unlisten(s, this.events);
  119949. }, this);
  119950. },
  119951. elementChanged: function(el, oldValue) {
  119952. var a = el.getAttribute(ATTRIB);
  119953. var st = this.touchActionToScrollType(a);
  119954. var oldSt = this.touchActionToScrollType(oldValue);
  119955. // simply update scrollType if listeners are already established
  119956. if (st && oldSt) {
  119957. el._scrollType = st;
  119958. allShadows(el).forEach(function(s) {
  119959. s._scrollType = st;
  119960. }, this);
  119961. } else if (oldSt) {
  119962. this.elementRemoved(el);
  119963. } else if (st) {
  119964. this.elementAdded(el);
  119965. }
  119966. },
  119967. scrollTypes: {
  119968. EMITTER: 'none',
  119969. XSCROLLER: 'pan-x',
  119970. YSCROLLER: 'pan-y',
  119971. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  119972. },
  119973. touchActionToScrollType: function(touchAction) {
  119974. var t = touchAction;
  119975. var st = this.scrollTypes;
  119976. if (t === 'none') {
  119977. return 'none';
  119978. } else if (t === st.XSCROLLER) {
  119979. return 'X';
  119980. } else if (t === st.YSCROLLER) {
  119981. return 'Y';
  119982. } else if (st.SCROLLER.exec(t)) {
  119983. return 'XY';
  119984. }
  119985. },
  119986. POINTER_TYPE: 'touch',
  119987. firstTouch: null,
  119988. isPrimaryTouch: function(inTouch) {
  119989. return this.firstTouch === inTouch.identifier;
  119990. },
  119991. setPrimaryTouch: function(inTouch) {
  119992. // set primary touch if there no pointers, or the only pointer is the mouse
  119993. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  119994. this.firstTouch = inTouch.identifier;
  119995. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  119996. this.scrolling = false;
  119997. this.cancelResetClickCount();
  119998. }
  119999. },
  120000. removePrimaryPointer: function(inPointer) {
  120001. if (inPointer.isPrimary) {
  120002. this.firstTouch = null;
  120003. this.firstXY = null;
  120004. this.resetClickCount();
  120005. }
  120006. },
  120007. clickCount: 0,
  120008. resetId: null,
  120009. resetClickCount: function() {
  120010. var fn = function() {
  120011. this.clickCount = 0;
  120012. this.resetId = null;
  120013. }.bind(this);
  120014. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  120015. },
  120016. cancelResetClickCount: function() {
  120017. if (this.resetId) {
  120018. clearTimeout(this.resetId);
  120019. }
  120020. },
  120021. typeToButtons: function(type) {
  120022. var ret = 0;
  120023. if (type === 'touchstart' || type === 'touchmove') {
  120024. ret = 1;
  120025. }
  120026. return ret;
  120027. },
  120028. touchToPointer: function(inTouch) {
  120029. var cte = this.currentTouchEvent;
  120030. var e = dispatcher.cloneEvent(inTouch);
  120031. // We reserve pointerId 1 for Mouse.
  120032. // Touch identifiers can start at 0.
  120033. // Add 2 to the touch identifier for compatibility.
  120034. var id = e.pointerId = inTouch.identifier + 2;
  120035. e.target = captureInfo[id] || findTarget(e);
  120036. e.bubbles = true;
  120037. e.cancelable = true;
  120038. e.detail = this.clickCount;
  120039. e.button = 0;
  120040. e.buttons = this.typeToButtons(cte.type);
  120041. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  120042. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  120043. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  120044. e.isPrimary = this.isPrimaryTouch(inTouch);
  120045. e.pointerType = this.POINTER_TYPE;
  120046. // forward modifier keys
  120047. e.altKey = cte.altKey;
  120048. e.ctrlKey = cte.ctrlKey;
  120049. e.metaKey = cte.metaKey;
  120050. e.shiftKey = cte.shiftKey;
  120051. // forward touch preventDefaults
  120052. var self = this;
  120053. e.preventDefault = function() {
  120054. self.scrolling = false;
  120055. self.firstXY = null;
  120056. cte.preventDefault();
  120057. };
  120058. return e;
  120059. },
  120060. processTouches: function(inEvent, inFunction) {
  120061. var tl = inEvent.changedTouches;
  120062. this.currentTouchEvent = inEvent;
  120063. for (var i = 0, t; i < tl.length; i++) {
  120064. t = tl[i];
  120065. inFunction.call(this, this.touchToPointer(t));
  120066. }
  120067. },
  120068. // For single axis scrollers, determines whether the element should emit
  120069. // pointer events or behave as a scroller
  120070. shouldScroll: function(inEvent) {
  120071. if (this.firstXY) {
  120072. var ret;
  120073. var scrollAxis = inEvent.currentTarget._scrollType;
  120074. if (scrollAxis === 'none') {
  120075. // this element is a touch-action: none, should never scroll
  120076. ret = false;
  120077. } else if (scrollAxis === 'XY') {
  120078. // this element should always scroll
  120079. ret = true;
  120080. } else {
  120081. var t = inEvent.changedTouches[0];
  120082. // check the intended scroll axis, and other axis
  120083. var a = scrollAxis;
  120084. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  120085. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  120086. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  120087. // if delta in the scroll axis > delta other axis, scroll instead of
  120088. // making events
  120089. ret = da >= doa;
  120090. }
  120091. this.firstXY = null;
  120092. return ret;
  120093. }
  120094. },
  120095. findTouch: function(inTL, inId) {
  120096. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  120097. if (t.identifier === inId) {
  120098. return true;
  120099. }
  120100. }
  120101. },
  120102. // In some instances, a touchstart can happen without a touchend. This
  120103. // leaves the pointermap in a broken state.
  120104. // Therefore, on every touchstart, we remove the touches that did not fire a
  120105. // touchend event.
  120106. // To keep state globally consistent, we fire a
  120107. // pointercancel for this "abandoned" touch
  120108. vacuumTouches: function(inEvent) {
  120109. var tl = inEvent.touches;
  120110. // pointermap.size should be < tl.length here, as the touchstart has not
  120111. // been processed yet.
  120112. if (pointermap$1.size >= tl.length) {
  120113. var d = [];
  120114. pointermap$1.forEach(function(value, key) {
  120115. // Never remove pointerId == 1, which is mouse.
  120116. // Touch identifiers are 2 smaller than their pointerId, which is the
  120117. // index in pointermap.
  120118. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  120119. var p = value.out;
  120120. d.push(p);
  120121. }
  120122. }, this);
  120123. d.forEach(this.cancelOut, this);
  120124. }
  120125. },
  120126. touchstart: function(inEvent) {
  120127. this.vacuumTouches(inEvent);
  120128. this.setPrimaryTouch(inEvent.changedTouches[0]);
  120129. this.dedupSynthMouse(inEvent);
  120130. if (!this.scrolling) {
  120131. this.clickCount++;
  120132. this.processTouches(inEvent, this.overDown);
  120133. }
  120134. },
  120135. overDown: function(inPointer) {
  120136. pointermap$1.set(inPointer.pointerId, {
  120137. target: inPointer.target,
  120138. out: inPointer,
  120139. outTarget: inPointer.target
  120140. });
  120141. dispatcher.enterOver(inPointer);
  120142. dispatcher.down(inPointer);
  120143. },
  120144. touchmove: function(inEvent) {
  120145. if (!this.scrolling) {
  120146. if (this.shouldScroll(inEvent)) {
  120147. this.scrolling = true;
  120148. this.touchcancel(inEvent);
  120149. } else {
  120150. inEvent.preventDefault();
  120151. this.processTouches(inEvent, this.moveOverOut);
  120152. }
  120153. }
  120154. },
  120155. moveOverOut: function(inPointer) {
  120156. var event = inPointer;
  120157. var pointer = pointermap$1.get(event.pointerId);
  120158. // a finger drifted off the screen, ignore it
  120159. if (!pointer) {
  120160. return;
  120161. }
  120162. var outEvent = pointer.out;
  120163. var outTarget = pointer.outTarget;
  120164. dispatcher.move(event);
  120165. if (outEvent && outTarget !== event.target) {
  120166. outEvent.relatedTarget = event.target;
  120167. event.relatedTarget = outTarget;
  120168. // recover from retargeting by shadow
  120169. outEvent.target = outTarget;
  120170. if (event.target) {
  120171. dispatcher.leaveOut(outEvent);
  120172. dispatcher.enterOver(event);
  120173. } else {
  120174. // clean up case when finger leaves the screen
  120175. event.target = outTarget;
  120176. event.relatedTarget = null;
  120177. this.cancelOut(event);
  120178. }
  120179. }
  120180. pointer.out = event;
  120181. pointer.outTarget = event.target;
  120182. },
  120183. touchend: function(inEvent) {
  120184. this.dedupSynthMouse(inEvent);
  120185. this.processTouches(inEvent, this.upOut);
  120186. },
  120187. upOut: function(inPointer) {
  120188. if (!this.scrolling) {
  120189. dispatcher.up(inPointer);
  120190. dispatcher.leaveOut(inPointer);
  120191. }
  120192. this.cleanUpPointer(inPointer);
  120193. },
  120194. touchcancel: function(inEvent) {
  120195. this.processTouches(inEvent, this.cancelOut);
  120196. },
  120197. cancelOut: function(inPointer) {
  120198. dispatcher.cancel(inPointer);
  120199. dispatcher.leaveOut(inPointer);
  120200. this.cleanUpPointer(inPointer);
  120201. },
  120202. cleanUpPointer: function(inPointer) {
  120203. pointermap$1.delete(inPointer.pointerId);
  120204. this.removePrimaryPointer(inPointer);
  120205. },
  120206. // prevent synth mouse events from creating pointer events
  120207. dedupSynthMouse: function(inEvent) {
  120208. var lts = mouseEvents.lastTouches;
  120209. var t = inEvent.changedTouches[0];
  120210. // only the primary finger will synth mouse events
  120211. if (this.isPrimaryTouch(t)) {
  120212. // remember x/y of last touch
  120213. var lt = { x: t.clientX, y: t.clientY };
  120214. lts.push(lt);
  120215. var fn = (function(lts, lt) {
  120216. var i = lts.indexOf(lt);
  120217. if (i > -1) {
  120218. lts.splice(i, 1);
  120219. }
  120220. }).bind(null, lts, lt);
  120221. setTimeout(fn, DEDUP_TIMEOUT);
  120222. }
  120223. }
  120224. };
  120225. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  120226. touchEvents.elementChanged, touchEvents);
  120227. var pointermap$2 = dispatcher.pointermap;
  120228. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  120229. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  120230. var msEvents = {
  120231. events: [
  120232. 'MSPointerDown',
  120233. 'MSPointerMove',
  120234. 'MSPointerUp',
  120235. 'MSPointerOut',
  120236. 'MSPointerOver',
  120237. 'MSPointerCancel',
  120238. 'MSGotPointerCapture',
  120239. 'MSLostPointerCapture'
  120240. ],
  120241. register: function(target) {
  120242. dispatcher.listen(target, this.events);
  120243. },
  120244. unregister: function(target) {
  120245. dispatcher.unlisten(target, this.events);
  120246. },
  120247. POINTER_TYPES: [
  120248. '',
  120249. 'unavailable',
  120250. 'touch',
  120251. 'pen',
  120252. 'mouse'
  120253. ],
  120254. prepareEvent: function(inEvent) {
  120255. var e = inEvent;
  120256. if (HAS_BITMAP_TYPE) {
  120257. e = dispatcher.cloneEvent(inEvent);
  120258. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  120259. }
  120260. return e;
  120261. },
  120262. cleanup: function(id) {
  120263. pointermap$2.delete(id);
  120264. },
  120265. MSPointerDown: function(inEvent) {
  120266. pointermap$2.set(inEvent.pointerId, inEvent);
  120267. var e = this.prepareEvent(inEvent);
  120268. dispatcher.down(e);
  120269. },
  120270. MSPointerMove: function(inEvent) {
  120271. var e = this.prepareEvent(inEvent);
  120272. dispatcher.move(e);
  120273. },
  120274. MSPointerUp: function(inEvent) {
  120275. var e = this.prepareEvent(inEvent);
  120276. dispatcher.up(e);
  120277. this.cleanup(inEvent.pointerId);
  120278. },
  120279. MSPointerOut: function(inEvent) {
  120280. var e = this.prepareEvent(inEvent);
  120281. dispatcher.leaveOut(e);
  120282. },
  120283. MSPointerOver: function(inEvent) {
  120284. var e = this.prepareEvent(inEvent);
  120285. dispatcher.enterOver(e);
  120286. },
  120287. MSPointerCancel: function(inEvent) {
  120288. var e = this.prepareEvent(inEvent);
  120289. dispatcher.cancel(e);
  120290. this.cleanup(inEvent.pointerId);
  120291. },
  120292. MSLostPointerCapture: function(inEvent) {
  120293. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  120294. dispatcher.dispatchEvent(e);
  120295. },
  120296. MSGotPointerCapture: function(inEvent) {
  120297. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  120298. dispatcher.dispatchEvent(e);
  120299. }
  120300. };
  120301. function applyPolyfill() {
  120302. // only activate if this platform does not have pointer events
  120303. if (!window.PointerEvent) {
  120304. window.PointerEvent = PointerEvent;
  120305. if (window.navigator.msPointerEnabled) {
  120306. var tp = window.navigator.msMaxTouchPoints;
  120307. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  120308. value: tp,
  120309. enumerable: true
  120310. });
  120311. dispatcher.registerSource('ms', msEvents);
  120312. } else {
  120313. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  120314. value: 0,
  120315. enumerable: true
  120316. });
  120317. dispatcher.registerSource('mouse', mouseEvents);
  120318. if (window.ontouchstart !== undefined) {
  120319. dispatcher.registerSource('touch', touchEvents);
  120320. }
  120321. }
  120322. dispatcher.register(document);
  120323. }
  120324. }
  120325. var n = window.navigator;
  120326. var s;
  120327. var r;
  120328. var h;
  120329. function assertActive(id) {
  120330. if (!dispatcher.pointermap.has(id)) {
  120331. var error = new Error('InvalidPointerId');
  120332. error.name = 'InvalidPointerId';
  120333. throw error;
  120334. }
  120335. }
  120336. function assertConnected(elem) {
  120337. var parent = elem.parentNode;
  120338. while (parent && parent !== elem.ownerDocument) {
  120339. parent = parent.parentNode;
  120340. }
  120341. if (!parent) {
  120342. var error = new Error('InvalidStateError');
  120343. error.name = 'InvalidStateError';
  120344. throw error;
  120345. }
  120346. }
  120347. function inActiveButtonState(id) {
  120348. var p = dispatcher.pointermap.get(id);
  120349. return p.buttons !== 0;
  120350. }
  120351. if (n.msPointerEnabled) {
  120352. s = function(pointerId) {
  120353. assertActive(pointerId);
  120354. assertConnected(this);
  120355. if (inActiveButtonState(pointerId)) {
  120356. dispatcher.setCapture(pointerId, this, true);
  120357. this.msSetPointerCapture(pointerId);
  120358. }
  120359. };
  120360. r = function(pointerId) {
  120361. assertActive(pointerId);
  120362. dispatcher.releaseCapture(pointerId, true);
  120363. this.msReleasePointerCapture(pointerId);
  120364. };
  120365. } else {
  120366. s = function setPointerCapture(pointerId) {
  120367. assertActive(pointerId);
  120368. assertConnected(this);
  120369. if (inActiveButtonState(pointerId)) {
  120370. dispatcher.setCapture(pointerId, this);
  120371. }
  120372. };
  120373. r = function releasePointerCapture(pointerId) {
  120374. assertActive(pointerId);
  120375. dispatcher.releaseCapture(pointerId);
  120376. };
  120377. }
  120378. h = function hasPointerCapture(pointerId) {
  120379. return !!dispatcher.captureInfo[pointerId];
  120380. };
  120381. function applyPolyfill$1() {
  120382. if (window.Element && !Element.prototype.setPointerCapture) {
  120383. Object.defineProperties(Element.prototype, {
  120384. 'setPointerCapture': {
  120385. value: s
  120386. },
  120387. 'releasePointerCapture': {
  120388. value: r
  120389. },
  120390. 'hasPointerCapture': {
  120391. value: h
  120392. }
  120393. });
  120394. }
  120395. }
  120396. applyAttributeStyles();
  120397. applyPolyfill();
  120398. applyPolyfill$1();
  120399. var pointerevents = {
  120400. dispatcher: dispatcher,
  120401. Installer: Installer,
  120402. PointerEvent: PointerEvent,
  120403. PointerMap: PointerMap,
  120404. targetFinding: targeting
  120405. };
  120406. return pointerevents;
  120407. }));
  120408. /***/ }),
  120409. /* 65 */
  120410. /***/ (function(module, exports, __webpack_require__) {
  120411. "use strict";
  120412. Object.defineProperty(exports, "__esModule", { value: true });
  120413. var defaultViewer_1 = __webpack_require__(8);
  120414. var mappers_1 = __webpack_require__(3);
  120415. var globals_1 = __webpack_require__(4);
  120416. /**
  120417. * Will attach an init function the the DOMContentLoaded event.
  120418. * The init function will be removed automatically after the event was triggered.
  120419. */
  120420. function initListeners() {
  120421. document.addEventListener("DOMContentLoaded", init);
  120422. function init(event) {
  120423. document.removeEventListener("DOMContentLoaded", init);
  120424. if (globals_1.viewerGlobals.disableInit)
  120425. return;
  120426. InitTags();
  120427. }
  120428. }
  120429. exports.initListeners = initListeners;
  120430. /**
  120431. * Select all HTML tags on the page that match the selector and initialize a viewer
  120432. *
  120433. * @param selector the selector to initialize the viewer on (default is 'babylon')
  120434. */
  120435. function InitTags(selector) {
  120436. if (selector === void 0) { selector = 'babylon'; }
  120437. var elements = document.querySelectorAll(selector);
  120438. for (var i = 0; i < elements.length; ++i) {
  120439. var element = elements.item(i);
  120440. // get the html configuration
  120441. var configMapper = mappers_1.mapperManager.getMapper('dom');
  120442. var config = configMapper.map(element);
  120443. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  120444. }
  120445. }
  120446. exports.InitTags = InitTags;
  120447. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQzt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